-
Notifications
You must be signed in to change notification settings - Fork 1
/
x-tag-components.js
2261 lines (2011 loc) · 65.9 KB
/
x-tag-components.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// We don't use the platform bootstrapper, so fake this stuff.
window.Platform = {};
var logFlags = {};
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is goverened by a BSD-style
* license that can be found in the LICENSE file.
*/
// SideTable is a weak map where possible. If WeakMap is not available the
// association is stored as an expando property.
var SideTable;
// TODO(arv): WeakMap does not allow for Node etc to be keys in Firefox
if (typeof WeakMap !== 'undefined' && navigator.userAgent.indexOf('Firefox/') < 0) {
SideTable = WeakMap;
} else {
(function() {
var defineProperty = Object.defineProperty;
var hasOwnProperty = Object.hasOwnProperty;
var counter = new Date().getTime() % 1e9;
SideTable = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
};
SideTable.prototype = {
set: function(key, value) {
defineProperty(key, this.name, {value: value, writable: true});
},
get: function(key) {
return hasOwnProperty.call(key, this.name) ? key[this.name] : undefined;
},
delete: function(key) {
this.set(key, undefined);
}
}
})();
}
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function() {
// poor man's adapter for template.content on various platform scenarios
window.templateContent = window.templateContent || function(inTemplate) {
return inTemplate.content;
};
// so we can call wrap/unwrap without testing for ShadowDOMPolyfill
window.wrap = window.unwrap = function(n){
return n;
}
window.createShadowRoot = function(inElement) {
return inElement.webkitCreateShadowRoot();
};
window.templateContent = function(inTemplate) {
// if MDV exists, it may need to boostrap this template to reveal content
if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) {
HTMLTemplateElement.bootstrap(inTemplate);
}
// fallback when there is no Shadow DOM polyfill, no MDV polyfill, and no
// native template support
if (!inTemplate.content && !inTemplate._content) {
var frag = document.createDocumentFragment();
while (inTemplate.firstChild) {
frag.appendChild(inTemplate.firstChild);
}
inTemplate._content = frag;
}
return inTemplate.content || inTemplate._content;
};
})();
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function(scope) {
// Old versions of iOS do not have bind.
if (!Function.prototype.bind) {
Function.prototype.bind = function(scope) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var args2 = args.slice();
args2.push.apply(args2, arguments);
return self.apply(scope, args2);
};
};
}
// namespace an import from CustomElements
// TODO(sjmiles): clean up this global
scope.mixin = window.mixin;
})(window.Platform);
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function(scope) {
'use strict';
// polyfill DOMTokenList
// * add/remove: allow these methods to take multiple classNames
// * toggle: add a 2nd argument which forces the given state rather
// than toggling.
var add = DOMTokenList.prototype.add;
var remove = DOMTokenList.prototype.remove;
DOMTokenList.prototype.add = function() {
for (var i = 0; i < arguments.length; i++) {
add.call(this, arguments[i]);
}
};
DOMTokenList.prototype.remove = function() {
for (var i = 0; i < arguments.length; i++) {
remove.call(this, arguments[i]);
}
};
DOMTokenList.prototype.toggle = function(name, bool) {
if (arguments.length == 1) {
bool = !this.contains(name);
}
bool ? this.add(name) : this.remove(name);
};
DOMTokenList.prototype.switch = function(oldName, newName) {
oldName && this.remove(oldName);
newName && this.add(newName);
};
// make forEach work on NodeList
NodeList.prototype.forEach = function(cb, context) {
Array.prototype.slice.call(this).forEach(cb, context);
};
HTMLCollection.prototype.forEach = function(cb, context) {
Array.prototype.slice.call(this).forEach(cb, context);
};
// polyfill performance.now
if (!window.performance) {
var start = Date.now();
// only at millisecond precision
window.performance = {now: function(){ return Date.now() - start }};
}
// polyfill for requestAnimationFrame
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
var nativeRaf = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame;
return nativeRaf ?
function(callback) {
return nativeRaf(function() {
callback(performance.now());
});
} :
function( callback ){
return window.setTimeout(callback, 1000 / 60);
};
})();
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = (function() {
return window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function(id) {
clearTimeout(id);
};
})();
}
// utility
function createDOM(inTagOrNode, inHTML, inAttrs) {
var dom = typeof inTagOrNode == 'string' ?
document.createElement(inTagOrNode) : inTagOrNode.cloneNode(true);
dom.innerHTML = inHTML;
if (inAttrs) {
for (var n in inAttrs) {
dom.setAttribute(n, inAttrs[n]);
}
}
return dom;
}
// exports
scope.createDOM = createDOM;
})(window.Platform);
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
// poor man's adapter for template.content on various platform scenarios
window.templateContent = window.templateContent || function(inTemplate) {
return inTemplate.content;
};
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
(function(scope) {
if (!scope) {
scope = window.HTMLImports = {flags:{}};
}
var IMPORT_LINK_TYPE = 'import';
// highlander object represents a primary document (the argument to 'parse')
// at the root of a tree of documents
var importer = {
documents: {},
cache: {},
preloadSelectors: [
'link[rel=' + IMPORT_LINK_TYPE + ']',
'script[src]',
'link[rel=stylesheet]'
].join(','),
load: function(inDocument, inNext) {
// construct a loader instance
loader = new Loader(importer.loaded, inNext);
// alias the loader cache (for debugging)
loader.cache = importer.cache;
// add nodes from document into loader queue
importer.preload(inDocument);
},
preload: function(inDocument) {
// all preloadable nodes in inDocument
var nodes = inDocument.querySelectorAll(importer.preloadSelectors);
// only load imports from the main document
// TODO(sjmiles): do this by altering the selector list instead
if (inDocument === document) {
nodes = Array.prototype.filter.call(nodes, function(n) {
return isDocumentLink(n);
});
}
// add these nodes to loader's queue
loader.addNodes(nodes);
},
loaded: function(inUrl, inElt, inResource) {
if (isDocumentLink(inElt)) {
var document = importer.documents[inUrl];
// if we've never seen a document at this url
if (!document) {
// generate an HTMLDocument from data
document = makeDocument(inResource, inUrl);
// resolve resource paths relative to host document
path.resolvePathsInHTML(document);
// cache document
importer.documents[inUrl] = document;
// add nodes from this document to the loader queue
importer.preload(document);
}
// store document resource
inElt.content = inElt.__resource = document;
} else {
inElt.__resource = inResource;
// resolve stylesheet resource paths relative to host document
if (isStylesheetLink(inElt)) {
path.resolvePathsInStylesheet(inElt);
}
}
}
};
function isDocumentLink(inElt) {
return isLinkRel(inElt, IMPORT_LINK_TYPE);
}
function isStylesheetLink(inElt) {
return isLinkRel(inElt, 'stylesheet');
}
function isLinkRel(inElt, inRel) {
return (inElt.localName === 'link' && inElt.getAttribute('rel') === inRel);
}
function inMainDocument(inElt) {
return inElt.ownerDocument === document ||
// TODO(sjmiles): ShadowDOMPolyfill intrusion
inElt.ownerDocument.impl === document;
}
function makeDocument(inHTML, inUrl) {
// create a new HTML document
var doc = document.implementation.createHTMLDocument(IMPORT_LINK_TYPE);
// cache the new document's source url
doc._URL = inUrl;
// establish a relative path via <base>
var base = doc.createElement('base');
base.setAttribute('href', document.baseURI);
doc.head.appendChild(base);
// install html
doc.body.innerHTML = inHTML;
return doc;
}
var loader;
var Loader = function(inOnLoad, inOnComplete) {
this.onload = inOnLoad;
this.oncomplete = inOnComplete;
this.inflight = 0;
this.pending = {};
this.cache = {};
};
Loader.prototype = {
addNodes: function(inNodes) {
// number of transactions to complete
this.inflight += inNodes.length;
// commence transactions
forEach(inNodes, this.require, this);
// anything to do?
this.checkDone();
},
require: function(inElt) {
var url = path.nodeUrl(inElt);
// TODO(sjmiles): ad-hoc
inElt.__nodeUrl = url;
// deduplication
if (!this.dedupe(url, inElt)) {
// fetch this resource
this.fetch(url, inElt);
}
},
dedupe: function(inUrl, inElt) {
if (this.pending[inUrl]) {
// add to list of nodes waiting for inUrl
this.pending[inUrl].push(inElt);
// don't need fetch
return true;
}
if (this.cache[inUrl]) {
// complete load using cache data
this.onload(inUrl, inElt, loader.cache[inUrl]);
// finished this transaction
this.tail();
// don't need fetch
return true;
}
// first node waiting for inUrl
this.pending[inUrl] = [inElt];
// need fetch (not a dupe)
return false;
},
fetch: function(inUrl, inElt) {
xhr.load(inUrl, function(err, resource) {
this.receive(inUrl, inElt, err, resource);
}.bind(this));
},
receive: function(inUrl, inElt, inErr, inResource) {
if (!inErr) {
loader.cache[inUrl] = inResource;
}
loader.pending[inUrl].forEach(function(e) {
if (!inErr) {
this.onload(inUrl, e, inResource);
}
this.tail();
}, this);
loader.pending[inUrl] = null;
},
tail: function() {
--this.inflight;
this.checkDone();
},
checkDone: function() {
if (!this.inflight) {
this.oncomplete();
}
}
};
var path = {
nodeUrl: function(inNode) {
return path.resolveUrl(path.getDocumentUrl(document), path.hrefOrSrc(inNode));
},
hrefOrSrc: function(inNode) {
return inNode.getAttribute("href") || inNode.getAttribute("src");
},
documentUrlFromNode: function(inNode) {
return path.getDocumentUrl(inNode.ownerDocument);
},
getDocumentUrl: function(inDocument) {
var url = inDocument &&
// TODO(sjmiles): ShadowDOMPolyfill intrusion
(inDocument._URL || (inDocument.impl && inDocument.impl._URL)
|| inDocument.baseURI || inDocument.URL)
|| '';
// take only the left side if there is a #
return url.split('#')[0];
},
resolveUrl: function(inBaseUrl, inUrl, inRelativeToDocument) {
if (this.isAbsUrl(inUrl)) {
return inUrl;
}
var url = this.compressUrl(this.urlToPath(inBaseUrl) + inUrl);
if (inRelativeToDocument) {
url = path.makeRelPath(path.getDocumentUrl(document), url);
}
return url;
},
isAbsUrl: function(inUrl) {
return /(^data:)|(^http[s]?:)|(^\/)/.test(inUrl);
},
urlToPath: function(inBaseUrl) {
var parts = inBaseUrl.split("/");
parts.pop();
parts.push('');
return parts.join("/");
},
compressUrl: function(inUrl) {
var parts = inUrl.split("/");
for (var i=0, p; i<parts.length; i++) {
p = parts[i];
if (p === "..") {
parts.splice(i-1, 2);
i -= 2;
}
}
return parts.join("/");
},
// make a relative path from source to target
makeRelPath: function(inSource, inTarget) {
var s, t;
s = this.compressUrl(inSource).split("/");
t = this.compressUrl(inTarget).split("/");
while (s.length && s[0] === t[0]){
s.shift();
t.shift();
}
for(var i = 0, l = s.length-1; i < l; i++) {
t.unshift("..");
}
var r = t.join("/");
return r;
},
resolvePathsInHTML: function(inRoot) {
var docUrl = path.documentUrlFromNode(inRoot.body);
// TODO(sorvell): MDV Polyfill Intrusion
if (window.HTMLTemplateElement && HTMLTemplateElement.bootstrap) {
HTMLTemplateElement.bootstrap(inRoot);
}
var node = inRoot.body;
path._resolvePathsInHTML(node, docUrl);
},
_resolvePathsInHTML: function(inRoot, inUrl) {
path.resolveAttributes(inRoot, inUrl);
path.resolveStyleElts(inRoot, inUrl);
// handle templates, if supported
if (window.templateContent) {
var templates = inRoot.querySelectorAll('template');
if (templates) {
forEach(templates, function(t) {
path._resolvePathsInHTML(templateContent(t), inUrl);
});
}
}
},
resolvePathsInStylesheet: function(inSheet) {
var docUrl = path.nodeUrl(inSheet);
inSheet.__resource = path.resolveCssText(inSheet.__resource, docUrl);
},
resolveStyleElts: function(inRoot, inUrl) {
var styles = inRoot.querySelectorAll('style');
if (styles) {
forEach(styles, function(style) {
style.textContent = path.resolveCssText(style.textContent, inUrl);
});
}
},
resolveCssText: function(inCssText, inBaseUrl) {
return inCssText.replace(/url\([^)]*\)/g, function(inMatch) {
// find the url path, ignore quotes in url string
var urlPath = inMatch.replace(/["']/g, "").slice(4, -1);
urlPath = path.resolveUrl(inBaseUrl, urlPath, true);
return "url(" + urlPath + ")";
});
},
resolveAttributes: function(inRoot, inUrl) {
// search for attributes that host urls
var nodes = inRoot && inRoot.querySelectorAll(URL_ATTRS_SELECTOR);
if (nodes) {
forEach(nodes, function(n) {
this.resolveNodeAttributes(n, inUrl);
}, this);
}
},
resolveNodeAttributes: function(inNode, inUrl) {
URL_ATTRS.forEach(function(v) {
var attr = inNode.attributes[v];
if (attr && attr.value &&
(attr.value.search(URL_TEMPLATE_SEARCH) < 0)) {
var urlPath = path.resolveUrl(inUrl, attr.value, true);
attr.value = urlPath;
}
});
}
};
var URL_ATTRS = ['href', 'src', 'action'];
var URL_ATTRS_SELECTOR = '[' + URL_ATTRS.join('],[') + ']';
var URL_TEMPLATE_SEARCH = '{{.*}}';
var xhr = scope.xhr || {
async: true,
ok: function(inRequest) {
return (inRequest.status >= 200 && inRequest.status < 300)
|| (inRequest.status === 304)
|| (inRequest.status === 0);
},
load: function(url, next, nextContext) {
var request = new XMLHttpRequest();
if (scope.flags.debug || scope.flags.bust) {
url += '?' + Math.random();
}
request.open('GET', url, xhr.async);
request.addEventListener('readystatechange', function(e) {
if (request.readyState === 4) {
next.call(nextContext, !xhr.ok(request) && request,
request.response, url);
}
});
request.send();
}
};
var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
// exports
scope.xhr = xhr;
scope.importer = importer;
scope.getDocumentUrl = path.getDocumentUrl;
// bootstrap
// IE shim for CustomEvent
if (typeof window.CustomEvent !== 'function') {
window.CustomEvent = function(inType) {
var e = document.createEvent('HTMLEvents');
e.initEvent(inType, true, true);
return e;
};
}
document.addEventListener('DOMContentLoaded', function() {
// preload document resource trees
importer.load(document, function() {
// TODO(sjmiles): ShadowDOM polyfill pollution
var doc = window.ShadowDOMPolyfill ? ShadowDOMPolyfill.wrap(document)
: document;
HTMLImports.readyTime = new Date().getTime();
// send HTMLImportsLoaded when finished
doc.body.dispatchEvent(
new CustomEvent('HTMLImportsLoaded', {bubbles: true})
);
});
});
})(window.HTMLImports);
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (!window.MutationObserver) {
window.MutationObserver =
window.WebKitMutationObserver ||
window.JsMutationObserver;
if (!MutationObserver) {
throw new Error("no mutation observer support");
}
}
/*
* Copyright 2013 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* Implements `document.register`
* @module CustomElements
*/
/**
* Polyfilled extensions to the `document` object.
* @class Document
*/
(function(scope) {
if (!scope) {
scope = window.CustomElements = {flags:{}};
}
// native document.register?
scope.hasNative = (document.webkitRegister || document.register) && scope.flags.register === 'native';
if (scope.hasNative) {
// normalize
document.register = document.register || document.webkitRegister;
var nop = function() {};
// exports
scope.registry = {};
scope.upgradeElement = nop;
} else {
/**
* Registers a custom tag name with the document.
*
* When a registered element is created, a `readyCallback` method is called
* in the scope of the element. The `readyCallback` method can be specified on
* either `inOptions.prototype` or `inOptions.lifecycle` with the latter taking
* precedence.
*
* @method register
* @param {String} inName The tag name to register. Must include a dash ('-'),
* for example 'x-component'.
* @param {Object} inOptions
* @param {String} [inOptions.extends]
* (_off spec_) Tag name of an element to extend (or blank for a new
* element). This parameter is not part of the specification, but instead
* is a hint for the polyfill because the extendee is difficult to infer.
* Remember that the input prototype must chain to the extended element's
* prototype (or HTMLElement.prototype) regardless of the value of
* `extends`.
* @param {Object} inOptions.prototype The prototype to use for the new
* element. The prototype must inherit from HTMLElement.
* @param {Object} [inOptions.lifecycle]
* Callbacks that fire at important phases in the life of the custom
* element.
*
* @example
* FancyButton = document.register("fancy-button", {
* extends: 'button',
* prototype: Object.create(HTMLButtonElement.prototype, {
* readyCallback: {
* value: function() {
* console.log("a fancy-button was created",
* }
* }
* })
* });
* @return {Function} Constructor for the newly registered type.
*/
function register(inName, inOptions) {
//console.warn('document.register("' + inName + '", ', inOptions, ')');
// construct a defintion out of options
// TODO(sjmiles): probably should clone inOptions instead of mutating it
var definition = inOptions || {};
if (!inName) {
// TODO(sjmiles): replace with more appropriate error (Erik can probably
// offer guidance)
throw new Error('Name argument must not be empty');
}
// record name
definition.name = inName;
// must have a prototype, default to an extension of HTMLElement
// TODO(sjmiles): probably should throw if no prototype, check spec
if (!definition.prototype) {
// TODO(sjmiles): replace with more appropriate error (Erik can probably
// offer guidance)
throw new Error('Options missing required prototype property');
}
// ensure a lifecycle object so we don't have to null test it
definition.lifecycle = definition.lifecycle || {};
// build a list of ancestral custom elements (for native base detection)
// TODO(sjmiles): we used to need to store this, but current code only
// uses it in 'resolveTagName': it should probably be inlined
definition.ancestry = ancestry(definition.extends);
// extensions of native specializations of HTMLElement require localName
// to remain native, and use secondary 'is' specifier for extension type
resolveTagName(definition);
// some platforms require modifications to the user-supplied prototype
// chain
resolvePrototypeChain(definition);
// overrides to implement attributeChanged callback
overrideAttributeApi(definition.prototype);
// 7.1.5: Register the DEFINITION with DOCUMENT
registerDefinition(inName, definition);
// 7.1.7. Run custom element constructor generation algorithm with PROTOTYPE
// 7.1.8. Return the output of the previous step.
definition.ctor = generateConstructor(definition);
definition.ctor.prototype = definition.prototype;
// force our .constructor to be our actual constructor
definition.prototype.constructor = definition.ctor;
// if initial parsing is complete
if (scope.ready) {
// upgrade any pre-existing nodes of this type
scope.upgradeAll(document);
}
return definition.ctor;
}
function ancestry(inExtends) {
var extendee = registry[inExtends];
if (extendee) {
return ancestry(extendee.extends).concat([extendee]);
}
return [];
}
function resolveTagName(inDefinition) {
// if we are explicitly extending something, that thing is our
// baseTag, unless it represents a custom component
var baseTag = inDefinition.extends;
// if our ancestry includes custom components, we only have a
// baseTag if one of them does
for (var i=0, a; (a=inDefinition.ancestry[i]); i++) {
baseTag = a.is && a.tag;
}
// our tag is our baseTag, if it exists, and otherwise just our name
inDefinition.tag = baseTag || inDefinition.name;
if (baseTag) {
// if there is a base tag, use secondary 'is' specifier
inDefinition.is = inDefinition.name;
}
}
function resolvePrototypeChain(inDefinition) {
// if we don't support __proto__ we need to locate the native level
// prototype for precise mixing in
if (!Object.__proto__) {
// default prototype
var native = HTMLElement.prototype;
// work out prototype when using type-extension
if (inDefinition.is) {
var inst = document.createElement(inDefinition.tag);
native = Object.getPrototypeOf(inst);
}
}
// cache this in case of mixin
inDefinition.native = native;
}
// SECTION 4
function instantiate(inDefinition) {
// 4.a.1. Create a new object that implements PROTOTYPE
// 4.a.2. Let ELEMENT by this new object
//
// the custom element instantiation algorithm must also ensure that the
// output is a valid DOM element with the proper wrapper in place.
//
return upgrade(domCreateElement(inDefinition.tag), inDefinition);
}
function upgrade(inElement, inDefinition) {
// some definitions specify an 'is' attribute
if (inDefinition.is) {
inElement.setAttribute('is', inDefinition.is);
}
// make 'element' implement inDefinition.prototype
implement(inElement, inDefinition);
// flag as upgraded
inElement.__upgraded__ = true;
// there should never be a shadow root on inElement at this point
// we require child nodes be upgraded before ready
scope.upgradeSubtree(inElement);
// lifecycle management
ready(inElement);
// OUTPUT
return inElement;
}
function implement(inElement, inDefinition) {
// prototype swizzling is best
if (Object.__proto__) {
inElement.__proto__ = inDefinition.prototype;
} else {
// where above we can re-acquire inPrototype via
// getPrototypeOf(Element), we cannot do so when
// we use mixin, so we install a magic reference
customMixin(inElement, inDefinition.prototype, inDefinition.native);
inElement.__proto__ = inDefinition.prototype;
}
}
function customMixin(inTarget, inSrc, inNative) {
// TODO(sjmiles): 'used' allows us to only copy the 'youngest' version of
// any property. This set should be precalculated. We also need to
// consider this for supporting 'super'.
var used = {};
// start with inSrc
var p = inSrc;
// sometimes the default is HTMLUnknownElement.prototype instead of
// HTMLElement.prototype, so we add a test
// the idea is to avoid mixing in native prototypes, so adding
// the second test is WLOG
while (p !== inNative && p !== HTMLUnknownElement.prototype) {
var keys = Object.getOwnPropertyNames(p);
for (var i=0, k; k=keys[i]; i++) {
if (!used[k]) {
Object.defineProperty(inTarget, k,
Object.getOwnPropertyDescriptor(p, k));
used[k] = 1;
}
}
p = Object.getPrototypeOf(p);
}
}
function ready(inElement) {
// invoke readyCallback
if (inElement.readyCallback) {
inElement.readyCallback();
}
}
// attribute watching
function overrideAttributeApi(prototype) {
// overrides to implement callbacks
// TODO(sjmiles): should support access via .attributes NamedNodeMap
// TODO(sjmiles): preserves user defined overrides, if any
var setAttribute = prototype.setAttribute;
prototype.setAttribute = function(name, value) {
changeAttribute.call(this, name, value, setAttribute);
}
var removeAttribute = prototype.removeAttribute;
prototype.removeAttribute = function(name, value) {
changeAttribute.call(this, name, value, removeAttribute);
}
}
function changeAttribute(name, value, operation) {
var oldValue = this.getAttribute(name);
operation.apply(this, arguments);
if (this.attributeChangedCallback
&& (this.getAttribute(name) !== oldValue)) {
this.attributeChangedCallback(name, oldValue);
}
}
// element registry (maps tag names to definitions)
var registry = {};
function registerDefinition(inName, inDefinition) {
registry[inName] = inDefinition;
}
function generateConstructor(inDefinition) {
return function() {
return instantiate(inDefinition);
};
}
function createElement(inTag) {
var definition = registry[inTag];
if (definition) {
return new definition.ctor();
}
return domCreateElement(inTag);
}
function upgradeElement(inElement) {
if (!inElement.__upgraded__ && (inElement.nodeType === Node.ELEMENT_NODE)) {
var type = inElement.getAttribute('is') || inElement.localName;
var definition = registry[type];
return definition && upgrade(inElement, definition);
}
}
function cloneNode(deep) {
// call original clone
var n = domCloneNode.call(this, deep);
// upgrade the element and subtree
scope.upgradeAll(n);
return n;
}
// capture native createElement before we override it
var domCreateElement = document.createElement.bind(document);
// capture native cloneNode before we override it
var domCloneNode = Node.prototype.cloneNode;
// exports
document.register = register;
document.createElement = createElement; // override
Node.prototype.cloneNode = cloneNode; // override
scope.registry = registry;
/**
* Upgrade an element to a custom element. Upgrading an element
* causes the custom prototype to be applied, an `is` attribute
* to be attached (as needed), and invocation of the `readyCallback`.
* `upgrade` does nothing if the element is already upgraded, or
* if it matches no registered custom tag name.
*
* @method ugprade
* @param {Element} inElement The element to upgrade.
* @return {Element} The upgraded element.
*/
scope.upgrade = upgradeElement;
}
})(window.CustomElements);
/*
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
(function(scope){
/*
if (HTMLElement.prototype.webkitShadowRoot) {
Object.defineProperty(HTMLElement.prototype, 'shadowRoot', {
get: function() {
return this.webkitShadowRoot;
}
};
}
*/
// walk the subtree rooted at node, applying 'find(element, data)' function
// to each element
// if 'find' returns true for 'element', do not search element's subtree
function findAll(node, find, data) {
var e = node.firstElementChild;
if (!e) {
e = node.firstChild;
while (e && e.nodeType !== Node.ELEMENT_NODE) {
e = e.nextSibling;
}
}
while (e) {
if (find(e, data) !== true) {
findAll(e, find, data);
}
e = e.nextElementSibling;
}
return null;
}
// walk the subtree rooted at node, including descent into shadow-roots,
// applying 'cb' to each element
function forSubtree(node, cb) {
//logFlags.dom && node.childNodes && node.childNodes.length && console.group('subTree: ', node);
findAll(node, function(e) {
if (cb(e)) {
return true;
}
if (e.webkitShadowRoot) {
forSubtree(e.webkitShadowRoot, cb);
}
});