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

Side by Side Diff: polymer_0.5.0/bower_components/webcomponentsjs/HTMLImports.js

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

Powered by Google App Engine
This is Rietveld 408576698