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
1685 lines (1543 loc) · 57.7 KB
/
Copy pathindex.js
File metadata and controls
1685 lines (1543 loc) · 57.7 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$1 = 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$1();
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);
};
// https://codepen.io/WebReflection/pen/dqZrpV?editors=0010
// 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') || !Object.isFrozen(t.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$1();
}
};
// 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];
this._ = null;
}
// when a wire is inserted, all its nodes will follow
Wire.prototype.valueOf = function valueOf(different) {
var noFragment = this._ == null;
if (noFragment) this._ = fragment(this.first);
if (noFragment || different) append(this._, this.childNodes);
return this._;
};
// when a wire is removed, all its nodes must be removed as well
Wire.prototype.remove = function remove() {
this._ = null;
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];
var styleValue = typeof value === 'number' && !IS_NON_DIMENSIONAL.test(_key) ? value + 'px' : value;
if (/^--/.test(_key)) info.setProperty(_key, styleValue);else info[_key] = styleValue;
}
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 */
var append$1 = function append(get, parent, children, start, end, before) {
if (end - start < 2) parent.insertBefore(get(children[start], 1), before);else {
var fragment = parent.ownerDocument.createDocumentFragment();
while (start < end) {
fragment.appendChild(get(children[start++], 1));
}parent.insertBefore(fragment, before);
}
};
var eqeq = function eqeq(a, b) {
return a == b;
};
var identity = function identity(O) {
return O;
};
var indexOf = function indexOf(moreNodes, moreStart, moreEnd, lessNodes, lessStart, lessEnd, compare) {
var length = lessEnd - lessStart;
/* istanbul ignore if */
if (length < 1) return -1;
while (moreEnd - moreStart >= length) {
var m = moreStart;
var l = lessStart;
while (m < moreEnd && l < lessEnd && compare(moreNodes[m], lessNodes[l])) {
m++;
l++;
}
if (l === lessEnd) return moreStart;
moreStart = m + 1;
}
return -1;
};
var isReversed = function isReversed(futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare) {
while (currentStart < currentEnd && compare(currentNodes[currentStart], futureNodes[futureEnd - 1])) {
currentStart++;
futureEnd--;
} return futureEnd === 0;
};
var next = function next(get, list, i, length, before) {
return i < length ? get(list[i], 0) : 0 < i ? get(list[i - 1], -0).nextSibling : before;
};
var remove = function remove(get, parent, children, start, end) {
if (end - start < 2) parent.removeChild(get(children[start], -1));else {
var range = parent.ownerDocument.createRange();
range.setStartBefore(get(children[start], -1));
range.setEndAfter(get(children[end - 1], -1));
range.deleteContents();
}
};
// - - - - - - - - - - - - - - - - - - -
// diff related constants and utilities
// - - - - - - - - - - - - - - - - - - -
var DELETION = -1;
var INSERTION = 1;
var SKIP = 0;
var SKIP_OND = 50;
/* istanbul ignore next */
var Rel = typeof Map === 'undefined' ? function () {
var k = [],
v = [];
return {
has: function has(value) {
return -1 < k.indexOf(value);
},
get: function get(value) {
return v[k.indexOf(value)];
},
set: function set(value) {
var i = k.indexOf(value);
v[i < 0 ? k.push(value) - 1 : i] = value;
}
};
} : Map;
var HS = function HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges) {
var k = 0;
/* istanbul ignore next */
var minLen = futureChanges < currentChanges ? futureChanges : currentChanges;
var link = Array(minLen++);
var tresh = Array(minLen);
tresh[0] = -1;
for (var i = 1; i < minLen; i++) {
tresh[i] = currentEnd;
}var keymap = new Rel();
for (var _i = currentStart; _i < currentEnd; _i++) {
keymap.set(currentNodes[_i], _i);
}for (var _i2 = futureStart; _i2 < futureEnd; _i2++) {
var idxInOld = keymap.get(futureNodes[_i2]);
if (idxInOld != null) {
k = findK(tresh, minLen, idxInOld);
/* istanbul ignore else */
if (-1 < k) {
tresh[k] = idxInOld;
link[k] = {
newi: _i2,
oldi: idxInOld,
prev: link[k - 1]
};
}
}
}
k = --minLen;
--currentEnd;
while (tresh[k] > currentEnd) {
--k;
}minLen = currentChanges + futureChanges - k;
var diff = Array(minLen);
var ptr = link[k];
--futureEnd;
while (ptr) {
var _ptr = ptr,
newi = _ptr.newi,
oldi = _ptr.oldi;
while (futureEnd > newi) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd > oldi) {
diff[--minLen] = DELETION;
--currentEnd;
}
diff[--minLen] = SKIP;
--futureEnd;
--currentEnd;
ptr = ptr.prev;
}
while (futureEnd >= futureStart) {
diff[--minLen] = INSERTION;
--futureEnd;
}
while (currentEnd >= currentStart) {
diff[--minLen] = DELETION;
--currentEnd;
}
return diff;
};
// this is pretty much the same petit-dom code without the delete map part
// https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L556-L561
var OND = function OND(futureNodes, futureStart, rows, currentNodes, currentStart, cols, compare) {
var length = rows + cols;
var v = [];
var d = void 0,
k = void 0,
r = void 0,
c = void 0,
pv = void 0,
cv = void 0,
pd = void 0;
outer: for (d = 0; d <= length; d++) {
/* istanbul ignore if */
if (d > SKIP_OND) return null;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
cv = v[d] = [];
for (k = -d; k <= d; k += 2) {
if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
c = pv[pd + k + 1];
} else {
c = pv[pd + k - 1] + 1;
}
r = c - k;
while (c < cols && r < rows && compare(currentNodes[currentStart + c], futureNodes[futureStart + r])) {
c++;
r++;
}
if (c === cols && r === rows) {
break outer;
}
cv[d + k] = c;
}
}
var diff = Array(d / 2 + length / 2);
var diffIdx = diff.length - 1;
for (d = v.length - 1; d >= 0; d--) {
while (c > 0 && r > 0 && compare(currentNodes[currentStart + c - 1], futureNodes[futureStart + r - 1])) {
// diagonal edge = equality
diff[diffIdx--] = SKIP;
c--;
r--;
}
if (!d) break;
pd = d - 1;
/* istanbul ignore next */
pv = d ? v[d - 1] : [0, 0];
k = c - r;
if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) {
// vertical edge = insertion
r--;
diff[diffIdx--] = INSERTION;
} else {
// horizontal edge = deletion
c--;
diff[diffIdx--] = DELETION;
}
}
return diff;
};
var applyDiff = function applyDiff(diff, get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before) {
var live = new Rel();
var length = diff.length;
var currentIndex = currentStart;
var i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
futureStart++;
currentIndex++;
break;
case INSERTION:
// TODO: bulk appends for sequential nodes
live.set(futureNodes[futureStart], 1);
append$1(get, parentNode, futureNodes, futureStart++, futureStart, currentIndex < currentLength ? get(currentNodes[currentIndex], 1) : before);
break;
case DELETION:
currentIndex++;
break;
}
}
i = 0;
while (i < length) {
switch (diff[i++]) {
case SKIP:
currentStart++;
break;
case DELETION:
// TODO: bulk removes for sequential nodes
if (live.has(currentNodes[currentStart])) currentStart++;else remove(get, parentNode, currentNodes, currentStart++, currentStart);
break;
}
}
};
var findK = function findK(ktr, length, j) {
var lo = 1;
var hi = length;
while (lo < hi) {
var mid = (lo + hi) / 2 >>> 0;
if (j < ktr[mid]) hi = mid;else lo = mid + 1;
}
return lo;
};
var smartDiff = function smartDiff(get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before) {
applyDiff(OND(futureNodes, futureStart, futureChanges, currentNodes, currentStart, currentChanges, compare) || HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges), get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before);
};
/* AUTOMATICALLY IMPORTED, DO NOT MODIFY */
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 currentLength = currentNodes.length;
var currentEnd = currentLength;
var currentStart = 0;
var futureEnd = futureNodes.length;
var futureStart = 0;
// common prefix
while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentStart], futureNodes[futureStart])) {
currentStart++;
futureStart++;
}
// common suffix
while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentEnd - 1], futureNodes[futureEnd - 1])) {
currentEnd--;
futureEnd--;
}
var currentSame = currentStart === currentEnd;
var futureSame = futureStart === futureEnd;
// same list
if (currentSame && futureSame) return futureNodes;
// only stuff to add
if (currentSame && futureStart < futureEnd) {
append$1(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentStart, currentLength, before));
return futureNodes;
}
// only stuff to remove
if (futureSame && currentStart < currentEnd) {
remove(get, parentNode, currentNodes, currentStart, currentEnd);
return futureNodes;
}
var currentChanges = currentEnd - currentStart;
var futureChanges = futureEnd - futureStart;
var i = -1;
// 2 simple indels: the shortest sequence is a subsequence of the longest
if (currentChanges < futureChanges) {
i = indexOf(futureNodes, futureStart, futureEnd, currentNodes, currentStart, currentEnd, compare);
// inner diff
if (-1 < i) {
append$1(get, parentNode, futureNodes, futureStart, i, get(currentNodes[currentStart], 0));
append$1(get, parentNode, futureNodes, i + currentChanges, futureEnd, next(get, currentNodes, currentEnd, currentLength, before));
return futureNodes;
}
}
/* istanbul ignore else */
else if (futureChanges < currentChanges) {
i = indexOf(currentNodes, currentStart, currentEnd, futureNodes, futureStart, futureEnd, compare);
// outer diff
if (-1 < i) {
remove(get, parentNode, currentNodes, currentStart, i);
remove(get, parentNode, currentNodes, i + futureChanges, currentEnd);
return futureNodes;
}
}
// common case with one replacement for many nodes