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
1430 lines (1321 loc) · 49.9 KB
/
Copy pathindex.js
File metadata and controls
1430 lines (1321 loc) · 49.9 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 (global) {
'use strict';
var G = document.defaultView;
// Node.CONSTANTS
// 'cause some engine has no global Node defined
// (i.e. Node, NativeScript, basicHTML ... )
var ELEMENT_NODE = 1;
var TEXT_NODE = 3;
var COMMENT_NODE = 8;
var DOCUMENT_FRAGMENT_NODE = 11;
// HTML related constants
var VOID_ELEMENTS = /^area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr$/i;
// SVG related constants
var OWNER_SVG_ELEMENT = 'ownerSVGElement';
var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
// Custom Elements / MutationObserver constants
var CONNECTED = 'connected';
var DISCONNECTED = 'dis' + CONNECTED;
// hyperHTML related constants
var EXPANDO = '_hyper: ';
var SHOULD_USE_TEXT_CONTENT = /^style|textarea$/i;
var UID = EXPANDO + (Math.random() * new Date() | 0) + ';';
var UIDC = '<!--' + UID + '-->';
// you know that kind of basics you need to cover
// your use case only but you don't want to bloat the library?
// There's even a package in here:
// https://www.npmjs.com/package/poorlyfills
// used to dispatch simple events
var Event = G.Event;
try {
new Event('Event');
} catch (o_O) {
Event = function Event(type) {
var e = document.createEvent('Event');
e.initEvent(type, false, false);
return e;
};
}
// used to store template literals
/* istanbul ignore next */
var Map = G.Map || function Map() {
var keys = [],
values = [];
return {
get: function get(obj) {
return values[keys.indexOf(obj)];
},
set: function set(obj, value) {
values[keys.push(obj) - 1] = value;
}
};
};
// used to store wired content
var ID = 0;
var WeakMap = G.WeakMap || function WeakMap() {
var key = UID + ID++;
return {
get: function get(obj) {
return obj[key];
},
set: function set(obj, value) {
Object.defineProperty(obj, key, {
configurable: true,
value: value
});
}
};
};
// used to store hyper.Components
var WeakSet = G.WeakSet || function WeakSet() {
var wm = new WeakMap();
return {
add: function add(obj) {
wm.set(obj, true);
},
has: function has(obj) {
return wm.get(obj) === true;
}
};
};
// used to be sure IE9 or older Androids work as expected
var isArray = Array.isArray || function (toString) {
return function (arr) {
return toString.call(arr) === '[object Array]';
};
}({}.toString);
var trim = UID.trim || function () {
return this.replace(/^\s+|\s+$/g, '');
};
// hyperHTML.Component is a very basic class
// able to create Custom Elements like components
// including the ability to listen to connect/disconnect
// events via onconnect/ondisconnect attributes
// Components can be created imperatively or declaratively.
// The main difference is that declared components
// will not automatically render on setState(...)
// to simplify state handling on render.
function Component() {
return this; // this is needed in Edge !!!
}
// Component is lazily setup because it needs
// wire mechanism as lazy content
function setup(content) {
// there are various weakly referenced variables in here
// and mostly are to use Component.for(...) static method.
var children = new WeakMap();
var create = Object.create;
var createEntry = function createEntry(wm, id, component) {
wm.set(id, component);
return component;
};
var get = function get(Class, info, context, id) {
var relation = info.get(Class) || relate(Class, info);
switch (typeof id) {
case 'object':
case 'function':
var wm = relation.w || (relation.w = new WeakMap());
return wm.get(id) || createEntry(wm, id, new Class(context));
default:
var sm = relation.p || (relation.p = create(null));
return sm[id] || (sm[id] = new Class(context));
}
};
var relate = function relate(Class, info) {
var relation = { w: null, p: null };
info.set(Class, relation);
return relation;
};
var set = function set(context) {
var info = new Map();
children.set(context, info);
return info;
};
// The Component Class
Object.defineProperties(Component, {
// Component.for(context[, id]) is a convenient way
// to automatically relate data/context to children components
// If not created yet, the new Component(context) is weakly stored
// and after that same instance would always be returned.
for: {
configurable: true,
value: function value(context, id) {
return get(this, children.get(context) || set(context), context, id == null ? 'default' : id);
}
}
});
Object.defineProperties(Component.prototype, {
// all events are handled with the component as context
handleEvent: {
value: function value(e) {
var ct = e.currentTarget;
this['getAttribute' in ct && ct.getAttribute('data-call') || 'on' + e.type](e);
}
},
// components will lazily define html or svg properties
// as soon as these are invoked within the .render() method
// Such render() method is not provided by the base class
// but it must be available through the Component extend.
// Declared components could implement a
// render(props) method too and use props as needed.
html: lazyGetter('html', content),
svg: lazyGetter('svg', content),
// the state is a very basic/simple mechanism inspired by Preact
state: lazyGetter('state', function () {
return this.defaultState;
}),
// it is possible to define a default state that'd be always an object otherwise
defaultState: {
get: function get() {
return {};
}
},
// dispatch a bubbling, cancelable, custom event
// through the first known/available node
dispatch: {
value: function value(type, detail) {
var _wire$ = this._wire$;
if (_wire$) {
var event = new CustomEvent(type, {
bubbles: true,
cancelable: true,
detail: detail
});
event.component = this;
return (_wire$.dispatchEvent ? _wire$ : _wire$.childNodes[0]).dispatchEvent(event);
}
return false;
}
},
// setting some property state through a new object
// or a callback, triggers also automatically a render
// unless explicitly specified to not do so (render === false)
setState: {
value: function value(state, render) {
var target = this.state;
var source = typeof state === 'function' ? state.call(this, target) : state;
for (var key in source) {
target[key] = source[key];
}if (render !== false) this.render();
return this;
}
}
});
}
// instead of a secret key I could've used a WeakMap
// However, attaching a property directly will result
// into better performance with thousands of components
// hanging around, and less memory pressure caused by the WeakMap
var lazyGetter = function lazyGetter(type, fn) {
var secret = '_' + type + '$';
return {
get: function get() {
return this[secret] || setValue(this, secret, fn.call(this, type));
},
set: function set(value) {
setValue(this, secret, value);
}
};
};
// shortcut to set value on get or set(value)
var setValue = function setValue(self, secret, value) {
return Object.defineProperty(self, secret, {
configurable: true,
value: typeof value === 'function' ? function () {
return self._wire$ = value.apply(this, arguments);
} : value
})[secret];
};
var attributes = {};
var intents = {};
var keys = [];
var hasOwnProperty = intents.hasOwnProperty;
var length = 0;
var Intent = {
// used to invoke right away hyper:attributes
attributes: attributes,
// hyperHTML.define('intent', (object, update) => {...})
// can be used to define a third parts update mechanism
// when every other known mechanism failed.
// hyper.define('user', info => info.name);
// hyper(node)`<p>${{user}}</p>`;
define: function define(intent, callback) {
if (intent.indexOf('-') < 0) {
if (!(intent in intents)) {
length = keys.push(intent);
}
intents[intent] = callback;
} else {
attributes[intent] = callback;
}
},
// this method is used internally as last resort
// to retrieve a value out of an object
invoke: function invoke(object, callback) {
for (var i = 0; i < length; i++) {
var key = keys[i];
if (hasOwnProperty.call(object, key)) {
return intents[key](object[key], callback);
}
}
}
};
// these are tiny helpers to simplify most common operations needed here
var create = function create(node, type) {
return doc(node).createElement(type);
};
var doc = function doc(node) {
return node.ownerDocument || node;
};
var fragment = function fragment(node) {
return doc(node).createDocumentFragment();
};
var text = function text(node, _text) {
return doc(node).createTextNode(_text);
};
// TODO: I'd love to code-cover RegExp too here
// these are fundamental for this library
var spaces = ' \\f\\n\\r\\t';
var almostEverything = '[^ ' + spaces + '\\/>"\'=]+';
var attrName = '[ ' + spaces + ']+' + almostEverything;
var tagName = '<([A-Za-z]+[A-Za-z0-9:_-]*)((?:';
var attrPartials = '(?:=(?:\'[^\']*?\'|"[^"]*?"|<[^>]*?>|' + almostEverything + '))?)';
var attrSeeker = new RegExp(tagName + attrName + attrPartials + '+)([ ' + spaces + ']*/?>)', 'g');
var selfClosing = new RegExp(tagName + attrName + attrPartials + '*)([ ' + spaces + ']*/>)', 'g');
var testFragment = fragment(document);
// DOM4 node.append(...many)
var hasAppend = 'append' in testFragment;
// detect old browsers without HTMLTemplateElement content support
var hasContent = 'content' in create(document, 'template');
// IE 11 has problems with cloning templates: it "forgets" empty childNodes
testFragment.appendChild(text(testFragment, 'g'));
testFragment.appendChild(text(testFragment, ''));
var hasDoomedCloneNode = testFragment.cloneNode(true).childNodes.length === 1;
// old browsers need to fallback to cloneNode
// Custom Elements V0 and V1 will work polyfilled
// but native implementations need importNode instead
// (specially Chromium and its old V0 implementation)
var hasImportNode = 'importNode' in document;
// appends an array of nodes
// to a generic node/fragment
// When available, uses append passing all arguments at once
// hoping that's somehow faster, even if append has more checks on type
var append = hasAppend ? function (node, childNodes) {
node.append.apply(node, childNodes);
} : function (node, childNodes) {
var length = childNodes.length;
for (var i = 0; i < length; i++) {
node.appendChild(childNodes[i]);
}
};
var findAttributes = new RegExp('(' + attrName + '=)([\'"]?)' + UIDC + '\\2', 'gi');
var comments = function comments($0, $1, $2, $3) {
return '<' + $1 + $2.replace(findAttributes, replaceAttributes) + $3;
};
var replaceAttributes = function replaceAttributes($0, $1, $2) {
return $1 + ($2 || '"') + UID + ($2 || '"');
};
// given a node and a generic HTML content,
// create either an SVG or an HTML fragment
// where such content will be injected
var createFragment = function createFragment(node, html) {
return (OWNER_SVG_ELEMENT in node ? SVGFragment : HTMLFragment)(node, html.replace(attrSeeker, comments));
};
// IE/Edge shenanigans proof cloneNode
// it goes through all nodes manually
// instead of relying the engine to suddenly
// merge nodes together
var cloneNode = hasDoomedCloneNode ? function (node) {
var clone = node.cloneNode();
var childNodes = node.childNodes ||
// this is an excess of caution
// but some node, in IE, might not
// have childNodes property.
// The following fallback ensure working code
// in older IE without compromising performance
// or any other browser/engine involved.
/* istanbul ignore next */
[];
var length = childNodes.length;
for (var i = 0; i < length; i++) {
clone.appendChild(cloneNode(childNodes[i]));
}
return clone;
} :
// the following ignore is due code-coverage
// combination of not having document.importNode
// but having a working node.cloneNode.
// This shenario is common on older Android/WebKit browsers
// but basicHTML here tests just two major cases:
// with document.importNode or with broken cloneNode.
/* istanbul ignore next */
function (node) {
return node.cloneNode(true);
};
// IE and Edge do not support children in SVG nodes
/* istanbul ignore next */
var getChildren = function getChildren(node) {
var children = [];
var childNodes = node.childNodes;
var length = childNodes.length;
for (var i = 0; i < length; i++) {
if (childNodes[i].nodeType === ELEMENT_NODE) children.push(childNodes[i]);
}
return children;
};
// used to import html into fragments
var importNode = hasImportNode ? function (doc$$1, node) {
return doc$$1.importNode(node, true);
} : function (doc$$1, node) {
return cloneNode(node);
};
// just recycling a one-off array to use slice
// in every needed place
var slice = [].slice;
// lazy evaluated, returns the unique identity
// of a template literal, as tempalte literal itself.
// By default, ES2015 template literals are unique
// tag`a${1}z` === tag`a${2}z`
// even if interpolated values are different
// the template chunks are in a frozen Array
// that is identical each time you use the same
// literal to represent same static content
// around its own interpolations.
var unique = function unique(template) {
return _TL(template);
};
// TL returns a unique version of the template
// it needs lazy feature detection
// (cannot trust literals with transpiled code)
var _TL = function TL(t) {
if (
// TypeScript template literals are not standard
t.propertyIsEnumerable('raw') ||
// Firefox < 55 has not standard implementation neither
/Firefox\/(\d+)/.test((G.navigator || {}).userAgent) && parseFloat(RegExp.$1) < 55) {
var T = {};
_TL = function TL(t) {
var k = '^' + t.join('^');
return T[k] || (T[k] = t);
};
} else {
// make TL an identity like function
_TL = function TL(t) {
return t;
};
}
return _TL(t);
};
// used to store templates objects
// since neither Map nor WeakMap are safe
var TemplateMap = function TemplateMap() {
try {
var wm = new WeakMap();
var o_O = Object.freeze([]);
wm.set(o_O, true);
if (!wm.get(o_O)) throw o_O;
return wm;
} catch (o_O) {
// inevitable legacy code leaks due
// https://github.com/tc39/ecma262/pull/890
return new Map();
}
};
// create document fragments via native template
// with a fallback for browsers that won't be able
// to deal with some injected element such <td> or others
var HTMLFragment = hasContent ? function (node, html) {
var container = create(node, 'template');
container.innerHTML = html;
return container.content;
} : function (node, html) {
var container = create(node, 'template');
var content = fragment(node);
if (/^[^\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(html)) {
var selector = RegExp.$1;
container.innerHTML = '<table>' + html + '</table>';
append(content, slice.call(container.querySelectorAll(selector)));
} else {
container.innerHTML = html;
append(content, slice.call(container.childNodes));
}
return content;
};
// creates SVG fragment with a fallback for IE that needs SVG
// within the HTML content
var SVGFragment = hasContent ? function (node, html) {
var content = fragment(node);
var container = doc(node).createElementNS(SVG_NAMESPACE, 'svg');
container.innerHTML = html;
append(content, slice.call(container.childNodes));
return content;
} : function (node, html) {
var content = fragment(node);
var container = create(node, 'div');
container.innerHTML = '<svg xmlns="' + SVG_NAMESPACE + '">' + html + '</svg>';
append(content, slice.call(container.firstChild.childNodes));
return content;
};
function Wire(childNodes) {
this.childNodes = childNodes;
this.length = childNodes.length;
this.first = childNodes[0];
this.last = childNodes[this.length - 1];
}
// when a wire is inserted, all its nodes will follow
Wire.prototype.insert = function insert() {
var df = fragment(this.first);
append(df, this.childNodes);
return df;
};
// when a wire is removed, all its nodes must be removed as well
Wire.prototype.remove = function remove() {
var first = this.first;
var last = this.last;
if (this.length === 2) {
last.parentNode.removeChild(last);
} else {
var range = doc(first).createRange();
range.setStartBefore(this.childNodes[1]);
range.setEndAfter(last);
range.deleteContents();
}
return first;
};
// every template literal interpolation indicates
// a precise target in the DOM the template is representing.
// `<p id=${'attribute'}>some ${'content'}</p>`
// hyperHTML finds only once per template literal,
// hence once per entire application life-cycle,
// all nodes that are related to interpolations.
// These nodes are stored as indexes used to retrieve,
// once per upgrade, nodes that will change on each future update.
// A path example is [2, 0, 1] representing the operation:
// node.childNodes[2].childNodes[0].childNodes[1]
// Attributes are addressed via their owner node and their name.
var createPath = function createPath(node) {
var path = [];
var parentNode = void 0;
switch (node.nodeType) {
case ELEMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
parentNode = node;
break;
case COMMENT_NODE:
parentNode = node.parentNode;
prepend(path, parentNode, node);
break;
default:
parentNode = node.ownerElement;
break;
}
for (node = parentNode; parentNode = parentNode.parentNode; node = parentNode) {
prepend(path, parentNode, node);
}
return path;
};
var prepend = function prepend(path, parent, node) {
path.unshift(path.indexOf.call(parent.childNodes, node));
};
var Path = {
create: function create(type, node, name) {
return { type: type, name: name, node: node, path: createPath(node) };
},
find: function find(node, path) {
var length = path.length;
for (var i = 0; i < length; i++) {
node = node.childNodes[path[i]];
}
return node;
}
};
// from https://github.com/developit/preact/blob/33fc697ac11762a1cb6e71e9847670d047af7ce5/src/constants.js
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
// style is handled as both string and object
// even if the target is an SVG element (consistency)
var Style = (function (node, original, isSVG) {
if (isSVG) {
var style = original.cloneNode(true);
style.value = '';
node.setAttributeNode(style);
return update(style, isSVG);
}
return update(node.style, isSVG);
});
// the update takes care or changing/replacing
// only properties that are different or
// in case of string, the whole node
var update = function update(style, isSVG) {
var oldType = void 0,
oldValue = void 0;
return function (newValue) {
switch (typeof newValue) {
case 'object':
if (newValue) {
if (oldType === 'object') {
if (!isSVG) {
if (oldValue !== newValue) {
for (var key in oldValue) {
if (!(key in newValue)) {
style[key] = '';
}
}
}
}
} else {
if (isSVG) style.value = '';else style.cssText = '';
}
var info = isSVG ? {} : style;
for (var _key in newValue) {
var value = newValue[_key];
info[_key] = typeof value === 'number' && !IS_NON_DIMENSIONAL.test(_key) ? value + 'px' : value;
}
oldType = 'object';
if (isSVG) style.value = toStyle(oldValue = info);else oldValue = newValue;
break;
}
default:
if (oldValue != newValue) {
oldType = 'string';
oldValue = newValue;
if (isSVG) style.value = newValue || '';else style.cssText = newValue || '';
}
break;
}
};
};
var hyphen = /([^A-Z])([A-Z]+)/g;
var ized = function ized($0, $1, $2) {
return $1 + '-' + $2.toLowerCase();
};
var toStyle = function toStyle(object) {
var css = [];
for (var key in object) {
css.push(key.replace(hyphen, ized), ':', object[key], ';');
}
return css.join('');
};
/* AUTOMATICALLY IMPORTED, DO NOT MODIFY */
/*! (c) 2017 Andrea Giammarchi (ISC) */
/**
* This code is a revisited port of the snabbdom vDOM diffing logic,
* the same that fuels as fork Vue.js or other libraries.
* @credits https://github.com/snabbdom/snabbdom
*/
var eqeq = function eqeq(a, b) {
return a == b;
};
var identity = function identity(O) {
return O;
};
var remove = function remove(get, parentNode, before, after) {
if (after == null) {
parentNode.removeChild(get(before, -1));
} else {
var range = parentNode.ownerDocument.createRange();
range.setStartBefore(get(before, -1));
range.setEndAfter(get(after, -1));
range.deleteContents();
}
};
var domdiff = function domdiff(parentNode, // where changes happen
currentNodes, // Array of current items/nodes
futureNodes, // Array of future items/nodes
options // optional object with one of the following properties
// before: domNode
// compare(generic, generic) => true if same generic
// node(generic) => Node
) {
if (!options) options = {};
var compare = options.compare || eqeq;
var get = options.node || identity;
var before = options.before == null ? null : get(options.before, 0);
var currentStart = 0,
futureStart = 0;
var currentEnd = currentNodes.length - 1;
var currentStartNode = currentNodes[0];
var currentEndNode = currentNodes[currentEnd];
var futureEnd = futureNodes.length - 1;
var futureStartNode = futureNodes[0];
var futureEndNode = futureNodes[futureEnd];
while (currentStart <= currentEnd && futureStart <= futureEnd) {
if (currentStartNode == null) {
currentStartNode = currentNodes[++currentStart];
} else if (currentEndNode == null) {
currentEndNode = currentNodes[--currentEnd];
} else if (futureStartNode == null) {
futureStartNode = futureNodes[++futureStart];
} else if (futureEndNode == null) {
futureEndNode = futureNodes[--futureEnd];
} else if (compare(currentStartNode, futureStartNode)) {
currentStartNode = currentNodes[++currentStart];
futureStartNode = futureNodes[++futureStart];
} else if (compare(currentEndNode, futureEndNode)) {
currentEndNode = currentNodes[--currentEnd];
futureEndNode = futureNodes[--futureEnd];
} else if (compare(currentStartNode, futureEndNode)) {
parentNode.insertBefore(get(currentStartNode, 1), get(currentEndNode, -0).nextSibling);
currentStartNode = currentNodes[++currentStart];
futureEndNode = futureNodes[--futureEnd];
} else if (compare(currentEndNode, futureStartNode)) {
parentNode.insertBefore(get(currentEndNode, 1), get(currentStartNode, 0));
currentEndNode = currentNodes[--currentEnd];
futureStartNode = futureNodes[++futureStart];
} else {
var index = currentNodes.indexOf(futureStartNode);
if (index < 0) {
parentNode.insertBefore(get(futureStartNode, 1), get(currentStartNode, 0));
futureStartNode = futureNodes[++futureStart];
} else {
var i = index;
var f = futureStart;
while (i <= currentEnd && f <= futureEnd && currentNodes[i] === futureNodes[f]) {
i++;
f++;
}
if (1 < i - index) {
if (--index === currentStart) {
parentNode.removeChild(get(currentStartNode, -1));
} else {
remove(get, parentNode, currentStartNode, currentNodes[index]);
}
currentStart = i;
futureStart = f;
currentStartNode = currentNodes[i];
futureStartNode = futureNodes[f];
} else {
var el = currentNodes[index];
currentNodes[index] = null;
parentNode.insertBefore(get(el, 1), get(currentStartNode, 0));
futureStartNode = futureNodes[++futureStart];
}
}
}
}
if (currentStart <= currentEnd || futureStart <= futureEnd) {
if (currentStart > currentEnd) {
var pin = futureNodes[futureEnd + 1];
var place = pin == null ? before : get(pin, 0);
if (futureStart === futureEnd) {
parentNode.insertBefore(get(futureNodes[futureStart], 1), place);
} else {
var fragment = parentNode.ownerDocument.createDocumentFragment();
while (futureStart <= futureEnd) {
fragment.appendChild(get(futureNodes[futureStart++], 1));
}
parentNode.insertBefore(fragment, place);
}
} else {
if (currentNodes[currentStart] == null) currentStart++;
if (currentStart === currentEnd) {
parentNode.removeChild(get(currentNodes[currentStart], -1));
} else {
remove(get, parentNode, currentNodes[currentStart], currentNodes[currentEnd]);
}
}
}
return futureNodes;
};
// hyper.Component have a connected/disconnected
// mechanism provided by MutationObserver
// This weak set is used to recognize components
// as DOM node that needs to trigger connected/disconnected events
var components = new WeakSet();
// a basic dictionary used to filter already cached attributes
// while looking for special hyperHTML values.
function Cache() {}
Cache.prototype = Object.create(null);
// returns an intent to explicitly inject content as html
var asHTML = function asHTML(html) {
return { html: html };
};
// returns nodes from wires and components
var asNode = function asNode(item, i) {
return 'ELEMENT_NODE' in item ? item : item.constructor === Wire ?
// in the Wire case, the content can be
// removed, post-pended, inserted, or pre-pended and
// all these cases are handled by domdiff already
/* istanbul ignore next */
1 / i < 0 ? i ? item.remove() : item.last : i ? item.insert() : item.first : asNode(item.render(), i);
};
// returns true if domdiff can handle the value
var canDiff = function canDiff(value) {
return 'ELEMENT_NODE' in value || value instanceof Wire || value instanceof Component;
};
// updates are created once per context upgrade
// within the main render function (../hyper/render.js)
// These are an Array of callbacks to invoke passing
// each interpolation value.
// Updates can be related to any kind of content,
// attributes, or special text-only cases such <style>
// elements or <textarea>
var create$1 = function create$$1(root, paths) {
var updates = [];
var length = paths.length;
for (var i = 0; i < length; i++) {
var info = paths[i];
var node = Path.find(root, info.path);
switch (info.type) {
case 'any':
updates.push(setAnyContent(node, []));
break;
case 'attr':
updates.push(setAttribute(node, info.name, info.node));
break;
case 'text':
updates.push(setTextContent(node));
node.textContent = '';
break;
}
}
return updates;
};
// finding all paths is a one-off operation performed
// when a new template literal is used.
// The goal is to map all target nodes that will be
// used to update content/attributes every time
// the same template literal is used to create content.
// The result is a list of paths related to the template
// with all the necessary info to create updates as
// list of callbacks that target directly affected nodes.
var find = function find(node, paths, parts) {
var childNodes = node.childNodes;
var length = childNodes.length;
for (var i = 0; i < length; i++) {
var child = childNodes[i];
switch (child.nodeType) {
case ELEMENT_NODE:
findAttributes$1(child, paths, parts);
find(child, paths, parts);
break;
case COMMENT_NODE:
if (child.textContent === UID) {
parts.shift();
paths.push(
// basicHTML or other non standard engines
// might end up having comments in nodes
// where they shouldn't, hence this check.
SHOULD_USE_TEXT_CONTENT.test(node.nodeName) ? Path.create('text', node) : Path.create('any', child));
}
break;
case TEXT_NODE:
// the following ignore is actually covered by browsers
// only basicHTML ends up on previous COMMENT_NODE case
// instead of TEXT_NODE because it knows nothing about
// special style or textarea behavior
/* istanbul ignore if */
if (SHOULD_USE_TEXT_CONTENT.test(node.nodeName) && trim.call(child.textContent) === UIDC) {
parts.shift();
paths.push(Path.create('text', node));
}
break;
}
}
};
// attributes are searched via unique hyperHTML id value.
// Despite HTML being case insensitive, hyperHTML is able
// to recognize attributes by name in a caseSensitive way.
// This plays well with Custom Elements definitions
// and also with XML-like environments, without trusting
// the resulting DOM but the template literal as the source of truth.
// IE/Edge has a funny bug with attributes and these might be duplicated.
// This is why there is a cache in charge of being sure no duplicated
// attributes are ever considered in future updates.
var findAttributes$1 = function findAttributes(node, paths, parts) {
var cache = new Cache();
var attributes = node.attributes;
var array = slice.call(attributes);
var remove = [];
var length = array.length;
for (var i = 0; i < length; i++) {
var attribute = array[i];
if (attribute.value === UID) {
var name = attribute.name;
// the following ignore is covered by IE
// and the IE9 double viewBox test
/* istanbul ignore else */
if (!(name in cache)) {
var realName = parts.shift().replace(/^(?:|[\S\s]*?\s)(\S+?)=['"]?$/, '$1');
cache[name] = attributes[realName] ||
// the following ignore is covered by browsers
// while basicHTML is already case-sensitive
/* istanbul ignore next */
attributes[realName.toLowerCase()];
paths.push(Path.create('attr', cache[name], realName));
}
remove.push(attribute);
}
}
var len = remove.length;
for (var _i = 0; _i < len; _i++) {
// Edge HTML bug #16878726
var _attribute = remove[_i];
if (/^id$/i.test(_attribute.name)) node.removeAttribute(_attribute.name);
// standard browsers would work just fine here
else node.removeAttributeNode(remove[_i]);
}
// This is a very specific Firefox/Safari issue
// but since it should be a not so common pattern,
// it's probably worth patching regardless.
// Basically, scripts created through strings are death.
// You need to create fresh new scripts instead.
// TODO: is there any other node that needs such nonsense?
var nodeName = node.nodeName;
if (/^script$/i.test(nodeName)) {
// this used to be like that
// const script = createElement(node, nodeName);
// then Edge arrived and decided that scripts created
// through template documents aren't worth executing
// so it became this ... hopefully it won't hurt in the wild
var script = document.createElement(nodeName);
for (var _i2 = 0; _i2 < attributes.length; _i2++) {
script.setAttributeNode(attributes[_i2].cloneNode(true));
}
script.textContent = node.textContent;
node.parentNode.replaceChild(script, node);
}
};
// when a Promise is used as interpolation value
// its result must be parsed once resolved.
// This callback is in charge of understanding what to do
// with a returned value once the promise is resolved.
var invokeAtDistance = 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(Intent.invoke(value, callback)).then(callback);
}
};
// quick and dirty way to check for Promise/ish values
var isPromise_ish = function isPromise_ish(value) {
return value != null && 'then' in value;
};
// in a hyper(node)`<div>${content}</div>` case
// everything could happen:
// * it's a JS primitive, stored as text
// * it's null or undefined, the node should be cleaned
// * it's a component, update the content by rendering it
// * it's a promise, update the content once resolved
// * it's an explicit intent, perform the desired operation
// * it's an Array, resolve all values if Promises and/or
// update the node with the resulting list of content
var setAnyContent = function setAnyContent(node, childNodes) {
var diffOptions = { node: asNode, before: node };
var fastPath = false;
var oldValue = void 0;
var anyContent = function anyContent(value) {
switch (typeof value) {
case 'string':
case 'number':
case 'boolean':
if (fastPath) {
if (oldValue !== value) {
oldValue = value;
childNodes[0].textContent = value;
}
} else {
fastPath = true;
oldValue = value;
childNodes = domdiff(node.parentNode, childNodes, [text(node, value)], diffOptions);
}
break;