forked from WebReflection/hyperHTML
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1600 lines (1480 loc) · 47.1 KB
/
Copy pathindex.js
File metadata and controls
1600 lines (1480 loc) · 47.1 KB
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
var hyperHTML = (function (globalDocument, majinbuu) {'use strict';
/*! (c) 2017 Andrea Giammarchi @WebReflection, (ISC) */
// ---------------------------------------------
// hyperHTML Public API
// ---------------------------------------------
// The document must be swap-able at runtime.
// Needed by both basicHTML and nativeHTML
hyper.document = globalDocument;
// friendly destructuring
hyper.hyper = hyper;
function hyper(HTML) {
return arguments.length < 2 ?
(HTML == null ?
wireContent('html') :
(typeof HTML === 'string' ?
wire(null, HTML) :
('raw' in HTML ?
wireContent('html')(HTML) :
('nodeType' in HTML ?
bind(HTML) :
wireWeakly(HTML, 'html')
)
)
)) :
('raw' in HTML ?
wireContent('html') : wire
).apply(null, arguments);
}
// hyper.adopt(el) 🐣
// import an already live DOM structure
// described as TL
hyper.adopt = function adopt(node) {
return function () {
notAdopting = false;
render.apply(node, arguments);
notAdopting = true;
return node;
};
};
// hyper.bind(el) ⚡️
// render TL inside a DOM node used as context
hyper.bind = bind;
function bind(context) { return render.bind(context); }
// hyper.define('transformer', callback) 🌀
hyper.define = function define(transformer, callback) {
if (!(transformer in transformers)) {
transformersKeys.push(transformer);
}
transformers[transformer] = callback;
// TODO: else throw ? console.warn ? who cares ?
};
// hyper.escape('<html>') => '<text>' 🏃
hyper.escape = function escape(html) {
return html.replace(/[&<>'"]/g, fnEscape);
};
// hyper.wire(obj, 'type:ID') ➰
// relate a renderer to a generic object
hyper.wire = wire;
function wire(obj, type) {
return arguments.length < 1 ?
wireContent('html') :
(obj == null ?
wireContent(type || 'html') :
wireWeakly(obj, type || 'html')
);
}
// hyper.Component([initialState]) 🍻
// An overly-simplified Component class.
// For full Custom Elements support
// see HyperHTMLElement instead.
hyper.Component = Component;
function Component() {}
Object.defineProperties(
Component.prototype,
{
// same as HyperHTMLElement handleEvent
handleEvent: {value: function (e) {
// both IE < 11 and JSDOM lack dataset
var ct = e.currentTarget;
this[
('getAttribute' in ct && ct.getAttribute('data-call')) ||
('on' + e.type)
](e);
}},
// returns its own HTML wire or create it once on comp.render()
html: lazyGetter('html', wireContent),
// returns its own SVG wire or create it once on comp.render()
svg: lazyGetter('svg', wireContent),
// same as HyperHTMLElement state
state: lazyGetter('state', function () { return this.defaultState; }),
// same as HyperHTMLElement get defaultState
defaultState: {get: function () { return {}; }},
// same as HyperHTMLElement setState
setState: {value: function (state) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) target[key] = source[key];
this.render();
}}
// the render must be defined when extending hyper.Component
// the render **must** return either comp.html or comp.svg wire
// render() { return this.html`<p>that's it</p>`; }
}
);
// - - - - - - - - - - - - - - - - - - - - - - -
// ---------------------------------------------
// Constants
// ---------------------------------------------
// Node.CONSTANTS
// without assuming Node is globally available
// since this project is used on the backend too
var ELEMENT_NODE = 1;
var ATTRIBUTE_NODE = 2;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_FRAGMENT_NODE = 11;
// SVG related
var OWNER_SVG_ELEMENT = 'ownerSVGElement';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
var SHOULD_USE_ATTRIBUTE = /^style$/i;
var SHOULD_USE_TEXT_CONTENT = /^style|textarea$/i;
var EXPANDO = '_hyper: ';
var UID = EXPANDO + ((Math.random() * new Date) | 0) + ';';
var UIDC = '<!--' + UID + '-->';
// ---------------------------------------------
// DOM Manipulation
// ---------------------------------------------
function Aura(node, childNodes) {
this.node = node;
this.childNodes = childNodes;
return majinbuu.aura(this, childNodes);
}
Aura.prototype.splice = function splice(start) {
for (var
tmp,
ph = this.node,
cn = this.childNodes,
target = cn[start + (arguments[1] || 0)] || ph,
result = cn.splice.apply(cn, arguments),
pn = ph.parentNode,
i = 0,
length = result.length;
i < length; i++
) {
tmp = result[i];
// TODO: this is not optimal (but necessary)
if (cn.indexOf(tmp) < 0) {
pn.removeChild(tmp);
}
}
i = 2;
length = arguments.length;
if (i < length) {
if ((length - i) === 1) {
tmp = arguments[i];
} else {
tmp = createDocumentFragment(pn.ownerDocument);
while (i < length) {
tmp.appendChild(arguments[i++]);
}
}
pn.insertBefore(tmp, target);
}
return result;
};
// ---------------------------------------------
// hyperHTML Operations
// ---------------------------------------------
// entry point for all TL => DOM operations
function render(template) {
var hyper = hypers.get(this);
if (
!hyper ||
hyper.template !== TL(template)
) {
upgrade.apply(this, arguments);
} else {
update.apply(hyper.updates, arguments);
}
return this;
}
// `<div class="${'attr'}"></div>`
// `<div onclick="${function () {... }}"></div>`
// `<div onclick="${{handleEvent(){ ... }}}"></div>`
// `<div contenteditable="${true}"></div>`
function setAttribute(attribute, removeAttributes, name) {
var
node = attribute.ownerElement,
isData = name === 'data',
isEvent = !isData && /^on/.test(name),
isSpecial = isData ||
(isSpecialAttribute(node, name) &&
!SHOULD_USE_ATTRIBUTE.test(name)),
type = isEvent ? name.slice(2) : '',
noOwner = isSpecial || isEvent,
wontUpgrade = isSpecial && (isData || name in node),
oldValue, specialAttr, upgrade
;
if (isEvent || wontUpgrade) {
removeAttributes.push(node, name);
if (isEvent) {
if (type === CONNECTED || type === DISCONNECTED) {
components.add(node);
}
else if (name.toLowerCase() in node) {
type = type.toLowerCase();
}
}
}
if (isSpecial) {
if (!wontUpgrade) {
upgrade = toBeUpgraded.get(node);
if (!upgrade) {
upgrade = {
_: Object.create(null),
$: function () {
toBeUpgraded.delete(node);
for (var name in this._) {
this._[name].$();
}
}
};
toBeUpgraded.set(node, upgrade);
}
upgrade._[name] = {
_: null,
$: function () {
wontUpgrade = true;
specialAttr(this._);
}
};
}
specialAttr = function specialAttr(newValue) {
if (wontUpgrade) {
if (oldValue !== newValue) {
oldValue = newValue;
// WebKit moves the cursor if input.value
// is set again, even if same value
if (node[name] !== newValue) {
// let the browser handle the case
// input.value = null;
// input.value; // ''
if (newValue == null) {
// reflect the null intent,
// do not pass undefined!
node[name] = null;
node.removeAttribute(name);
} else {
node[name] = newValue;
}
}
}
} else {
attribute.value = newValue;
upgrade._[name]._ = newValue;
if (name in node) upgrade.$();
}
};
}
return isEvent ?
function eventAttr(newValue) {
if (oldValue !== newValue) {
if (oldValue) node.removeEventListener(type, oldValue, false);
oldValue = newValue;
if (newValue) node.addEventListener(type, newValue, false);
}
} :
(isSpecial ?
specialAttr :
function normalAttr(newValue) {
if (oldValue !== newValue) {
oldValue = newValue;
// avoid triggering again attributeChangeCallback
// if the value was identical
if (attribute.value !== newValue) {
if (newValue == null) {
if (!noOwner) {
// TODO: should attribute.value = null here?
noOwner = true;
node.removeAttributeNode(attribute);
}
} else {
attribute.value = newValue;
if (noOwner) {
noOwner = false;
node.setAttributeNode(attribute);
}
}
}
}
}
);
}
// `<style>${'text'}</style>`
function setTextContent(node) {
var oldValue;
return function (value) {
if (value !== oldValue) {
oldValue = value;
node.textContent = value;
}
};
}
// `<p>${'any'}</p>`
// `<li>a</li>${'virtual'}<li>c</li>`
function setAnyContent(node, childNodes, aura) {
var oldValue;
return function anyContent(value) {
switch (typeof value) {
case 'string':
case 'number':
case 'boolean':
var length = childNodes.length;
if (
length === 1 &&
childNodes[0].nodeType === TEXT_NODE
) {
if (oldValue !== value) {
oldValue = value;
childNodes[0].textContent = value;
}
} else {
oldValue = value;
if (length) {
aura.splice(0, length, createText(node, value));
} else {
childNodes[0] = node.parentNode.insertBefore(
createText(node, value),
node
);
}
}
break;
case 'function':
anyContent(value(node.parentNode, childNodes, 0));
break;
case 'object':
case 'undefined':
if (value == null) {
oldValue = value;
anyContent('');
break;
} else if (value instanceof Component) {
value = value.render();
}
default:
oldValue = value;
if (isArray(value)) {
var length = value.length;
if (length === 0) {
aura.splice(0);
} else {
switch (typeof value[0]) {
case 'string':
case 'number':
case 'boolean':
anyContent({html: value});
break;
case 'function':
var parentNode = node.parentNode;
for (var i = 0; i < length; i++) {
value[i] = value[i](parentNode, childNodes, i);
}
anyContent(value.concat.apply([], value));
break;
case 'object':
if (isArray(value[0])) {
value = value.concat.apply([], value);
}
if (isPromise_ish(value[0])) {
Promise.all(value).then(anyContent);
break;
} else {
for (var i = 0, length = value.length; i < length; i++) {
if (value[i] instanceof Component) {
value[i] = value[i].render();
}
}
}
default:
optimist(aura, value);
break;
}
}
} else if (isNode_ish(value)) {
optimist(
aura,
value.nodeType === DOCUMENT_FRAGMENT_NODE ?
slice.call(value.childNodes) :
[value]
);
} else if (isPromise_ish(value)) {
value.then(anyContent);
} else if ('placeholder' in value) {
invokeAtDistance(value, anyContent);
} else if ('text' in value) {
anyContent(String(value.text));
} else if ('any' in value) {
anyContent(value.any);
} else if ('html' in value) {
var html = [].concat(value.html).join('');
aura.splice(0);
var fragment = createFragment(node, html);
childNodes.push.apply(childNodes, fragment.childNodes);
node.parentNode.insertBefore(fragment, node);
} else if ('length' in value) {
anyContent(slice.call(value));
} else {
anyContent(invokeTransformer(value, anyContent));
}
break;
}
};
}
// ---------------------------------------------
// DOM Traversing
// ---------------------------------------------
// look for attributes that contains the comment text
function attributesSeeker(node, paths, parts) {
for (var
name, realName, attrs,
attribute,
cache = Object.create(null),
attributes = node.attributes,
i = 0, length = attributes.length;
i < length; i++
) {
attribute = attributes[i];
if (attribute.value === UID) {
name = attribute.name;
// this is an IE < 11 thing only
if (name in cache) {
// attributes with unrecognized values
// are duplicated, even if same attribute, across the node
// to fix it, you need to remove it
node.removeAttributeNode(attribute);
// put a value that won't (hopefully) bother IE
cache[name].value = '';
// and place the node back
node.setAttributeNode(cache[name]);
// this will decrease attributes count by 1
length--;
// so the loop should be decreased by 1 too
i--;
} else {
realName = parts.shift().replace(/^(?:|[\S\s]*?\s)(\S+?)=['"]?$/, '$1');
attrs = node.attributes;
// fallback is needed in both jsdom
// and in not-so-standard browsers/engines
cache[name] = attrs[realName] || attrs[realName.toLowerCase()];
paths.push(Path('attr', cache[name], realName));
}
}
}
}
// walk the fragment tree in search of comments
function hyperSeeker(node, paths, parts) {
for (var
child,
childNodes = node.childNodes,
length = childNodes.length,
i = 0; i < length; i++
) {
child = childNodes[i];
switch (child.nodeType) {
case ELEMENT_NODE:
attributesSeeker(child, paths, parts);
hyperSeeker(child, paths, parts);
break;
case COMMENT_NODE:
if (child.textContent === UID) {
parts.shift();
paths.push(Path('any', child));
}
break;
case TEXT_NODE:
if (
SHOULD_USE_TEXT_CONTENT.test(node.nodeName) &&
trim.call(child.textContent) === UIDC
) {
parts.shift();
paths.push(Path('text', node));
}
break;
}
}
}
// ---------------------------------------------
// Features detection / ugly UA sniffs
// ---------------------------------------------
/*
var importNode = 'importNode' in globalDocument ?
function (doc, node) {
return doc.importNode(node, true);
} :
function (doc, node) {
return node;
};
*/
var featureFragment = createDocumentFragment(globalDocument);
// Firefox < 55 has non standard template literals.
// https://bugzilla.mozilla.org/show_bug.cgi?id=1108941
// TODO: is there any better way to feature detect this ?
var FF = typeof navigator === 'object' &&
/Firefox\/(\d+)/.test(navigator.userAgent) &&
parseFloat(RegExp.$1) < 55;
// If attributes order is shuffled, threat the browser differently
// Usually this is a well known IE only limitation but some older FF does the same.
var IE = (function () {
var p = globalDocument.createElement('p');
p.innerHTML = '<i data-i="" class=""></i>';
return /class/i.test(p.firstChild.attributes[0].name);
}());
// beside IE, old WebKit browsers don't have `children` in DocumentFragment
var WK = !('children' in featureFragment);
// both Firefox < 55 and TypeScript have issues with template literals
// this lazy defined callback should spot issues right away
// and in the best case scenario become a no-op
var TL = function (template) {
if (template.propertyIsEnumerable('raw') || FF) TL = unique;
else TL = function (t) { return t; };
return TL(template);
};
// ---------------------------------------------
// Helpers
// ---------------------------------------------
// used to convert childNodes to Array
var slice = [].slice;
// used to sanitize html
var oEscape = {
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
};
function fnEscape(m) {
return oEscape[m];
}
// return content as html
function asHTML(html) {
return {html: html};
}
// return a single node or an Array or nodes
function createContent(node) {
for (var
child,
content = [],
childNodes = node.childNodes,
i = 0,
length = childNodes.length;
i < length; i++
) {
child = childNodes[i];
if (
child.nodeType === ELEMENT_NODE ||
trim.call(child.textContent).length !== 0
) {
content.push(child);
}
}
return content.length === 1 ? content[0] : content;
}
// just a minifier friendly indirection
function createDocumentFragment(document) {
return document.createDocumentFragment();
}
// given a node, inject some html and return
// the resulting template document fragment
function createFragment(node, html) {
return (
OWNER_SVG_ELEMENT in node ?
createSVGFragment :
createHTMLFragment
)(node, html.replace(no, comments));
}
// create fragment for HTML
function createHTMLFragment(node, html) {
var fragment;
var document = node.ownerDocument;
var container = document.createElement(
// TODO: this is a work around for A-Frame V0 based components
// see: https://stackoverflow.com/questions/46797635/aframe-content-not-rendering-on-chrome-with-hyperhtml/46817370
// TODO: the following RegExp breaks: https://github.com/WebReflection/hyperHTML/issues/135
// /<([a-z][a-z0-9]*(?:-[a-z0-9]+)+)[\s\S]*?>[\s\S]*?<\/\1>/i.test(html) ?
/<(a-\w+)[\s\S]*?>[\s\S]*?<\/\1>/.test(html) ?
'div' : 'template'
);
// var container = document.createElement('template');
var hasContent = 'content' in container;
var needsTableWrap = false;
if (!hasContent) {
// DO NOT MOVE THE FOLLOWING LINE ELSEWHERE
fragment = createDocumentFragment(document);
// (a jsdom + nodejs tests coverage gotcha)
// el.innerHTML = '<td></td>'; is not possible
// if the content is a partial internal table content
// it needs to be wrapped around once injected.
// HTMLTemplateElement does not suffer this issue.
needsTableWrap = /^[^\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(html);
}
if (needsTableWrap) {
// secure the RegExp.$1 result ASAP to avoid issues
// in case a non-browser DOM library uses RegExp internally
// when HTML content is injected (basicHTML / jsdom / others...)
var selector = RegExp.$1;
container.innerHTML = '<table>' + html + '</table>';
appendNodes(fragment, slice.call(container.querySelectorAll(selector)));
} else {
container.innerHTML = html;
if (hasContent) {
fragment = container.content;
// fragment = importNode(document, container.content);
} else {
appendNodes(fragment, slice.call(container.childNodes));
}
}
return fragment;
}
// create a fragment for SVG
function createSVGFragment(node, html) {
var document = node.ownerDocument;
var fragment = createDocumentFragment(document);
if (IE || WK) {
var container = document.createElement('div');
container.innerHTML = '<svg xmlns="' + SVG_NAMESPACE + '">' + html + '</svg>';
appendNodes(fragment, slice.call(container.firstChild.childNodes));
} else {
var container = document.createElementNS(SVG_NAMESPACE, 'svg');
container.innerHTML = html;
appendNodes(fragment, slice.call(container.childNodes));
}
return fragment;
}
// given a node, it does what is says
function createText(node, text) {
return node.ownerDocument.createTextNode(text);
}
// dispatch same event through a list of nodes
function dispatchAll(nodes, type) {
for (var
e, node,
isConnected = type === CONNECTED,
i = 0, length = nodes.length;
i < length; i++
) {
node = nodes[i];
/* istanbul ignore else */
if (node.nodeType === ELEMENT_NODE) {
e = dispatchTarget(node, isConnected, type, e);
}
}
}
// per each inserted element, check initialization
function dispatchTarget(node, isConnected, type, e) {
/* istanbul ignore next */
if (components.has(node)) {
node.dispatchEvent(e || (e = new $Event(type)));
}
else if (isConnected && toBeUpgraded.has(node)) {
toBeUpgraded.get(node).$();
}
else {
for (var
nodes = getChildren(node),
i = 0, length = nodes.length;
i < length; i++
) {
e = dispatchTarget(nodes[i], isConnected, type, e);
}
}
return e;
}
// returns current customElements reference
// compatible with basicHTML too
function getCEClass(node) {
var doc = hyper.document;
var ce = doc.customElements || doc.defaultView.customElements;
return ce && ce.get(node.nodeName.toLowerCase());
}
// verify that an attribute has
// a special meaning for the node
function isSpecialAttribute(node, name) {
var notSVG = !(OWNER_SVG_ELEMENT in node);
if (notSVG && /-/.test(node.nodeName)) {
var Class = getCEClass(node);
if (Class) node = Class.prototype;
}
return notSVG && name in node;
}
// use a placeholder and resolve with the right callback
function invokeAtDistance(value, callback) {
callback(value.placeholder);
if ('text' in value) {
Promise.resolve(value.text).then(String).then(callback);
} else if ('any' in value) {
Promise.resolve(value.any).then(callback);
} else if ('html' in value) {
Promise.resolve(value.html).then(asHTML).then(callback);
} else {
Promise.resolve(invokeTransformer(value, callback)).then(callback);
}
}
// last attempt to transform content
function invokeTransformer(object, callback) {
for (var key, i = 0, length = transformersKeys.length; i < length; i++) {
key = transformersKeys[i];
if (object.hasOwnProperty(key)) {
return transformers[key](object[key], callback);
}
}
}
// quick and dirty Node check
function isNode_ish(value) {
return 'ELEMENT_NODE' in value;
}
// quick and dirty Promise check
function isPromise_ish(value) {
return value != null && 'then' in value;
}
// return a descriptor that lazily initialize a property
// unless it hasn't be previously set directly
function lazyGetter(type, fn) {
var secret = '_' + type + '$';
return {
get: function () {
return this[secret] || (this[type] = fn.call(this, type));
},
set: function (value) {
defineProperty(this, secret, {configurable: true, value: value});
}
};
}
// uses majinbuu only if the two lists are different
function optimist(aura, value) {
var i = 0, length = aura.length;
if (value.length !== length) {
majinbuu(aura, value, hyper.MAX_LIST_SIZE);
} else {
for (; i < length--; i++) {
if (aura[length] !== value[length] || aura[i] !== value[i]) {
majinbuu(aura, value, hyper.MAX_LIST_SIZE);
return;
}
}
}
}
// remove a list of [node, attribute]
function removeAttributeList(list) {
for (var i = 0, length = list.length; i < length; i++) {
list[i++].removeAttribute(list[i]);
}
}
// specify the content to update
function setContent(info, target, removeAttributes, childNodes) {
var update;
switch (info.type) {
case 'any':
// TODO: don't pass the target, it shouldn't be needed
update = setAnyContent(target, childNodes, new Aura(target, childNodes));
break;
case 'attr':
update = setAttribute(target, removeAttributes, info.name);
break;
case 'text':
update = setTextContent(target);
break;
}
return update;
}
// used for common path creation.
function Path(type, node, name) {
return {type: type, path: createPath(node), name: name};
}
// ---------------------------------------------
// Hybrid Shims
// ---------------------------------------------
var CONNECTED = 'connected';
var DISCONNECTED = 'dis' + CONNECTED;
var $Event;
try {
new Event(CONNECTED);
$Event = Event;
} catch(o_O) {
$Event = function (type) {
var e = hyper.document.createEvent('Event');
e.initEvent(type, false, false);
return e;
};
}
try {
(new MutationObserver(function (records) {
for (var record, i = 0, length = records.length; i < length; i++) {
record = records[i];
dispatchAll(record.removedNodes, DISCONNECTED);
dispatchAll(record.addedNodes, CONNECTED);
}
})).observe(globalDocument, {subtree: true, childList: true});
} catch(o_O) {
globalDocument.addEventListener('DOMNodeInserted', function (e) {
dispatchAll([e.target], CONNECTED);
}, false);
globalDocument.addEventListener('DOMNodeRemoved', function (e) {
dispatchAll([e.target], DISCONNECTED);
}, false);
}
// WeakMap with partial UID fallback
var $WeakMap = typeof WeakMap === typeof $WeakMap ?
function () {
// NOT A POLYFILL: simplified ad-hoc for this library cases
/* istanbul ignore next */
return {
delete: function (obj) { delete obj[UID]; },
get: function (obj) { return obj[UID]; },
has: function (obj) { return UID in obj; },
set: function (obj, value) {
Object.defineProperty(obj, UID, {
configurable: true,
value: value
});
}
};
} :
WeakMap;
var $WeakSet = typeof WeakSet === typeof $WeakSet ?
function () {
var wm = new $WeakMap;
// NOT A POLYFILL: simplified ad-hoc for this library cases
/* istanbul ignore next */
return {
add: function (obj) { wm.set(obj, true); },
has: function (obj) { return wm.get(obj) === true; }
};
} :
WeakSet;
// Map with partial double Array fallback
var $Map = typeof Map === typeof $Map ?
function () {
var k = [], v = [];
return {
get: function (obj) {
return v[k.indexOf(obj)];
},
// being used with unique template literals
// there is never a case when a value is overwritten
// no need to check upfront for the indexOf
set: function (obj, value) {
v[k.push(obj) - 1] = value;
}
};
} :
Map;
// TODO: which browser needs these partial polyfills here?
// BB7 and webOS need this
var isArray = Array.isArray ||
(function () {
var toString = {}.toString;
// I once had an engine returning [array Array]
// and I've got scared since!
var s = toString.call([]);
return function (a) {
return toString.call(a) === s;
};
}());
// older WebKit need this
var trim = EXPANDO.trim ||
function () { return this.replace(/^\s+|\s+$/g, ''); };
// ---------------------------------------------
// Shared variables
// ---------------------------------------------
// recycled defineProperty shortcut
var defineProperty = Object.defineProperty;
// transformers registry
var transformers = {};
var transformersKeys = [];
// normalize Firefox issue with template literals
var templateObjects = {}, unique;
function unique(template) {
var key = '_' + template.join(UIDC);
return templateObjects[key] ||
(templateObjects[key] = template);
}
// use native .append(...childNodes) where available
var appendNodes = 'append' in featureFragment ?
function (node, childNodes) {
node.append.apply(node, childNodes);
} :
function appendNodes(node, childNodes) {
for (var
i = 0,
length = childNodes.length;
i < length; i++
) {
node.appendChild(childNodes[i]);
}
};
// returns children or retrieve them in IE/Edge
var getChildren = WK || IE ?
function (node) {
for (var
child,
children = [],
childNodes = node.childNodes,
j = 0, i = 0, length = childNodes.length;
i < length; i++
) {
child = childNodes[i];
if (child.nodeType === ELEMENT_NODE)
children[j++] = child;
}
return children;
} :
function (node) { return node.children; };
// return the correct node walking through a path
// fixes IE/Edge issues with attributes and children (fixes old WebKit too)
var getNode = IE || WK ?
function (parentNode, path) {
for (var name, i = 0, length = path.length; i < length; i++) {
name = path[i++];
switch (name) {
case 'children':
parentNode = getChildren(parentNode)[path[i]];
break;
default:
parentNode = parentNode[name][path[i]];