Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(372)

Side by Side Diff: packages/web_components/lib/HTMLImports.js

Issue 2312183003: Removed Polymer from Observatory deps (Closed)
Patch Set: Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /**
2 * @license
3 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
4 * This code may only be used under the BSD style license found at http://polyme r.github.io/LICENSE.txt
5 * The complete set of authors may be found at http://polymer.github.io/AUTHORS. txt
6 * The complete set of contributors may be found at http://polymer.github.io/CON TRIBUTORS.txt
7 * Code distributed by Google as part of the polymer project is also
8 * subject to an additional IP rights grant found at http://polymer.github.io/PA TENTS.txt
9 */
10 // @version 0.7.21
11 if (typeof WeakMap === "undefined") {
12 (function() {
13 var defineProperty = Object.defineProperty;
14 var counter = Date.now() % 1e9;
15 var WeakMap = function() {
16 this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__");
17 };
18 WeakMap.prototype = {
19 set: function(key, value) {
20 var entry = key[this.name];
21 if (entry && entry[0] === key) entry[1] = value; else defineProperty(key , this.name, {
22 value: [ key, value ],
23 writable: true
24 });
25 return this;
26 },
27 get: function(key) {
28 var entry;
29 return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefin ed;
30 },
31 "delete": function(key) {
32 var entry = key[this.name];
33 if (!entry || entry[0] !== key) return false;
34 entry[0] = entry[1] = undefined;
35 return true;
36 },
37 has: function(key) {
38 var entry = key[this.name];
39 if (!entry) return false;
40 return entry[0] === key;
41 }
42 };
43 window.WeakMap = WeakMap;
44 })();
45 }
46
47 (function(global) {
48 if (global.JsMutationObserver) {
49 return;
50 }
51 var registrationsTable = new WeakMap();
52 var setImmediate;
53 if (/Trident|Edge/.test(navigator.userAgent)) {
54 setImmediate = setTimeout;
55 } else if (window.setImmediate) {
56 setImmediate = window.setImmediate;
57 } else {
58 var setImmediateQueue = [];
59 var sentinel = String(Math.random());
60 window.addEventListener("message", function(e) {
61 if (e.data === sentinel) {
62 var queue = setImmediateQueue;
63 setImmediateQueue = [];
64 queue.forEach(function(func) {
65 func();
66 });
67 }
68 });
69 setImmediate = function(func) {
70 setImmediateQueue.push(func);
71 window.postMessage(sentinel, "*");
72 };
73 }
74 var isScheduled = false;
75 var scheduledObservers = [];
76 function scheduleCallback(observer) {
77 scheduledObservers.push(observer);
78 if (!isScheduled) {
79 isScheduled = true;
80 setImmediate(dispatchCallbacks);
81 }
82 }
83 function wrapIfNeeded(node) {
84 return window.ShadowDOMPolyfill && window.ShadowDOMPolyfill.wrapIfNeeded(nod e) || node;
85 }
86 function dispatchCallbacks() {
87 isScheduled = false;
88 var observers = scheduledObservers;
89 scheduledObservers = [];
90 observers.sort(function(o1, o2) {
91 return o1.uid_ - o2.uid_;
92 });
93 var anyNonEmpty = false;
94 observers.forEach(function(observer) {
95 var queue = observer.takeRecords();
96 removeTransientObserversFor(observer);
97 if (queue.length) {
98 observer.callback_(queue, observer);
99 anyNonEmpty = true;
100 }
101 });
102 if (anyNonEmpty) dispatchCallbacks();
103 }
104 function removeTransientObserversFor(observer) {
105 observer.nodes_.forEach(function(node) {
106 var registrations = registrationsTable.get(node);
107 if (!registrations) return;
108 registrations.forEach(function(registration) {
109 if (registration.observer === observer) registration.removeTransientObse rvers();
110 });
111 });
112 }
113 function forEachAncestorAndObserverEnqueueRecord(target, callback) {
114 for (var node = target; node; node = node.parentNode) {
115 var registrations = registrationsTable.get(node);
116 if (registrations) {
117 for (var j = 0; j < registrations.length; j++) {
118 var registration = registrations[j];
119 var options = registration.options;
120 if (node !== target && !options.subtree) continue;
121 var record = callback(options);
122 if (record) registration.enqueue(record);
123 }
124 }
125 }
126 }
127 var uidCounter = 0;
128 function JsMutationObserver(callback) {
129 this.callback_ = callback;
130 this.nodes_ = [];
131 this.records_ = [];
132 this.uid_ = ++uidCounter;
133 }
134 JsMutationObserver.prototype = {
135 observe: function(target, options) {
136 target = wrapIfNeeded(target);
137 if (!options.childList && !options.attributes && !options.characterData || options.attributeOldValue && !options.attributes || options.attributeFilter && options.attributeFilter.length && !options.attributes || options.characterDataOl dValue && !options.characterData) {
138 throw new SyntaxError();
139 }
140 var registrations = registrationsTable.get(target);
141 if (!registrations) registrationsTable.set(target, registrations = []);
142 var registration;
143 for (var i = 0; i < registrations.length; i++) {
144 if (registrations[i].observer === this) {
145 registration = registrations[i];
146 registration.removeListeners();
147 registration.options = options;
148 break;
149 }
150 }
151 if (!registration) {
152 registration = new Registration(this, target, options);
153 registrations.push(registration);
154 this.nodes_.push(target);
155 }
156 registration.addListeners();
157 },
158 disconnect: function() {
159 this.nodes_.forEach(function(node) {
160 var registrations = registrationsTable.get(node);
161 for (var i = 0; i < registrations.length; i++) {
162 var registration = registrations[i];
163 if (registration.observer === this) {
164 registration.removeListeners();
165 registrations.splice(i, 1);
166 break;
167 }
168 }
169 }, this);
170 this.records_ = [];
171 },
172 takeRecords: function() {
173 var copyOfRecords = this.records_;
174 this.records_ = [];
175 return copyOfRecords;
176 }
177 };
178 function MutationRecord(type, target) {
179 this.type = type;
180 this.target = target;
181 this.addedNodes = [];
182 this.removedNodes = [];
183 this.previousSibling = null;
184 this.nextSibling = null;
185 this.attributeName = null;
186 this.attributeNamespace = null;
187 this.oldValue = null;
188 }
189 function copyMutationRecord(original) {
190 var record = new MutationRecord(original.type, original.target);
191 record.addedNodes = original.addedNodes.slice();
192 record.removedNodes = original.removedNodes.slice();
193 record.previousSibling = original.previousSibling;
194 record.nextSibling = original.nextSibling;
195 record.attributeName = original.attributeName;
196 record.attributeNamespace = original.attributeNamespace;
197 record.oldValue = original.oldValue;
198 return record;
199 }
200 var currentRecord, recordWithOldValue;
201 function getRecord(type, target) {
202 return currentRecord = new MutationRecord(type, target);
203 }
204 function getRecordWithOldValue(oldValue) {
205 if (recordWithOldValue) return recordWithOldValue;
206 recordWithOldValue = copyMutationRecord(currentRecord);
207 recordWithOldValue.oldValue = oldValue;
208 return recordWithOldValue;
209 }
210 function clearRecords() {
211 currentRecord = recordWithOldValue = undefined;
212 }
213 function recordRepresentsCurrentMutation(record) {
214 return record === recordWithOldValue || record === currentRecord;
215 }
216 function selectRecord(lastRecord, newRecord) {
217 if (lastRecord === newRecord) return lastRecord;
218 if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) retur n recordWithOldValue;
219 return null;
220 }
221 function Registration(observer, target, options) {
222 this.observer = observer;
223 this.target = target;
224 this.options = options;
225 this.transientObservedNodes = [];
226 }
227 Registration.prototype = {
228 enqueue: function(record) {
229 var records = this.observer.records_;
230 var length = records.length;
231 if (records.length > 0) {
232 var lastRecord = records[length - 1];
233 var recordToReplaceLast = selectRecord(lastRecord, record);
234 if (recordToReplaceLast) {
235 records[length - 1] = recordToReplaceLast;
236 return;
237 }
238 } else {
239 scheduleCallback(this.observer);
240 }
241 records[length] = record;
242 },
243 addListeners: function() {
244 this.addListeners_(this.target);
245 },
246 addListeners_: function(node) {
247 var options = this.options;
248 if (options.attributes) node.addEventListener("DOMAttrModified", this, tru e);
249 if (options.characterData) node.addEventListener("DOMCharacterDataModified ", this, true);
250 if (options.childList) node.addEventListener("DOMNodeInserted", this, true );
251 if (options.childList || options.subtree) node.addEventListener("DOMNodeRe moved", this, true);
252 },
253 removeListeners: function() {
254 this.removeListeners_(this.target);
255 },
256 removeListeners_: function(node) {
257 var options = this.options;
258 if (options.attributes) node.removeEventListener("DOMAttrModified", this, true);
259 if (options.characterData) node.removeEventListener("DOMCharacterDataModif ied", this, true);
260 if (options.childList) node.removeEventListener("DOMNodeInserted", this, t rue);
261 if (options.childList || options.subtree) node.removeEventListener("DOMNod eRemoved", this, true);
262 },
263 addTransientObserver: function(node) {
264 if (node === this.target) return;
265 this.addListeners_(node);
266 this.transientObservedNodes.push(node);
267 var registrations = registrationsTable.get(node);
268 if (!registrations) registrationsTable.set(node, registrations = []);
269 registrations.push(this);
270 },
271 removeTransientObservers: function() {
272 var transientObservedNodes = this.transientObservedNodes;
273 this.transientObservedNodes = [];
274 transientObservedNodes.forEach(function(node) {
275 this.removeListeners_(node);
276 var registrations = registrationsTable.get(node);
277 for (var i = 0; i < registrations.length; i++) {
278 if (registrations[i] === this) {
279 registrations.splice(i, 1);
280 break;
281 }
282 }
283 }, this);
284 },
285 handleEvent: function(e) {
286 e.stopImmediatePropagation();
287 switch (e.type) {
288 case "DOMAttrModified":
289 var name = e.attrName;
290 var namespace = e.relatedNode.namespaceURI;
291 var target = e.target;
292 var record = new getRecord("attributes", target);
293 record.attributeName = name;
294 record.attributeNamespace = namespace;
295 var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevVa lue;
296 forEachAncestorAndObserverEnqueueRecord(target, function(options) {
297 if (!options.attributes) return;
298 if (options.attributeFilter && options.attributeFilter.length && optio ns.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(names pace) === -1) {
299 return;
300 }
301 if (options.attributeOldValue) return getRecordWithOldValue(oldValue);
302 return record;
303 });
304 break;
305
306 case "DOMCharacterDataModified":
307 var target = e.target;
308 var record = getRecord("characterData", target);
309 var oldValue = e.prevValue;
310 forEachAncestorAndObserverEnqueueRecord(target, function(options) {
311 if (!options.characterData) return;
312 if (options.characterDataOldValue) return getRecordWithOldValue(oldVal ue);
313 return record;
314 });
315 break;
316
317 case "DOMNodeRemoved":
318 this.addTransientObserver(e.target);
319
320 case "DOMNodeInserted":
321 var changedNode = e.target;
322 var addedNodes, removedNodes;
323 if (e.type === "DOMNodeInserted") {
324 addedNodes = [ changedNode ];
325 removedNodes = [];
326 } else {
327 addedNodes = [];
328 removedNodes = [ changedNode ];
329 }
330 var previousSibling = changedNode.previousSibling;
331 var nextSibling = changedNode.nextSibling;
332 var record = getRecord("childList", e.target.parentNode);
333 record.addedNodes = addedNodes;
334 record.removedNodes = removedNodes;
335 record.previousSibling = previousSibling;
336 record.nextSibling = nextSibling;
337 forEachAncestorAndObserverEnqueueRecord(e.relatedNode, function(options) {
338 if (!options.childList) return;
339 return record;
340 });
341 }
342 clearRecords();
343 }
344 };
345 global.JsMutationObserver = JsMutationObserver;
346 if (!global.MutationObserver) {
347 global.MutationObserver = JsMutationObserver;
348 JsMutationObserver._isPolyfilled = true;
349 }
350 })(self);
351
352 (function(scope) {
353 "use strict";
354 if (!window.performance) {
355 var start = Date.now();
356 window.performance = {
357 now: function() {
358 return Date.now() - start;
359 }
360 };
361 }
362 if (!window.requestAnimationFrame) {
363 window.requestAnimationFrame = function() {
364 var nativeRaf = window.webkitRequestAnimationFrame || window.mozRequestAni mationFrame;
365 return nativeRaf ? function(callback) {
366 return nativeRaf(function() {
367 callback(performance.now());
368 });
369 } : function(callback) {
370 return window.setTimeout(callback, 1e3 / 60);
371 };
372 }();
373 }
374 if (!window.cancelAnimationFrame) {
375 window.cancelAnimationFrame = function() {
376 return window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || function(id) {
377 clearTimeout(id);
378 };
379 }();
380 }
381 var workingDefaultPrevented = function() {
382 var e = document.createEvent("Event");
383 e.initEvent("foo", true, true);
384 e.preventDefault();
385 return e.defaultPrevented;
386 }();
387 if (!workingDefaultPrevented) {
388 var origPreventDefault = Event.prototype.preventDefault;
389 Event.prototype.preventDefault = function() {
390 if (!this.cancelable) {
391 return;
392 }
393 origPreventDefault.call(this);
394 Object.defineProperty(this, "defaultPrevented", {
395 get: function() {
396 return true;
397 },
398 configurable: true
399 });
400 };
401 }
402 var isIE = /Trident/.test(navigator.userAgent);
403 if (!window.CustomEvent || isIE && typeof window.CustomEvent !== "function") {
404 window.CustomEvent = function(inType, params) {
405 params = params || {};
406 var e = document.createEvent("CustomEvent");
407 e.initCustomEvent(inType, Boolean(params.bubbles), Boolean(params.cancelab le), params.detail);
408 return e;
409 };
410 window.CustomEvent.prototype = window.Event.prototype;
411 }
412 if (!window.Event || isIE && typeof window.Event !== "function") {
413 var origEvent = window.Event;
414 window.Event = function(inType, params) {
415 params = params || {};
416 var e = document.createEvent("Event");
417 e.initEvent(inType, Boolean(params.bubbles), Boolean(params.cancelable));
418 return e;
419 };
420 window.Event.prototype = origEvent.prototype;
421 }
422 })(window.WebComponents);
423
424 window.HTMLImports = window.HTMLImports || {
425 flags: {}
426 };
427
428 (function(scope) {
429 var IMPORT_LINK_TYPE = "import";
430 var useNative = Boolean(IMPORT_LINK_TYPE in document.createElement("link"));
431 var hasShadowDOMPolyfill = Boolean(window.ShadowDOMPolyfill);
432 var wrap = function(node) {
433 return hasShadowDOMPolyfill ? window.ShadowDOMPolyfill.wrapIfNeeded(node) : node;
434 };
435 var rootDocument = wrap(document);
436 var currentScriptDescriptor = {
437 get: function() {
438 var script = window.HTMLImports.currentScript || document.currentScript || (document.readyState !== "complete" ? document.scripts[document.scripts.length - 1] : null);
439 return wrap(script);
440 },
441 configurable: true
442 };
443 Object.defineProperty(document, "_currentScript", currentScriptDescriptor);
444 Object.defineProperty(rootDocument, "_currentScript", currentScriptDescriptor) ;
445 var isIE = /Trident/.test(navigator.userAgent);
446 function whenReady(callback, doc) {
447 doc = doc || rootDocument;
448 whenDocumentReady(function() {
449 watchImportsLoad(callback, doc);
450 }, doc);
451 }
452 var requiredReadyState = isIE ? "complete" : "interactive";
453 var READY_EVENT = "readystatechange";
454 function isDocumentReady(doc) {
455 return doc.readyState === "complete" || doc.readyState === requiredReadyStat e;
456 }
457 function whenDocumentReady(callback, doc) {
458 if (!isDocumentReady(doc)) {
459 var checkReady = function() {
460 if (doc.readyState === "complete" || doc.readyState === requiredReadySta te) {
461 doc.removeEventListener(READY_EVENT, checkReady);
462 whenDocumentReady(callback, doc);
463 }
464 };
465 doc.addEventListener(READY_EVENT, checkReady);
466 } else if (callback) {
467 callback();
468 }
469 }
470 function markTargetLoaded(event) {
471 event.target.__loaded = true;
472 }
473 function watchImportsLoad(callback, doc) {
474 var imports = doc.querySelectorAll("link[rel=import]");
475 var parsedCount = 0, importCount = imports.length, newImports = [], errorImp orts = [];
476 function checkDone() {
477 if (parsedCount == importCount && callback) {
478 callback({
479 allImports: imports,
480 loadedImports: newImports,
481 errorImports: errorImports
482 });
483 }
484 }
485 function loadedImport(e) {
486 markTargetLoaded(e);
487 newImports.push(this);
488 parsedCount++;
489 checkDone();
490 }
491 function errorLoadingImport(e) {
492 errorImports.push(this);
493 parsedCount++;
494 checkDone();
495 }
496 if (importCount) {
497 for (var i = 0, imp; i < importCount && (imp = imports[i]); i++) {
498 if (isImportLoaded(imp)) {
499 newImports.push(this);
500 parsedCount++;
501 checkDone();
502 } else {
503 imp.addEventListener("load", loadedImport);
504 imp.addEventListener("error", errorLoadingImport);
505 }
506 }
507 } else {
508 checkDone();
509 }
510 }
511 function isImportLoaded(link) {
512 return useNative ? link.__loaded || link.import && link.import.readyState != = "loading" : link.__importParsed;
513 }
514 if (useNative) {
515 new MutationObserver(function(mxns) {
516 for (var i = 0, l = mxns.length, m; i < l && (m = mxns[i]); i++) {
517 if (m.addedNodes) {
518 handleImports(m.addedNodes);
519 }
520 }
521 }).observe(document.head, {
522 childList: true
523 });
524 function handleImports(nodes) {
525 for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
526 if (isImport(n)) {
527 handleImport(n);
528 }
529 }
530 }
531 function isImport(element) {
532 return element.localName === "link" && element.rel === "import";
533 }
534 function handleImport(element) {
535 var loaded = element.import;
536 if (loaded) {
537 markTargetLoaded({
538 target: element
539 });
540 } else {
541 element.addEventListener("load", markTargetLoaded);
542 element.addEventListener("error", markTargetLoaded);
543 }
544 }
545 (function() {
546 if (document.readyState === "loading") {
547 var imports = document.querySelectorAll("link[rel=import]");
548 for (var i = 0, l = imports.length, imp; i < l && (imp = imports[i]); i+ +) {
549 handleImport(imp);
550 }
551 }
552 })();
553 }
554 whenReady(function(detail) {
555 window.HTMLImports.ready = true;
556 window.HTMLImports.readyTime = new Date().getTime();
557 var evt = rootDocument.createEvent("CustomEvent");
558 evt.initCustomEvent("HTMLImportsLoaded", true, true, detail);
559 rootDocument.dispatchEvent(evt);
560 });
561 scope.IMPORT_LINK_TYPE = IMPORT_LINK_TYPE;
562 scope.useNative = useNative;
563 scope.rootDocument = rootDocument;
564 scope.whenReady = whenReady;
565 scope.isIE = isIE;
566 })(window.HTMLImports);
567
568 (function(scope) {
569 var modules = [];
570 var addModule = function(module) {
571 modules.push(module);
572 };
573 var initializeModules = function() {
574 modules.forEach(function(module) {
575 module(scope);
576 });
577 };
578 scope.addModule = addModule;
579 scope.initializeModules = initializeModules;
580 })(window.HTMLImports);
581
582 window.HTMLImports.addModule(function(scope) {
583 var CSS_URL_REGEXP = /(url\()([^)]*)(\))/g;
584 var CSS_IMPORT_REGEXP = /(@import[\s]+(?!url\())([^;]*)(;)/g;
585 var path = {
586 resolveUrlsInStyle: function(style, linkUrl) {
587 var doc = style.ownerDocument;
588 var resolver = doc.createElement("a");
589 style.textContent = this.resolveUrlsInCssText(style.textContent, linkUrl, resolver);
590 return style;
591 },
592 resolveUrlsInCssText: function(cssText, linkUrl, urlObj) {
593 var r = this.replaceUrls(cssText, urlObj, linkUrl, CSS_URL_REGEXP);
594 r = this.replaceUrls(r, urlObj, linkUrl, CSS_IMPORT_REGEXP);
595 return r;
596 },
597 replaceUrls: function(text, urlObj, linkUrl, regexp) {
598 return text.replace(regexp, function(m, pre, url, post) {
599 var urlPath = url.replace(/["']/g, "");
600 if (linkUrl) {
601 urlPath = new URL(urlPath, linkUrl).href;
602 }
603 urlObj.href = urlPath;
604 urlPath = urlObj.href;
605 return pre + "'" + urlPath + "'" + post;
606 });
607 }
608 };
609 scope.path = path;
610 });
611
612 window.HTMLImports.addModule(function(scope) {
613 var xhr = {
614 async: true,
615 ok: function(request) {
616 return request.status >= 200 && request.status < 300 || request.status === 304 || request.status === 0;
617 },
618 load: function(url, next, nextContext) {
619 var request = new XMLHttpRequest();
620 if (scope.flags.debug || scope.flags.bust) {
621 url += "?" + Math.random();
622 }
623 request.open("GET", url, xhr.async);
624 request.addEventListener("readystatechange", function(e) {
625 if (request.readyState === 4) {
626 var redirectedUrl = null;
627 try {
628 var locationHeader = request.getResponseHeader("Location");
629 if (locationHeader) {
630 redirectedUrl = locationHeader.substr(0, 1) === "/" ? location.ori gin + locationHeader : locationHeader;
631 }
632 } catch (e) {
633 console.error(e.message);
634 }
635 next.call(nextContext, !xhr.ok(request) && request, request.response | | request.responseText, redirectedUrl);
636 }
637 });
638 request.send();
639 return request;
640 },
641 loadDocument: function(url, next, nextContext) {
642 this.load(url, next, nextContext).responseType = "document";
643 }
644 };
645 scope.xhr = xhr;
646 });
647
648 window.HTMLImports.addModule(function(scope) {
649 var xhr = scope.xhr;
650 var flags = scope.flags;
651 var Loader = function(onLoad, onComplete) {
652 this.cache = {};
653 this.onload = onLoad;
654 this.oncomplete = onComplete;
655 this.inflight = 0;
656 this.pending = {};
657 };
658 Loader.prototype = {
659 addNodes: function(nodes) {
660 this.inflight += nodes.length;
661 for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
662 this.require(n);
663 }
664 this.checkDone();
665 },
666 addNode: function(node) {
667 this.inflight++;
668 this.require(node);
669 this.checkDone();
670 },
671 require: function(elt) {
672 var url = elt.src || elt.href;
673 elt.__nodeUrl = url;
674 if (!this.dedupe(url, elt)) {
675 this.fetch(url, elt);
676 }
677 },
678 dedupe: function(url, elt) {
679 if (this.pending[url]) {
680 this.pending[url].push(elt);
681 return true;
682 }
683 var resource;
684 if (this.cache[url]) {
685 this.onload(url, elt, this.cache[url]);
686 this.tail();
687 return true;
688 }
689 this.pending[url] = [ elt ];
690 return false;
691 },
692 fetch: function(url, elt) {
693 flags.load && console.log("fetch", url, elt);
694 if (!url) {
695 setTimeout(function() {
696 this.receive(url, elt, {
697 error: "href must be specified"
698 }, null);
699 }.bind(this), 0);
700 } else if (url.match(/^data:/)) {
701 var pieces = url.split(",");
702 var header = pieces[0];
703 var body = pieces[1];
704 if (header.indexOf(";base64") > -1) {
705 body = atob(body);
706 } else {
707 body = decodeURIComponent(body);
708 }
709 setTimeout(function() {
710 this.receive(url, elt, null, body);
711 }.bind(this), 0);
712 } else {
713 var receiveXhr = function(err, resource, redirectedUrl) {
714 this.receive(url, elt, err, resource, redirectedUrl);
715 }.bind(this);
716 xhr.load(url, receiveXhr);
717 }
718 },
719 receive: function(url, elt, err, resource, redirectedUrl) {
720 this.cache[url] = resource;
721 var $p = this.pending[url];
722 for (var i = 0, l = $p.length, p; i < l && (p = $p[i]); i++) {
723 this.onload(url, p, resource, err, redirectedUrl);
724 this.tail();
725 }
726 this.pending[url] = null;
727 },
728 tail: function() {
729 --this.inflight;
730 this.checkDone();
731 },
732 checkDone: function() {
733 if (!this.inflight) {
734 this.oncomplete();
735 }
736 }
737 };
738 scope.Loader = Loader;
739 });
740
741 window.HTMLImports.addModule(function(scope) {
742 var Observer = function(addCallback) {
743 this.addCallback = addCallback;
744 this.mo = new MutationObserver(this.handler.bind(this));
745 };
746 Observer.prototype = {
747 handler: function(mutations) {
748 for (var i = 0, l = mutations.length, m; i < l && (m = mutations[i]); i++) {
749 if (m.type === "childList" && m.addedNodes.length) {
750 this.addedNodes(m.addedNodes);
751 }
752 }
753 },
754 addedNodes: function(nodes) {
755 if (this.addCallback) {
756 this.addCallback(nodes);
757 }
758 for (var i = 0, l = nodes.length, n, loading; i < l && (n = nodes[i]); i++ ) {
759 if (n.children && n.children.length) {
760 this.addedNodes(n.children);
761 }
762 }
763 },
764 observe: function(root) {
765 this.mo.observe(root, {
766 childList: true,
767 subtree: true
768 });
769 }
770 };
771 scope.Observer = Observer;
772 });
773
774 window.HTMLImports.addModule(function(scope) {
775 var path = scope.path;
776 var rootDocument = scope.rootDocument;
777 var flags = scope.flags;
778 var isIE = scope.isIE;
779 var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
780 var IMPORT_SELECTOR = "link[rel=" + IMPORT_LINK_TYPE + "]";
781 var importParser = {
782 documentSelectors: IMPORT_SELECTOR,
783 importsSelectors: [ IMPORT_SELECTOR, "link[rel=stylesheet]:not([type])", "st yle:not([type])", "script:not([type])", 'script[type="application/javascript"]', 'script[type="text/javascript"]' ].join(","),
784 map: {
785 link: "parseLink",
786 script: "parseScript",
787 style: "parseStyle"
788 },
789 dynamicElements: [],
790 parseNext: function() {
791 var next = this.nextToParse();
792 if (next) {
793 this.parse(next);
794 }
795 },
796 parse: function(elt) {
797 if (this.isParsed(elt)) {
798 flags.parse && console.log("[%s] is already parsed", elt.localName);
799 return;
800 }
801 var fn = this[this.map[elt.localName]];
802 if (fn) {
803 this.markParsing(elt);
804 fn.call(this, elt);
805 }
806 },
807 parseDynamic: function(elt, quiet) {
808 this.dynamicElements.push(elt);
809 if (!quiet) {
810 this.parseNext();
811 }
812 },
813 markParsing: function(elt) {
814 flags.parse && console.log("parsing", elt);
815 this.parsingElement = elt;
816 },
817 markParsingComplete: function(elt) {
818 elt.__importParsed = true;
819 this.markDynamicParsingComplete(elt);
820 if (elt.__importElement) {
821 elt.__importElement.__importParsed = true;
822 this.markDynamicParsingComplete(elt.__importElement);
823 }
824 this.parsingElement = null;
825 flags.parse && console.log("completed", elt);
826 },
827 markDynamicParsingComplete: function(elt) {
828 var i = this.dynamicElements.indexOf(elt);
829 if (i >= 0) {
830 this.dynamicElements.splice(i, 1);
831 }
832 },
833 parseImport: function(elt) {
834 elt.import = elt.__doc;
835 if (window.HTMLImports.__importsParsingHook) {
836 window.HTMLImports.__importsParsingHook(elt);
837 }
838 if (elt.import) {
839 elt.import.__importParsed = true;
840 }
841 this.markParsingComplete(elt);
842 if (elt.__resource && !elt.__error) {
843 elt.dispatchEvent(new CustomEvent("load", {
844 bubbles: false
845 }));
846 } else {
847 elt.dispatchEvent(new CustomEvent("error", {
848 bubbles: false
849 }));
850 }
851 if (elt.__pending) {
852 var fn;
853 while (elt.__pending.length) {
854 fn = elt.__pending.shift();
855 if (fn) {
856 fn({
857 target: elt
858 });
859 }
860 }
861 }
862 this.parseNext();
863 },
864 parseLink: function(linkElt) {
865 if (nodeIsImport(linkElt)) {
866 this.parseImport(linkElt);
867 } else {
868 linkElt.href = linkElt.href;
869 this.parseGeneric(linkElt);
870 }
871 },
872 parseStyle: function(elt) {
873 var src = elt;
874 elt = cloneStyle(elt);
875 src.__appliedElement = elt;
876 elt.__importElement = src;
877 this.parseGeneric(elt);
878 },
879 parseGeneric: function(elt) {
880 this.trackElement(elt);
881 this.addElementToDocument(elt);
882 },
883 rootImportForElement: function(elt) {
884 var n = elt;
885 while (n.ownerDocument.__importLink) {
886 n = n.ownerDocument.__importLink;
887 }
888 return n;
889 },
890 addElementToDocument: function(elt) {
891 var port = this.rootImportForElement(elt.__importElement || elt);
892 port.parentNode.insertBefore(elt, port);
893 },
894 trackElement: function(elt, callback) {
895 var self = this;
896 var done = function(e) {
897 elt.removeEventListener("load", done);
898 elt.removeEventListener("error", done);
899 if (callback) {
900 callback(e);
901 }
902 self.markParsingComplete(elt);
903 self.parseNext();
904 };
905 elt.addEventListener("load", done);
906 elt.addEventListener("error", done);
907 if (isIE && elt.localName === "style") {
908 var fakeLoad = false;
909 if (elt.textContent.indexOf("@import") == -1) {
910 fakeLoad = true;
911 } else if (elt.sheet) {
912 fakeLoad = true;
913 var csr = elt.sheet.cssRules;
914 var len = csr ? csr.length : 0;
915 for (var i = 0, r; i < len && (r = csr[i]); i++) {
916 if (r.type === CSSRule.IMPORT_RULE) {
917 fakeLoad = fakeLoad && Boolean(r.styleSheet);
918 }
919 }
920 }
921 if (fakeLoad) {
922 setTimeout(function() {
923 elt.dispatchEvent(new CustomEvent("load", {
924 bubbles: false
925 }));
926 });
927 }
928 }
929 },
930 parseScript: function(scriptElt) {
931 var script = document.createElement("script");
932 script.__importElement = scriptElt;
933 script.src = scriptElt.src ? scriptElt.src : generateScriptDataUrl(scriptE lt);
934 scope.currentScript = scriptElt;
935 this.trackElement(script, function(e) {
936 if (script.parentNode) {
937 script.parentNode.removeChild(script);
938 }
939 scope.currentScript = null;
940 });
941 this.addElementToDocument(script);
942 },
943 nextToParse: function() {
944 this._mayParse = [];
945 return !this.parsingElement && (this.nextToParseInDoc(rootDocument) || thi s.nextToParseDynamic());
946 },
947 nextToParseInDoc: function(doc, link) {
948 if (doc && this._mayParse.indexOf(doc) < 0) {
949 this._mayParse.push(doc);
950 var nodes = doc.querySelectorAll(this.parseSelectorsForNode(doc));
951 for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
952 if (!this.isParsed(n)) {
953 if (this.hasResource(n)) {
954 return nodeIsImport(n) ? this.nextToParseInDoc(n.__doc, n) : n;
955 } else {
956 return;
957 }
958 }
959 }
960 }
961 return link;
962 },
963 nextToParseDynamic: function() {
964 return this.dynamicElements[0];
965 },
966 parseSelectorsForNode: function(node) {
967 var doc = node.ownerDocument || node;
968 return doc === rootDocument ? this.documentSelectors : this.importsSelecto rs;
969 },
970 isParsed: function(node) {
971 return node.__importParsed;
972 },
973 needsDynamicParsing: function(elt) {
974 return this.dynamicElements.indexOf(elt) >= 0;
975 },
976 hasResource: function(node) {
977 if (nodeIsImport(node) && node.__doc === undefined) {
978 return false;
979 }
980 return true;
981 }
982 };
983 function nodeIsImport(elt) {
984 return elt.localName === "link" && elt.rel === IMPORT_LINK_TYPE;
985 }
986 function generateScriptDataUrl(script) {
987 var scriptContent = generateScriptContent(script);
988 return "data:text/javascript;charset=utf-8," + encodeURIComponent(scriptCont ent);
989 }
990 function generateScriptContent(script) {
991 return script.textContent + generateSourceMapHint(script);
992 }
993 function generateSourceMapHint(script) {
994 var owner = script.ownerDocument;
995 owner.__importedScripts = owner.__importedScripts || 0;
996 var moniker = script.ownerDocument.baseURI;
997 var num = owner.__importedScripts ? "-" + owner.__importedScripts : "";
998 owner.__importedScripts++;
999 return "\n//# sourceURL=" + moniker + num + ".js\n";
1000 }
1001 function cloneStyle(style) {
1002 var clone = style.ownerDocument.createElement("style");
1003 clone.textContent = style.textContent;
1004 path.resolveUrlsInStyle(clone);
1005 return clone;
1006 }
1007 scope.parser = importParser;
1008 scope.IMPORT_SELECTOR = IMPORT_SELECTOR;
1009 });
1010
1011 window.HTMLImports.addModule(function(scope) {
1012 var flags = scope.flags;
1013 var IMPORT_LINK_TYPE = scope.IMPORT_LINK_TYPE;
1014 var IMPORT_SELECTOR = scope.IMPORT_SELECTOR;
1015 var rootDocument = scope.rootDocument;
1016 var Loader = scope.Loader;
1017 var Observer = scope.Observer;
1018 var parser = scope.parser;
1019 var importer = {
1020 documents: {},
1021 documentPreloadSelectors: IMPORT_SELECTOR,
1022 importsPreloadSelectors: [ IMPORT_SELECTOR ].join(","),
1023 loadNode: function(node) {
1024 importLoader.addNode(node);
1025 },
1026 loadSubtree: function(parent) {
1027 var nodes = this.marshalNodes(parent);
1028 importLoader.addNodes(nodes);
1029 },
1030 marshalNodes: function(parent) {
1031 return parent.querySelectorAll(this.loadSelectorsForNode(parent));
1032 },
1033 loadSelectorsForNode: function(node) {
1034 var doc = node.ownerDocument || node;
1035 return doc === rootDocument ? this.documentPreloadSelectors : this.imports PreloadSelectors;
1036 },
1037 loaded: function(url, elt, resource, err, redirectedUrl) {
1038 flags.load && console.log("loaded", url, elt);
1039 elt.__resource = resource;
1040 elt.__error = err;
1041 if (isImportLink(elt)) {
1042 var doc = this.documents[url];
1043 if (doc === undefined) {
1044 doc = err ? null : makeDocument(resource, redirectedUrl || url);
1045 if (doc) {
1046 doc.__importLink = elt;
1047 this.bootDocument(doc);
1048 }
1049 this.documents[url] = doc;
1050 }
1051 elt.__doc = doc;
1052 }
1053 parser.parseNext();
1054 },
1055 bootDocument: function(doc) {
1056 this.loadSubtree(doc);
1057 this.observer.observe(doc);
1058 parser.parseNext();
1059 },
1060 loadedAll: function() {
1061 parser.parseNext();
1062 }
1063 };
1064 var importLoader = new Loader(importer.loaded.bind(importer), importer.loadedA ll.bind(importer));
1065 importer.observer = new Observer();
1066 function isImportLink(elt) {
1067 return isLinkRel(elt, IMPORT_LINK_TYPE);
1068 }
1069 function isLinkRel(elt, rel) {
1070 return elt.localName === "link" && elt.getAttribute("rel") === rel;
1071 }
1072 function hasBaseURIAccessor(doc) {
1073 return !!Object.getOwnPropertyDescriptor(doc, "baseURI");
1074 }
1075 function makeDocument(resource, url) {
1076 var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE);
1077 doc._URL = url;
1078 var base = doc.createElement("base");
1079 base.setAttribute("href", url);
1080 if (!doc.baseURI && !hasBaseURIAccessor(doc)) {
1081 Object.defineProperty(doc, "baseURI", {
1082 value: url
1083 });
1084 }
1085 var meta = doc.createElement("meta");
1086 meta.setAttribute("charset", "utf-8");
1087 doc.head.appendChild(meta);
1088 doc.head.appendChild(base);
1089 doc.body.innerHTML = resource;
1090 if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) {
1091 HTMLTemplateElement.bootstrap(doc);
1092 }
1093 return doc;
1094 }
1095 if (!document.baseURI) {
1096 var baseURIDescriptor = {
1097 get: function() {
1098 var base = document.querySelector("base");
1099 return base ? base.href : window.location.href;
1100 },
1101 configurable: true
1102 };
1103 Object.defineProperty(document, "baseURI", baseURIDescriptor);
1104 Object.defineProperty(rootDocument, "baseURI", baseURIDescriptor);
1105 }
1106 scope.importer = importer;
1107 scope.importLoader = importLoader;
1108 });
1109
1110 window.HTMLImports.addModule(function(scope) {
1111 var parser = scope.parser;
1112 var importer = scope.importer;
1113 var dynamic = {
1114 added: function(nodes) {
1115 var owner, parsed, loading;
1116 for (var i = 0, l = nodes.length, n; i < l && (n = nodes[i]); i++) {
1117 if (!owner) {
1118 owner = n.ownerDocument;
1119 parsed = parser.isParsed(owner);
1120 }
1121 loading = this.shouldLoadNode(n);
1122 if (loading) {
1123 importer.loadNode(n);
1124 }
1125 if (this.shouldParseNode(n) && parsed) {
1126 parser.parseDynamic(n, loading);
1127 }
1128 }
1129 },
1130 shouldLoadNode: function(node) {
1131 return node.nodeType === 1 && matches.call(node, importer.loadSelectorsFor Node(node));
1132 },
1133 shouldParseNode: function(node) {
1134 return node.nodeType === 1 && matches.call(node, parser.parseSelectorsForN ode(node));
1135 }
1136 };
1137 importer.observer.addCallback = dynamic.added.bind(dynamic);
1138 var matches = HTMLElement.prototype.matches || HTMLElement.prototype.matchesSe lector || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.m ozMatchesSelector || HTMLElement.prototype.msMatchesSelector;
1139 });
1140
1141 (function(scope) {
1142 var initializeModules = scope.initializeModules;
1143 var isIE = scope.isIE;
1144 if (scope.useNative) {
1145 return;
1146 }
1147 initializeModules();
1148 var rootDocument = scope.rootDocument;
1149 function bootstrap() {
1150 window.HTMLImports.importer.bootDocument(rootDocument);
1151 }
1152 if (document.readyState === "complete" || document.readyState === "interactive " && !window.attachEvent) {
1153 bootstrap();
1154 } else {
1155 document.addEventListener("DOMContentLoaded", bootstrap);
1156 }
1157 })(window.HTMLImports);
OLDNEW
« no previous file with comments | « packages/web_components/lib/CustomElements.min.js ('k') | packages/web_components/lib/HTMLImports.min.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698