-
Notifications
You must be signed in to change notification settings - Fork 20
/
twinspark.js
2118 lines (1796 loc) · 60.1 KB
/
twinspark.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
// jshint -W030, -W084, esversion: 6
(function(window, document, tsname) {
var location = window.location;
var script = document.currentScript;
/// Config
function cget(name, def) { return script && script.dataset[name] || def; }
function iget(name, def) { return parseInt(cget(name, def), 10); }
var xhrTimeout = iget('timeout', '3000');
var historyLimit = iget('history', '20');
var attrsToSettle = cget('settle', 'class,style,width,height').split(',');
var insertClass = cget('insert-class', 'ts-insert');
var removeClass = cget('remove-class', 'ts-remove');
var activeClass = cget('active-class', 'ts-active');
/// Internal variables
// Indicates if `init` has happened
var READY = false;
/** @typedef {{selector: string, handler: (function(!Element): void)}} */
var Directive;
/** @type {Array<Directive>} */
var DIRECTIVES = [];
/** @const {!Object<string, Function>} */
var FUNCS = {
stop: function(o) { if (o.event) o.event.stopPropagation(); },
prevent: function(o) { if (o.event) o.event.preventDefault(); },
delay: delay,
not: function(funcname) {
var args = [].slice.call(arguments, 1, arguments.length - 1);
var o = merge({}, arguments[arguments.length - 1]);
o.src = o.src.slice(o.command.length + 1);
o = /** @type {!CommandPayload}*/ (o);
var rv = executeCommand(funcname, args, o);
// this means previous command does not return truthy/falsy value, we
// ignore that
if (rv === null || rv === undefined) {
return rv;
}
return !rv;
},
target: function(sel, o) {
try {
let el = findTarget(o.el, sel);
if (!el)
return false;
o.el = el;
return undefined; // do not affect o.input
} catch(e) {
return false; // stop executing actions pipeline
}
},
remove: arity(
(o) => { o.el.remove(); },
(sel, o) => { findTarget(o.el, sel).remove(); }
),
wait: function(eventname, o) {
return new Promise(function(resolve) {
listen(o.el, eventname, resolve, {once: true});
});
},
on: function(eventname, o) {
var rest = o.line.split(o.src)[1].replace(/^[\s,]+/, '');
var action = parseActionSpec(rest)[0];
addListener(o.el, eventname, (_el, e) => {
_doAction(action, {el: o.el, event: e});
});
return false; // stop executing actions pipeline
},
req: arity(
(url, o) => { this.dispatcher(null, url, o); },
(method, url, o) => {
doReqBatch(makeReq(o.el, o.event, false,
{method: method,
url: url,
data: o.input ? [['input', o.input]] : null}));
}
),
class: function(cls, o) { o.el.classList.add(cls); },
"class+": function(cls, o) { o.el.classList.add(cls); },
"class-": function(cls, o) { o.el.classList.remove(cls); },
"class^": function(cls, o) { o.el.classList.toggle(cls); },
classtoggle: function(cls, o) { o.el.classList.toggle(cls); },
text: arity(
(o) => {
if (!(o.input === null || o.input === undefined)) {
o.el.textContent = o.input;
}
return o.input;
},
(value, o) => {
o.el.textContent = value;
return value;
}
),
html: arity(
(o) => {
if (!(o.input === null || o.input === undefined)) {
o.el.innerHTML = o.input;
}
return o.el.innerHTML;
},
(value, o) => {
o.el.innerHTML = value;
return value;
}
),
attr: arity(
(name, o) => {
let val = o.el[name];
return typeof val != 'undefined' ? val : getattr(o.el, name);
},
(name, value, o) => {
o.el[name] = value;
setattr(o.el, name, value);
return value;
}
),
log: function(...args) {
let o = args[args.length-1];
let rest = args.slice(args.length - 1);
if (o.input) {
rest.push(o.input);
}
console.log(...rest);
}
};
/// Utils
var ERR = console.error ?
console.error.bind(console, 'TwinSpark error:') :
console.log.bind(console, 'TwinSpark error:');
/** @type{function(...Function): Function} */
function arity(...funcs) {
let funcmap = funcs.reduce((acc, func) => {
if (acc[func.length]) {
throw extraerr('Arity dispatch: duplicate function with the same number of arguments', {
length: func.length,
func: func,
duplicate: acc[func.length],
});
}
acc[func.length] = func;
return acc;
}, {});
return function dispatcher() {
var len = arguments.length;
var func = funcmap[len];
if (!func) {
throw extraerr("No function supplied accepting " + len + " arguments", {
"functions": funcmap,
"arguments": Array.from(arguments)
});
}
return func.apply({dispatcher}, arguments);
}
}
/** @type{function(!Object, (Object|null|undefined)): !Object} */
var merge = Object.assign || function(tgt, src) {
if (!src) {
return tgt;
}
for (var k in src) {
if (Object.hasOwn(src, k)) {
tgt[k] = src[k];
}
}
return tgt;
};
function groupBy(arr, keyfn) {
return arr.reduce(function (acc, v) {
var key = keyfn(v);
(acc[key] || (acc[key] = [])).push(v);
return acc;
}, {});
}
function zip(arr1, arr2) {
return arr1.map((val, i) => [val, arr2[i]]);
}
/** @type {function(Array): Array} */
function distinct(arr) {
var seen = new Set(),
res = [],
val;
for (var i = 0; i < arr.length; i++) {
val = arr[i];
if (!seen.has(val)) {
seen.add(val);
res.push(val);
}
}
return res;
}
function el2str(el) {
return el.outerHTML.match(/<.+?>/)[0];
}
function extraerr(msg, data) {
var err = Error(msg);
err.extra = data;
return err;
}
function memoize(orig) {
var cache = null;
return function() {
return cache || (cache = orig());
};
}
/** @type {function(string): (number|undefined)} */
function parseTime(s) {
s = s && s.trim();
if (!s)
return;
if (s.match(/\d+s/))
return parseFloat(s) * 1000;
return parseFloat(s);
}
function delay(s) {
return new Promise(function(resolve) {
setTimeout(resolve, parseTime(s), true);
});
}
/// Events
/** @type {function(Function): void} */
function onload(fn) {
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', fn);
} else {
fn();
}
}
var onidle = window.requestIdleCallback || function(x) { setTimeout(x, 100); };
/** @type {function((Element|Node|Window), string, Object=, Object=): !Event} */
function sendEvent(el, type, detail, opts) {
// true if not supplied
var bubbles = (opts && 'bubbles' in opts) ? opts.bubbles : true;
var event = new CustomEvent(type, {bubbles: bubbles,
cancelable: true,
detail: detail});
console.debug('🛎️ EVENT', type, {el: el, detail: detail});
el.dispatchEvent(event);
return event;
}
function sendError(el, type, detail) {
sendEvent(el, type, merge({error: type}, detail));
}
/// Attribute handling
/** @type {function(!Element, !string): boolean} */
function hasattr(el, attr) {
return el.hasAttribute(attr);
}
/** @type {function(!Element, !string): string} */
function getattr(el, attr) {
return el.getAttribute(attr);
}
/** @type {function(!Element, !string, string): void} */
function setattr(el, attr, value) {
return el.setAttribute(attr, value);
}
/** @type {function(!Element, !string): void} */
function delattr(el, attr) {
return el.removeAttribute(attr);
}
/// DOM querying
/** @type {function(!Node, !string): Element} */
function qsf(el, selector) { // querySelectorFirst
if (el.nodeType == 1 && el.matches(selector))
return /** @type {!Element} */ (el);
return el.querySelector ? el.querySelector(selector) : null;
}
/** @type {function(!Node, !string): !Array<!Element>} */
function qse(el, selector) { // querySelectorEvery
if (!el.querySelectorAll)
return [];
var els = Array.from(el.querySelectorAll(selector));
if (el.nodeType == 1 && el.matches(selector))
els.unshift(el);
return els;
}
function elid(el) {
if (el.id)
return el.id;
var tag = el.tagName.toLowerCase();
if (el.className)
return tag + '.' + el.className.replace(' ', '.');
return tag;
}
/**
* Collects all non-empty attribute values from element and its parents.
* @type {function(!Element, string): Array<string>} */
function elcrumbs(el, attr) {
var result = [];
var value;
var _el = el; // this is to make Closure Compiler type checker happy :(
do {
value = getattr(_el, attr);
if (value) {
result.push(value);
}
} while (_el = _el.parentElement);
return result;
}
/** @type {function(!(Node|Window), string=, ?=): ?} */
function internalData(el, attr, def) {
var k = 'twinspark-internal';
var data = el[k] || (el[k] = {});
if (!attr)
return data;
if (!(attr in data) && typeof def != 'undefined')
data[attr] = def;
return data[attr];
}
/// Core
/**
* Registers new directive.
* @param {string} selector Directive selector.
* @param {function(!Element): void} handler Directive callback.
* @return void
*/
function register(selector, handler) {
var directive = {selector: selector, handler: handler};
DIRECTIVES.push(directive);
if (READY) {
qse(document.body, directive.selector).forEach(directive.handler);
}
}
/** @type {function(!(Node|Window), !string, !Function, !AddEventListenerOptions=): !(Node|Window)} */
function listen(el, type, func, opts) {
el.addEventListener(type, func, opts);
internalData(el, 'event-handlers', []).push({
type: type,
func: func,
opts: opts,
});
return el;
}
/** @type {function(!(Element|HTMLDocument)): void} */
function deactivateEl(el) {
internalData(el, 'event-handlers', [])
.forEach(h => el.removeEventListener(h.type, h.func, h.opts));
}
/** @type {function(!Element): void} */
function activateEl(el) {
deactivateEl(el);
DIRECTIVES.forEach(d => el.matches(d.selector) && d.handler(el));
}
/** @type {function(!Element): void} */
function activate(el) {
var selector = DIRECTIVES.map(d => d.selector).join(',');
qse(el, selector).forEach(activateEl);
sendEvent(el, 'ts-ready');
}
/** @type {function(!Element): void} */
function autofocus(el) {
var toFocus = qsf(el, '[autofocus]');
if (toFocus) {
toFocus.focus();
}
}
/// Ajax
/** @typedef {{
* ok: boolean,
* status: number,
* url: string,
* error: string
* }}
*/
var ResponseTimeout;
/** @typedef {{
* ok: boolean,
* status: number,
* url: string,
* reqUrl: string,
* xhr: XMLHttpRequest,
* opts: RequestInit,
* headers: Object,
* content: string,
* }}
*/
var Response;
/** @typedef {{response: Response, tasks: Array<Function>}} */
var SwapData;
/** @type {function(string, RequestInit): {promise: Promise<Response|ResponseTimeout>, xhr: XMLHttpRequest} } */
function xhr(url, opts) {
var xhr = new XMLHttpRequest();
return {
promise: new Promise(function(resolve, reject) {
opts || (opts = {});
xhr.open(opts.method || 'GET', url, true);
for (var k in opts.headers) {
xhr.setRequestHeader(k, opts.headers[k]);
}
for (var k in opts.xhr) {
xhr[k] = opts.xhr[k];
}
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status == 0) return; // timeout
var headers = {'ts-title': xhr.getResponseHeader('ts-title'),
'ts-history': xhr.getResponseHeader('ts-history'),
'ts-swap': xhr.getResponseHeader('ts-swap'),
'ts-swap-push': xhr.getResponseHeader('ts-swap-push'),
'ts-location': xhr.getResponseHeader('ts-location')};
return resolve({ok: xhr.status >= 200 && xhr.status <= 299,
status: xhr.status,
url: xhr.responseURL,
reqUrl: url,
xhr: xhr,
opts: opts,
headers: headers,
content: xhr.responseText});
};
xhr.timeout = xhrTimeout;
xhr.ontimeout = function() {
return reject({ok: false,
status: 0,
url: url,
content: "timeout"});
};
xhr.send(
/** @type {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string|undefined)} */
(opts.body));
}),
xhr: xhr
};
}
/// Data collection
/**
* Merge two sets of parameters into one
* @param {FormData} p1 Collection of parameters to be updated.
* @param {FormData|URLSearchParams|Iterable} p2 Collection of parameters to be merged in.
* @param {boolean=} removeEmpty Indicate if empty ('' or null) parameters from p2 should be removed.
* @return FormData|URLSearchParams
*/
function mergeParams(p1, p2, removeEmpty) {
if (!p2) return p1;
// iterator loop here since p2 could be either an array or an
// FormData instance
for (var [k, v] of p2) {
if (!k) continue;
if (removeEmpty && ((v === null) || (v === ''))) {
p1.delete(k);
} else {
p1.append(k, v);
}
}
return p1;
}
/**
* Parse either query string or JSON object.
* @param {string} v String to be parsed.
* @return FormData|Array<Array<string,*>>|null
*/
function parseData(v) {
if (v == "") return null;
if (v[0] == '{') {
var data = JSON.parse(v);
if (typeof data === 'object' && data !== null) {
var arr = [];
for (var k in data) {
arr.push([k, data[k]]);
}
return arr;
}
} else {
return mergeParams(new FormData(), new URLSearchParams(v));
}
}
/**
* @type {function(!Element, string): FormData}
*/
function eldata(el, attr) {
// reduceRight because deepest element is the first one
return elcrumbs(el, attr).reduceRight(
(acc, v) => mergeParams(acc, parseData(v), true),
new FormData());
}
/** @type {function(Element): string?} */
function formElementValue(el) {
if (!el.name)
return null;
// we will look at e.submitter separately
if (el.type == 'submit')
return null;
if (((el.type == 'radio') || (el.type == 'checkbox')) &&
!el.checked) {
return null;
}
return el.value;
}
/** @type {function(!Element, Event): !FormData} */
function collectData(el, e) {
var data = eldata(el, 'ts-data');
var tag = el.tagName;
var res;
if (tag == 'FORM') {
let currentElData = new FormData(el);
if (e && e.submitter && e.submitter.name && e.submitter.value
// old IOS Safari may add button's value to form data
&& !currentElData.has(e.submitter.name)) {
data.append(e.submitter.name, e.submitter.value);
}
data = mergeParams(data, currentElData);
} else if ((tag == 'INPUT') || (tag == 'SELECT') || (tag == 'TEXTAREA')) {
if (res = formElementValue(el))
data.append(el.name, /** @type {string} */ (res));
}
return data;
}
/// IndexedDB
var IDB = window.indexedDB;
function reqpromise(req) {
return new Promise(function(resolve, reject) {
req.onsuccess = function() { resolve(req.result); };
req.onerror = function() { reject(req.error); };
});
}
var _idb;
function idb() {
if (_idb)
return _idb;
var dbname = 'twinspark';
var req = IDB.open(dbname, 1);
req.onupgradeneeded = function() {
var db = req.result;
var store = db.createObjectStore(dbname, {keyPath: 'url'});
store.createIndex('time', 'time');
};
return _idb = reqpromise(req);
}
/** @type {function(Object, Object=): Object} */
function idbStore(db, opts) {
var rw = opts && opts.write;
return db.transaction(db.name, rw && 'readwrite' || 'readonly')
.objectStore(db.name);
}
/// History
async function deleteOverLimit(db) {
let store = idbStore(db);
let count = await reqpromise(store.count());
console.debug('PAGES IN STORAGE', count);
var toremove = count - historyLimit;
if (toremove <= 0)
return;
store = idbStore(db, {write: true});
let req = store.index('time').openCursor();
// This API is like an abyss looking at me. `onsuccess` will be called
// every time you call `cursor.continue()`.
req.onsuccess = function(_) {
var cursor = req.result;
if (cursor) {
cursor.delete();
if (--toremove > 0) {
cursor.continue();
}
}
}
}
async function storeCurrentState() {
if (historyLimit == 0) // disable history management
return;
var data = {url: location.pathname + location.search,
html: document.body.innerHTML,
time: +new Date()};
var db = await idb();
var store = idbStore(db, {write: true});
await reqpromise(store.put(data));
await deleteOverLimit(db);
}
function pushState(url, title) {
// Store HTML before "changing page", `swap` is going to change HTML after
// that
storeCurrentState();
// we need to put some state in our *current* history item, so that
// `onpopstate` knows it wasn't called because of `hashchange`
history.replaceState('history', '', '');
history.pushState(null, title, url);
sendEvent(window, 'ts-pushstate', {url: url});
}
function replaceState(url) {
history.replaceState('history', '', url);
sendEvent(window, 'ts-replacestate', {url: url});
}
async function onpopstate(e) {
if (historyLimit == 0) // disable history management
return;
// hashchange triggers onpopstate and there is nothing we can do about it
// https://stackoverflow.com/questions/25634422/stop-firing-popstate-on-hashchange
//
// the worst news here is that `popstate` is fired *before* `hashchange`, so
// we store some state in previous item in `pushState` function
if (!e.state)
return;
let url = location.pathname + location.search;
let db = await idb();
let store = idbStore(db);
let data = await reqpromise(store.get(url));
if (data && data.html) {
console.debug('onpopstate restore', data.url, data.html.length, data.time);
deactivateEl(document);
document.body.innerHTML = data.html;
// If user came back from a real page change, we indicate this with an
// `initial` property. There is a race between IndexedDB loading HTML
// and DOMContentLoaded, so in case when first happened and second did
// not, `READY` is false and thus `activate` will be run later on inside
// `init`. Skip this not to activate everything twice.
if (e.state == "INITIAL" && !READY) {
return;
}
activate(document.body);
}
}
/// Fragments
/** @type {function(Element, string, boolean): (Element|undefined)} */
function _findSingleTarget(el, sel, childrenOnly) {
if (!sel || !el) {
return el;
}
if (sel == 'target') {
return el;
}
if (sel == 'inherit') {
var parent = el.parentElement.closest('[ts-target]');
return findTarget(parent);
}
if (sel.slice(0, 7) == 'parent ') {
return el.closest(sel.slice(7));
}
if (sel.slice(0, 6) == 'child ') {
return el.querySelector(sel.slice(6));
}
if (sel.slice(0, 8) == 'sibling ') {
return el.parentElement.querySelector(sel.slice(8));
}
if (childrenOnly) {
return el.querySelector(sel);
}
return document.querySelector(sel);
}
/** @type {function(!Element, !string, !boolean): !Element} */
function findSingleTarget(el, sel, childrenOnly) {
var res = _findSingleTarget(el, sel, childrenOnly);
if (res)
return res;
var elstr = el2str(el);
throw extraerr(`Could not find element with selector ${sel} for element ${elstr}` +
(childrenOnly ? ' among children' : ''), {
element: elstr,
selector: sel
});
}
/** @type {function(Element, string=): Element} */
function findTarget(el, sel) {
if (!el) return el;
if (sel == null) {
sel = getattr(el, 'ts-target');
}
if (!sel) { // undefined, ""
return el;
}
var bits = sel.split('|').map(s => s.trim());
// when selector is not the first we are not going to escape to global
// search from document root, it's always one of modifiers (see
// `_findSingleTarget`), in the least it will look for a child
return bits.reduce((el, sel, idx) => findSingleTarget(el, sel, idx > 0), el);
}
/** @type {function(!Element, !Element, !Element): (Element|DocumentFragment)} */
function findReply(target, origin, reply) {
var sel = getattr(origin, 'ts-req-selector');
if (!sel) {
if ((reply.tagName == 'BODY') && (target.tagName != 'BODY')) {
return reply.children[0];
}
return reply;
}
if (sel.slice(0, 9) == 'children ') {
var el = qsf(reply, sel.slice(9));
var frag = new DocumentFragment();
if (el && el.children) {
frag.append.apply(frag, el.children);
}
return frag;
}
return qsf(reply, sel);
}
/** @type {function(!Element, !Element, !string, !boolean=): void} */
function syncattr(target, source, attr, withProp) {
if (withProp) {
let value = source[attr];
if (value != target[attr]) {
target[attr] = value;
value ? setattr(target, attr, value) : delattr(target, attr);
}
} else {
let value = getattr(source, attr);
if (value != getattr(target, attr)) {
value ? setattr(target, attr, value) : delattr(target, attr);
}
}
}
/** @type {function(!Element, !Element): void} */
function syncSettleAttrs(target, source) {
for (var attr of attrsToSettle) {
syncattr(target, source, attr);
}
}
/** @type {function(!Element): void} */
function elementInserted(el) {
el.classList.add(insertClass);
setTimeout(() => el.classList.remove(insertClass));
}
// if there is a node with same id in an old code and in a new code,
// temporarily set it attrs to what old code had (and then restore to new
// values)
function transitionAttrs(el, origin, ctx) {
if (!el.id) return;
var oldEl = origin.querySelector(el.tagName + "[id='" + el.id + "']");
if (!oldEl) {
return elementInserted(el);
}
var newAttrs = el.cloneNode();
syncSettleAttrs(el, oldEl);
ctx.tasks.push(function() {
syncSettleAttrs(el, newAttrs);
});
return ctx;
}
/// Morph, thanks to idiomorph and nanomorph
// Core algorithm from https://github.com/bigskysoftware/idiomorph
var morph = (function() {
/** @type {function(!Node, !Object): void} */
function cleanRemove(el, ctx) {
// callback before anything else to have a chance to do something
ctx.cb('node-remove', el);
if (el.nodeType != 1) {
el.remove();
return;
}
el.classList.add(removeClass);
// another approach would be to use `transitionrun`/`transitionend`
// events, but basic performance testing did not show a noticeable
// difference
var animations = el.getAnimations()
.filter(a => a instanceof window.CSSTransition);
if (!animations.length) {
return el.remove();
}
Promise.all(animations.map(a => a.finished))
.then(() => {
el.remove();
});
}
/** @type {function(!Node, !Object): void} */
function cleanInsert(el, ctx) {
// callback before anything so that there is a hook to change something
ctx.cb('node-insert', el);
if (el instanceof HTMLElement) {
activate(el);
elementInserted(el);
}
}
/**
* Makes one element look like the other
* @param {!Node} target In-DOM element which needs to be updated
* @param {!Node} reply Incoming element of necessary shape
* @return void
*/
function syncAttrs(target, reply) {
if (target.nodeType != 1) {
// text, comments
target.nodeValue = reply.nodeValue;
return;
}
target = /** @type !Element */ (target);
reply = /** @type !Element */ (reply);
for (var attr of reply.attributes) {
syncattr(target, reply, attr.name);
}
// iterate backwards to avoid skipping over items when a delete occurs
for (let i = target.attributes.length - 1; i >= 0; i--) {
syncattr(target, reply, target.attributes[i].name);
}
// sync inputs
if (target.tagName == 'INPUT' && target.type != 'file') {
// https://github.com/choojs/nanomorph/blob/master/lib/morph.js#L113
// Changing the "value" attribute without changing the "value" property
// will have no effect since attribute is only used to set the initial
// value. Similar for the "checked" attribute, and "disabled".
syncattr(target, reply, 'value', true);
syncattr(target, reply, 'checked', true);
syncattr(target, reply, 'disabled', true);
} else if (target.tagName == 'OPTION') {
syncattr(target, reply, 'selected', true);
} else if (target.tagName == 'TEXTAREA') {
syncattr(target, reply, 'value');
// NOTE what is this stuff, is it necessary? Can't find a test case, but
// nanomorph is doing that.
if (target.firstChild && target.firstChild.nodeValue != reply.value) {
target.firstChild.nodeValue = reply.value;
}
}
}
function intersection(setA, setB) {
const _intersection = new Set();
for (const elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem);
}
}
return _intersection;
}
function isSimilar(node1, node2) {
return (node1 &&
node2 &&
node1.nodeType == node2.nodeType &&
node1.tagName == node2.tagName);
}
/** @type {function(!Node, !Node): Element} */
function findIdsMatch(target, reply) {
if (reply.nodeType != 1)
return null;
var el = /** @type {!Element} */ (reply);
var replyIds = qse(el, '[id]').map(el => '#' + CSS.escape(el.id)).join(',');
if (!replyIds)
return null;
el = /** @type {!Element} */ (target);
do {
// check if any element having id like those coming in `reply`
if (qsf(el, replyIds)) {
return el;
}
} while (el = el.nextElementSibling);
return null;
}
/** @type {function(!Node, !Node, Set<string>): Node} */
function findSoftMatch(target, reply, incomingIds) {
var el = target;
var nextReply = reply.nextSibling;
var potentialMatches = 0;
do {
var ids = qse(el, '[id]').map(el => el.id);
// there are potential id matches, bail out of soft matching
if (ids.length && intersection(incomingIds, ids).size) {
return null;
}
// check similarities only if there is no ids inside of compared
// elements, in other case we want a clean removal to start animations
if (!ids.length && !qse(reply, '[id]').length && isSimilar(el, reply)) {
return el;