-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
1268 lines (1152 loc) · 42 KB
/
index.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
self.uland = (function (exports) {
'use strict';
/**
* @typedef {Object} Handler an object that handle events.
* @property {(event: Event) => void} connected an optional method triggered when node is connected.
* @property {(event: Event) => void} disconnected an optional method triggered when node is disconnected.
*/
/**
* @typedef {Object} UConnect an utility to connect or disconnect nodes to observe.
* @property {(node: Node, handler?: Handler) => void} connect a method to start observing a generic Node.
* @property {(node: Node) => void} disconnect a method to stop observing a generic Node.
* @property {() => void} kill a method to kill/disconnect the MutationObserver.
*/
/**
* Attach a MutationObserver to a generic node and returns a UConnect instance.
* @param {Node} root a DOM node to observe for mutations.
* @param {string} parse the kind of nodes to parse: children, by default, or childNodes.
* @param {Event} CE an Event/CustomEvent constructor (polyfilled in SSR).
* @param {MutationObserver} MO a MutationObserver constructor (polyfilled in SSR).
* @returns {UConnect} an utility to connect or disconnect nodes to observe.
*/
const observe = (root, parse, CE, MO) => {
const observed = new WeakMap;
// these two should be WeakSet but IE11 happens
const wmin = new WeakMap;
const wmout = new WeakMap;
const has = node => observed.has(node);
const disconnect = node => {
if (has(node)) {
listener(node, node.removeEventListener, observed.get(node));
observed.delete(node);
}
};
const connect = (node, handler) => {
disconnect(node);
if (!(handler || (handler = {})).handleEvent)
handler.handleEvent = handleEvent;
listener(node, node.addEventListener, handler);
observed.set(node, handler);
};
const listener = (node, method, handler) => {
method.call(node, 'disconnected', handler);
method.call(node, 'connected', handler);
};
const notifyObserved = (nodes, type, wmin, wmout) => {
for (let {length} = nodes, i = 0; i < length; i++)
notifyTarget(nodes[i], type, wmin, wmout);
};
const notifyTarget = (node, type, wmin, wmout) => {
if (has(node) && !wmin.has(node)) {
wmout.delete(node);
wmin.set(node, 0);
node.dispatchEvent(new (CE || CustomEvent)(type));
}
notifyObserved(node[parse || 'children'] || [], type, wmin, wmout);
};
const mo = new (MO || MutationObserver)(nodes => {
for (let {length} = nodes, i = 0; i < length; i++) {
const {removedNodes, addedNodes} = nodes[i];
notifyObserved(removedNodes, 'disconnected', wmout, wmin);
notifyObserved(addedNodes, 'connected', wmin, wmout);
}
});
mo.add = add;
mo.add(root || document);
const {attachShadow} = Element.prototype;
if (attachShadow)
Element.prototype.attachShadow = function (init) {
const sd = attachShadow.call(this, init);
mo.add(sd);
return sd;
};
return {has, connect, disconnect, kill() { mo.disconnect(); }};
};
function add(node) {
this.observe(node, {subtree: true, childList: true});
}
function handleEvent(event) {
if (event.type in this)
this[event.type](event);
}
let info = null, schedule = new Set;
const invoke = effect => {
const {$, r, h} = effect;
if (isFunction(r)) {
fx$1.get(h).delete(effect);
r();
}
if (isFunction(effect.r = $()))
fx$1.get(h).add(effect);
};
const runSchedule = () => {
const previous = schedule;
schedule = new Set;
previous.forEach(({h, c, a, e}) => {
// avoid running schedules when the hook is
// re-executed before such schedule happens
if (e)
h.apply(c, a);
});
};
const fx$1 = new WeakMap;
const effects = [];
const layoutEffects = [];
function different(value, i) {
return value !== this[i];
}
const dropEffect = hook => {
const effects = fx$1.get(hook);
if (effects)
wait.then(() => {
effects.forEach(effect => {
effect.r();
effect.r = null;
effect.d = true;
});
effects.clear();
});
};
const getInfo = () => info;
const hasEffect = hook => fx$1.has(hook);
const isFunction = f => typeof f === 'function';
const hooked$2 = callback => {
const current = {h: hook, c: null, a: null, e: 0, i: 0, s: []};
return hook;
function hook() {
const prev = info;
info = current;
current.e = current.i = 0;
try {
return callback.apply(current.c = this, current.a = arguments);
}
finally {
info = prev;
if (effects.length)
wait.then(effects.forEach.bind(effects.splice(0), invoke));
if (layoutEffects.length)
layoutEffects.splice(0).forEach(invoke);
}
}
};
const reschedule = info => {
if (!schedule.has(info)) {
info.e = 1;
schedule.add(info);
wait.then(runSchedule);
}
};
const wait = Promise.resolve();
const createContext = value => ({
_: new Set,
provide,
value
});
const useContext = ({_, value}) => {
_.add(getInfo());
return value;
};
function provide(newValue) {
const {_, value} = this;
if (value !== newValue) {
this._ = new Set;
this.value = newValue;
_.forEach(({h, c, a}) => {
h.apply(c, a);
});
}
}
const useCallback = (fn, guards) => useMemo(() => fn, guards);
const useMemo = (memo, guards) => {
const info = getInfo();
const {i, s} = info;
if (i === s.length || !guards || guards.some(different, s[i]._))
s[i] = {$: memo(), _: guards};
return s[info.i++].$;
};
const createEffect = stack => (callback, guards) => {
const info = getInfo();
const {i, s, h} = info;
const call = i === s.length;
info.i++;
if (call) {
if (!fx$1.has(h))
fx$1.set(h, new Set);
s[i] = {$: callback, _: guards, r: null, d: false, h};
}
if (call || !guards || s[i].d || guards.some(different, s[i]._))
stack.push(s[i]);
s[i].$ = callback;
s[i]._ = guards;
s[i].d = false;
};
const useEffect = createEffect(effects);
const useLayoutEffect = createEffect(layoutEffects);
const getValue = (value, f) => isFunction(f) ? f(value) : f;
const useReducer$1 = (reducer, value, init) => {
const info = getInfo();
const {i, s} = info;
if (i === s.length)
s.push({
$: isFunction(init) ?
init(value) : getValue(void 0, value),
set: value => {
s[i].$ = reducer(s[i].$, value);
reschedule(info);
}
});
const {$, set} = s[info.i++];
return [$, set];
};
const useState$1 = value => useReducer$1(getValue, value);
const useRef = current => {
const info = getInfo();
const {i, s} = info;
if (i === s.length)
s.push({current});
return s[info.i++];
};
/*! (c) Andrea Giammarchi - ISC */
let h = null, c = null, a = null;
const fx = new WeakMap;
const states = new WeakMap;
const set = (h, c, a, update) => {
const wrap = value => {
if (!fx.has(h)) {
fx.set(h, 0);
wait.then(() => {
fx.delete(h);
h.apply(c, a);
});
}
update(value);
};
states.set(update, wrap);
return wrap;
};
const wrap = (h, c, a, state) => (
h ? [
state[0],
states.get(state[1]) || set(h, c, a, state[1])
] :
state
);
const hooked$1 = (callback, outer) => {
const hook = hooked$2(
outer ?
/*async*/ function () {
const [ph, pc, pa] = [h, c, a];
[h, c, a] = [hook, this, arguments];
try {
return /*await*/ callback.apply(c, a);
}
finally {
[h, c, a] = [ph, pc, pa];
}
} :
callback
);
return hook;
};
const useReducer = (reducer, value, init) =>
wrap(h, c, a, useReducer$1(reducer, value, init));
const useState = value => wrap(h, c, a, useState$1(value));
/*! (c) Andrea Giammarchi - ISC */
const observer = observe(document, 'children', CustomEvent);
const find = ({firstChild}) => {
if (
firstChild &&
firstChild.nodeType !== 1 &&
!(firstChild = firstChild.nextElementSibling)
)
throw 'unobservable';
return firstChild;
};
const get = node => {
const {nodeType} = node;
if (nodeType)
return nodeType === 1 ? node : find(node);
else {
// give a chance to facades to return a reasonable value
const value = node.valueOf();
return value !== node ? get(value) : find(value);
}
};
const hooked = (fn, outer) => {
const hook = hooked$1(fn, outer);
return /*async*/ function () {
const node = /*await*/ hook.apply(this, arguments);
if (hasEffect(hook)) {
const element = get(node);
if (!observer.has(element))
observer.connect(element, {
disconnected() {
dropEffect(hook);
}
});
}
return node;
};
};
var umap = _ => ({
// About: get: _.get.bind(_)
// It looks like WebKit/Safari didn't optimize bind at all,
// so that using bind slows it down by 60%.
// Firefox and Chrome are just fine in both cases,
// so let's use the approach that works fast everywhere 👍
get: key => _.get(key),
set: (key, value) => (_.set(key, value), value)
});
const {isArray: isArray$1} = Array;
class MapSet extends Map {
set(key, value) {
super.set(key, value);
return value;
}
}
class WeakMapSet extends WeakMap {
set(key, value) {
super.set(key, value);
return value;
}
}
/*! (c) Andrea Giammarchi - ISC */
const empty = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
const elements = /<([a-z]+[a-z0-9:._-]*)([^>]*?)(\/?)>/g;
const attributes = /([^\s\\>"'=]+)\s*=\s*(['"]?)\x01/g;
const holes = /[\x01\x02]/g;
// \x01 Node.ELEMENT_NODE
// \x02 Node.ATTRIBUTE_NODE
/**
* Given a template, find holes as both nodes and attributes and
* return a string with holes as either comment nodes or named attributes.
* @param {string[]} template a template literal tag array
* @param {string} prefix prefix to use per each comment/attribute
* @param {boolean} svg enforces self-closing tags
* @returns {string} X/HTML with prefixed comments or attributes
*/
var instrument = (template, prefix, svg) => {
let i = 0;
return template
.join('\x01')
.trim()
.replace(
elements,
(_, name, attrs, selfClosing) => {
let ml = name + attrs.replace(attributes, '\x02=$2$1').trimEnd();
if (selfClosing.length)
ml += (svg || empty.test(name)) ? ' /' : ('></' + name);
return '<' + ml + '>';
}
)
.replace(
holes,
hole => hole === '\x01' ?
('<!--' + prefix + i++ + '-->') :
(prefix + i++)
);
};
const ELEMENT_NODE = 1;
const nodeType = 111;
const remove = ({firstChild, lastChild}) => {
const range = document.createRange();
range.setStartAfter(firstChild);
range.setEndAfter(lastChild);
range.deleteContents();
return firstChild;
};
const diffable = (node, operation) => node.nodeType === nodeType ?
((1 / operation) < 0 ?
(operation ? remove(node) : node.lastChild) :
(operation ? node.valueOf() : node.firstChild)) :
node
;
const persistent = fragment => {
const {firstChild, lastChild} = fragment;
if (firstChild === lastChild)
return lastChild || fragment;
const {childNodes} = fragment;
const nodes = [...childNodes];
return {
ELEMENT_NODE,
nodeType,
firstChild,
lastChild,
valueOf() {
if (childNodes.length !== nodes.length)
fragment.append(...nodes);
return fragment;
}
};
};
const aria = node => values => {
for (const key in values) {
const name = key === 'role' ? key : `aria-${key}`;
const value = values[key];
if (value == null)
node.removeAttribute(name);
else
node.setAttribute(name, value);
}
};
const attribute = (node, name) => {
let oldValue, orphan = true;
const attributeNode = document.createAttributeNS(null, name);
return newValue => {
if (oldValue !== newValue) {
oldValue = newValue;
if (oldValue == null) {
if (!orphan) {
node.removeAttributeNode(attributeNode);
orphan = true;
}
}
else {
const value = newValue;
if (value == null) {
if (!orphan)
node.removeAttributeNode(attributeNode);
orphan = true;
}
else {
attributeNode.value = value;
if (orphan) {
node.setAttributeNodeNS(attributeNode);
orphan = false;
}
}
}
}
};
};
const boolean = (node, key, oldValue) => newValue => {
if (oldValue !== !!newValue) {
// when IE won't be around anymore ...
// node.toggleAttribute(key, oldValue = !!newValue);
if ((oldValue = !!newValue))
node.setAttribute(key, '');
else
node.removeAttribute(key);
}
};
const data = ({dataset}) => values => {
for (const key in values) {
const value = values[key];
if (value == null)
delete dataset[key];
else
dataset[key] = value;
}
};
const event = (node, name) => {
let oldValue, lower, type = name.slice(2);
if (!(name in node) && (lower = name.toLowerCase()) in node)
type = lower.slice(2);
return newValue => {
const info = isArray$1(newValue) ? newValue : [newValue, false];
if (oldValue !== info[0]) {
if (oldValue)
node.removeEventListener(type, oldValue, info[1]);
if (oldValue = info[0])
node.addEventListener(type, oldValue, info[1]);
}
};
};
const ref = node => {
let oldValue;
return value => {
if (oldValue !== value) {
oldValue = value;
if (typeof value === 'function')
value(node);
else
value.current = node;
}
};
};
const setter = (node, key) => key === 'dataset' ?
data(node) :
value => {
node[key] = value;
};
const text = node => {
let oldValue;
return newValue => {
if (oldValue != newValue) {
oldValue = newValue;
node.textContent = newValue == null ? '' : newValue;
}
};
};
/**
* ISC License
*
* Copyright (c) 2020, Andrea Giammarchi, @WebReflection
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**
* @param {Node} parentNode The container where children live
* @param {Node[]} a The list of current/live children
* @param {Node[]} b The list of future children
* @param {(entry: Node, action: number) => Node} get
* The callback invoked per each entry related DOM operation.
* @param {Node} [before] The optional node used as anchor to insert before.
* @returns {Node[]} The same list of future children.
*/
var udomdiff = (parentNode, a, b, get, before) => {
const bLength = b.length;
let aEnd = a.length;
let bEnd = bLength;
let aStart = 0;
let bStart = 0;
let map = null;
while (aStart < aEnd || bStart < bEnd) {
// append head, tail, or nodes in between: fast path
if (aEnd === aStart) {
// we could be in a situation where the rest of nodes that
// need to be added are not at the end, and in such case
// the node to `insertBefore`, if the index is more than 0
// must be retrieved, otherwise it's gonna be the first item.
const node = bEnd < bLength ?
(bStart ?
(get(b[bStart - 1], -0).nextSibling) :
get(b[bEnd - bStart], 0)) :
before;
while (bStart < bEnd)
parentNode.insertBefore(get(b[bStart++], 1), node);
}
// remove head or tail: fast path
else if (bEnd === bStart) {
while (aStart < aEnd) {
// remove the node only if it's unknown or not live
if (!map || !map.has(a[aStart]))
parentNode.removeChild(get(a[aStart], -1));
aStart++;
}
}
// same node: fast path
else if (a[aStart] === b[bStart]) {
aStart++;
bStart++;
}
// same tail: fast path
else if (a[aEnd - 1] === b[bEnd - 1]) {
aEnd--;
bEnd--;
}
// The once here single last swap "fast path" has been removed in v1.1.0
// https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
// reverse swap: also fast path
else if (
a[aStart] === b[bEnd - 1] &&
b[bStart] === a[aEnd - 1]
) {
// this is a "shrink" operation that could happen in these cases:
// [1, 2, 3, 4, 5]
// [1, 4, 3, 2, 5]
// or asymmetric too
// [1, 2, 3, 4, 5]
// [1, 2, 3, 5, 6, 4]
const node = get(a[--aEnd], -1).nextSibling;
parentNode.insertBefore(
get(b[bStart++], 1),
get(a[aStart++], -1).nextSibling
);
parentNode.insertBefore(get(b[--bEnd], 1), node);
// mark the future index as identical (yeah, it's dirty, but cheap 👍)
// The main reason to do this, is that when a[aEnd] will be reached,
// the loop will likely be on the fast path, as identical to b[bEnd].
// In the best case scenario, the next loop will skip the tail,
// but in the worst one, this node will be considered as already
// processed, bailing out pretty quickly from the map index check
a[aEnd] = b[bEnd];
}
// map based fallback, "slow" path
else {
// the map requires an O(bEnd - bStart) operation once
// to store all future nodes indexes for later purposes.
// In the worst case scenario, this is a full O(N) cost,
// and such scenario happens at least when all nodes are different,
// but also if both first and last items of the lists are different
if (!map) {
map = new Map;
let i = bStart;
while (i < bEnd)
map.set(b[i], i++);
}
// if it's a future node, hence it needs some handling
if (map.has(a[aStart])) {
// grab the index of such node, 'cause it might have been processed
const index = map.get(a[aStart]);
// if it's not already processed, look on demand for the next LCS
if (bStart < index && index < bEnd) {
let i = aStart;
// counts the amount of nodes that are the same in the future
let sequence = 1;
while (++i < aEnd && i < bEnd && map.get(a[i]) === (index + sequence))
sequence++;
// effort decision here: if the sequence is longer than replaces
// needed to reach such sequence, which would brings again this loop
// to the fast path, prepend the difference before a sequence,
// and move only the future list index forward, so that aStart
// and bStart will be aligned again, hence on the fast path.
// An example considering aStart and bStart are both 0:
// a: [1, 2, 3, 4]
// b: [7, 1, 2, 3, 6]
// this would place 7 before 1 and, from that time on, 1, 2, and 3
// will be processed at zero cost
if (sequence > (index - bStart)) {
const node = get(a[aStart], 0);
while (bStart < index)
parentNode.insertBefore(get(b[bStart++], 1), node);
}
// if the effort wasn't good enough, fallback to a replace,
// moving both source and target indexes forward, hoping that some
// similar node will be found later on, to go back to the fast path
else {
parentNode.replaceChild(
get(b[bStart++], 1),
get(a[aStart++], -1)
);
}
}
// otherwise move the source forward, 'cause there's nothing to do
else
aStart++;
}
// this node has no meaning in the future list, so it's more than safe
// to remove it, and check the next live node out instead, meaning
// that only the live list index should be forwarded
else
parentNode.removeChild(get(a[aStart++], -1));
}
}
return b;
};
const {isArray, prototype} = Array;
const {indexOf} = prototype;
const {
createDocumentFragment,
createElement,
createElementNS,
createTextNode,
createTreeWalker,
importNode
} = new Proxy(document, {
get: (target, method) => target[method].bind(target)
});
const createHTML = html => {
const template = createElement('template');
template.innerHTML = html;
return template.content;
};
let xml;
const createSVG = svg => {
if (!xml) xml = createElementNS('http://www.w3.org/2000/svg', 'svg');
xml.innerHTML = svg;
const content = createDocumentFragment();
content.append(...xml.childNodes);
return content;
};
const createContent = (text, svg) => svg ?
createSVG(text) : createHTML(text);
// from a generic path, retrieves the exact targeted node
const reducePath = ({childNodes}, i) => childNodes[i];
// this helper avoid code bloat around handleAnything() callback
const diff = (comment, oldNodes, newNodes) => udomdiff(
comment.parentNode,
// TODO: there is a possible edge case where a node has been
// removed manually, or it was a keyed one, attached
// to a shared reference between renders.
// In this case udomdiff might fail at removing such node
// as its parent won't be the expected one.
// The best way to avoid this issue is to filter oldNodes
// in search of those not live, or not in the current parent
// anymore, but this would require both a change to uwire,
// exposing a parentNode from the firstChild, as example,
// but also a filter per each diff that should exclude nodes
// that are not in there, penalizing performance quite a lot.
// As this has been also a potential issue with domdiff,
// and both lighterhtml and hyperHTML might fail with this
// very specific edge case, I might as well document this possible
// "diffing shenanigan" and call it a day.
oldNodes,
newNodes,
diffable,
comment
);
// if an interpolation represents a comment, the whole
// diffing will be related to such comment.
// This helper is in charge of understanding how the new
// content for such interpolation/hole should be updated
const handleAnything = comment => {
let oldValue, text, nodes = [];
const anyContent = newValue => {
switch (typeof newValue) {
// primitives are handled as text content
case 'string':
case 'number':
case 'boolean':
if (oldValue !== newValue) {
oldValue = newValue;
if (!text)
text = createTextNode('');
text.data = newValue;
nodes = diff(comment, nodes, [text]);
}
break;
// null, and undefined are used to cleanup previous content
case 'object':
case 'undefined':
if (newValue == null) {
if (oldValue != newValue) {
oldValue = newValue;
nodes = diff(comment, nodes, []);
}
break;
}
// arrays and nodes have a special treatment
if (isArray(newValue)) {
oldValue = newValue;
// arrays can be used to cleanup, if empty
if (newValue.length === 0)
nodes = diff(comment, nodes, []);
// or diffed, if these contains nodes or "wires"
else if (typeof newValue[0] === 'object')
nodes = diff(comment, nodes, newValue);
// in all other cases the content is stringified as is
else
anyContent(String(newValue));
break;
}
// if the new value is a DOM node, or a wire, and it's
// different from the one already live, then it's diffed.
// if the node is a fragment, it's appended once via its childNodes
// There is no `else` here, meaning if the content
// is not expected one, nothing happens, as easy as that.
if (oldValue !== newValue && 'ELEMENT_NODE' in newValue) {
oldValue = newValue;
nodes = diff(
comment,
nodes,
newValue.nodeType === 11 ?
[...newValue.childNodes] :
[newValue]
);
}
break;
case 'function':
anyContent(newValue(comment));
break;
}
};
return anyContent;
};
// attributes can be:
// * ref=${...} for hooks and other purposes
// * aria=${...} for aria attributes
// * ?boolean=${...} for boolean attributes
// * .dataset=${...} for dataset related attributes
// * .setter=${...} for Custom Elements setters or nodes with setters
// such as buttons, details, options, select, etc
// * @event=${...} to explicitly handle event listeners
// * onevent=${...} to automatically handle event listeners
// * generic=${...} to handle an attribute just like an attribute
const handleAttribute = (node, name/*, svg*/) => {
switch (name[0]) {
case '?': return boolean(node, name.slice(1), false);
case '.': return setter(node, name.slice(1));
case '@': return event(node, 'on' + name.slice(1));
case 'o': if (name[1] === 'n') return event(node, name);
}
switch (name) {
case 'ref': return ref(node);
case 'aria': return aria(node);
}
return attribute(node, name/*, svg*/);
};
// each mapped update carries the update type and its path
// the type is either node, attribute, or text, while
// the path is how to retrieve the related node to update.
// In the attribute case, the attribute name is also carried along.
function handlers(options) {
const {type, path} = options;
const node = path.reduceRight(reducePath, this);
return type === 'node' ?
handleAnything(node) :
(type === 'attr' ?
handleAttribute(node, options.name/*, options.svg*/) :
text(node));
}
// from a fragment container, create an array of indexes
// related to its child nodes, so that it's possible
// to retrieve later on exact node via reducePath
const createPath = node => {
const path = [];
let {parentNode} = node;
while (parentNode) {
path.push(indexOf.call(parentNode.childNodes, node));
node = parentNode;
({parentNode} = node);
}
return path;
};
// the prefix is used to identify either comments, attributes, or nodes
// that contain the related unique id. In the attribute cases
// isµX="attribute-name" will be used to map current X update to that
// attribute name, while comments will be like <!--isµX-->, to map
// the update to that specific comment node, hence its parent.
// style and textarea will have <!--isµX--> text content, and are handled
// directly through text-only updates.
const prefix = 'isµ';
// Template Literals are unique per scope and static, meaning a template
// should be parsed once, and once only, as it will always represent the same
// content, within the exact same amount of updates each time.
// This cache relates each template to its unique content and updates.
const cache$2 = new WeakMapSet;
// a RegExp that helps checking nodes that cannot contain comments
const textOnly = /^(?:textarea|script|style|title|plaintext|xmp)$/;
const createCache$1 = () => ({
stack: [], // each template gets a stack for each interpolation "hole"
entry: null, // each entry contains details, such as:
// * the template that is representing
// * the type of node it represents (html or svg)
// * the content fragment with all nodes
// * the list of updates per each node (template holes)
// * the "wired" node or fragment that will get updates
// if the template or type are different from the previous one
// the entry gets re-created each time
wire: null // each rendered node represent some wired content and
// this reference to the latest one. If different, the node
// will be cleaned up and the new "wire" will be appended
});
// the entry stored in the rendered node cache, and per each "hole"
const createEntry = (type, template) => {
const {content, updates} = mapUpdates(type, template);
return {type, template, content, updates, wire: null};
};
// a template is instrumented to be able to retrieve where updates are needed.
// Each unique template becomes a fragment, cloned once per each other
// operation based on the same template, i.e. data => html`<p>${data}</p>`
const mapTemplate = (type, template) => {
const svg = type === 'svg';
const text = instrument(template, prefix, svg);
const content = createContent(text, svg);
// once instrumented and reproduced as fragment, it's crawled
// to find out where each update is in the fragment tree
const tw = createTreeWalker(content, 1 | 128);
const nodes = [];
const length = template.length - 1;
let i = 0;
// updates are searched via unique names, linearly increased across the tree
// <div isµ0="attr" isµ1="other"><!--isµ2--><style><!--isµ3--</style></div>
let search = `${prefix}${i}`;
while (i < length) {
const node = tw.nextNode();
// if not all updates are bound but there's nothing else to crawl
// it means that there is something wrong with the template.
if (!node)
throw `bad template: ${text}`;
// if the current node is a comment, and it contains isµX
// it means the update should take care of any content
if (node.nodeType === 8) {
// The only comments to be considered are those
// which content is exactly the same as the searched one.
if (node.data === search) {
nodes.push({type: 'node', path: createPath(node)});
search = `${prefix}${++i}`;
}
}
else {
// if the node is not a comment, loop through all its attributes
// named isµX and relate attribute updates to this node and the
// attribute name, retrieved through node.getAttribute("isµX")
// the isµX attribute will be removed as irrelevant for the layout
// let svg = -1;
while (node.hasAttribute(search)) {
nodes.push({
type: 'attr',
path: createPath(node),
name: node.getAttribute(search)
});
node.removeAttribute(search);
search = `${prefix}${++i}`;
}
// if the node was a style, textarea, or others, check its content
// and if it is <!--isµX--> then update tex-only this node
if (
textOnly.test(node.localName) &&
node.textContent.trim() === `<!--${search}-->`
){
node.textContent = '';
nodes.push({type: 'text', path: createPath(node)});
search = `${prefix}${++i}`;
}
}
}
// once all nodes to update, or their attributes, are known, the content
// will be cloned in the future to represent the template, and all updates