@hyperspan/framework 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,854 @@
1
+ //
2
+ // Idiomorph - DOM tree manipulation
3
+ // @see https://github.com/bigskysoftware/idiomorph/
4
+ //
5
+ var Idiomorph = (function () {
6
+ 'use strict';
7
+
8
+ //=============================================================================
9
+ // AND NOW IT BEGINS...
10
+ //=============================================================================
11
+ let EMPTY_SET = new Set();
12
+
13
+ // default configuration values, updatable by users now
14
+ let defaults = {
15
+ morphStyle: 'outerHTML',
16
+ callbacks: {
17
+ beforeNodeAdded: noOp,
18
+ afterNodeAdded: noOp,
19
+ beforeNodeMorphed: noOp,
20
+ afterNodeMorphed: noOp,
21
+ beforeNodeRemoved: noOp,
22
+ afterNodeRemoved: noOp,
23
+ beforeAttributeUpdated: noOp,
24
+ },
25
+ head: {
26
+ style: 'merge',
27
+ shouldPreserve: function (elt) {
28
+ return elt.getAttribute('im-preserve') === 'true';
29
+ },
30
+ shouldReAppend: function (elt) {
31
+ return elt.getAttribute('im-re-append') === 'true';
32
+ },
33
+ shouldRemove: noOp,
34
+ afterHeadMorphed: noOp,
35
+ },
36
+ };
37
+
38
+ //=============================================================================
39
+ // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren
40
+ //=============================================================================
41
+ function morph(oldNode, newContent, config = {}) {
42
+ if (oldNode instanceof Document) {
43
+ oldNode = oldNode.documentElement;
44
+ }
45
+
46
+ if (typeof newContent === 'string') {
47
+ newContent = parseContent(newContent);
48
+ }
49
+
50
+ let normalizedContent = normalizeContent(newContent);
51
+
52
+ let ctx = createMorphContext(oldNode, normalizedContent, config);
53
+
54
+ return morphNormalizedContent(oldNode, normalizedContent, ctx);
55
+ }
56
+
57
+ function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {
58
+ if (ctx.head.block) {
59
+ let oldHead = oldNode.querySelector('head');
60
+ let newHead = normalizedNewContent.querySelector('head');
61
+ if (oldHead && newHead) {
62
+ let promises = handleHeadElement(newHead, oldHead, ctx);
63
+ // when head promises resolve, call morph again, ignoring the head tag
64
+ Promise.all(promises).then(function () {
65
+ morphNormalizedContent(
66
+ oldNode,
67
+ normalizedNewContent,
68
+ Object.assign(ctx, {
69
+ head: {
70
+ block: false,
71
+ ignore: true,
72
+ },
73
+ })
74
+ );
75
+ });
76
+ return;
77
+ }
78
+ }
79
+
80
+ if (ctx.morphStyle === 'innerHTML') {
81
+ // innerHTML, so we are only updating the children
82
+ morphChildren(normalizedNewContent, oldNode, ctx);
83
+ return oldNode.children;
84
+ } else if (ctx.morphStyle === 'outerHTML' || ctx.morphStyle == null) {
85
+ // otherwise find the best element match in the new content, morph that, and merge its siblings
86
+ // into either side of the best match
87
+ let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);
88
+
89
+ // stash the siblings that will need to be inserted on either side of the best match
90
+ let previousSibling = bestMatch?.previousSibling;
91
+ let nextSibling = bestMatch?.nextSibling;
92
+
93
+ // morph it
94
+ let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);
95
+
96
+ if (bestMatch) {
97
+ // if there was a best match, merge the siblings in too and return the
98
+ // whole bunch
99
+ return insertSiblings(previousSibling, morphedNode, nextSibling);
100
+ } else {
101
+ // otherwise nothing was added to the DOM
102
+ return [];
103
+ }
104
+ } else {
105
+ throw 'Do not understand how to morph style ' + ctx.morphStyle;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * @param possibleActiveElement
111
+ * @param ctx
112
+ * @returns {boolean}
113
+ */
114
+ function ignoreValueOfActiveElement(possibleActiveElement, ctx) {
115
+ return (
116
+ ctx.ignoreActiveValue &&
117
+ possibleActiveElement === document.activeElement &&
118
+ possibleActiveElement !== document.body
119
+ );
120
+ }
121
+
122
+ /**
123
+ * @param oldNode root node to merge content into
124
+ * @param newContent new content to merge
125
+ * @param ctx the merge context
126
+ * @returns {Element} the element that ended up in the DOM
127
+ */
128
+ function morphOldNodeTo(oldNode, newContent, ctx) {
129
+ if (ctx.ignoreActive && oldNode === document.activeElement) {
130
+ // don't morph focused element
131
+ } else if (newContent == null) {
132
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;
133
+
134
+ oldNode.remove();
135
+ ctx.callbacks.afterNodeRemoved(oldNode);
136
+ return null;
137
+ } else if (!isSoftMatch(oldNode, newContent)) {
138
+ if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;
139
+ if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;
140
+
141
+ oldNode.parentElement.replaceChild(newContent, oldNode);
142
+ ctx.callbacks.afterNodeAdded(newContent);
143
+ ctx.callbacks.afterNodeRemoved(oldNode);
144
+ return newContent;
145
+ } else {
146
+ if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;
147
+
148
+ if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) {
149
+ // ignore the head element
150
+ } else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== 'morph') {
151
+ handleHeadElement(newContent, oldNode, ctx);
152
+ } else {
153
+ syncNodeFrom(newContent, oldNode, ctx);
154
+ if (!ignoreValueOfActiveElement(oldNode, ctx)) {
155
+ morphChildren(newContent, oldNode, ctx);
156
+ }
157
+ }
158
+ ctx.callbacks.afterNodeMorphed(oldNode, newContent);
159
+ return oldNode;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * This is the core algorithm for matching up children. The idea is to use id sets to try to match up
165
+ * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but
166
+ * by using id sets, we are able to better match up with content deeper in the DOM.
167
+ *
168
+ * Basic algorithm is, for each node in the new content:
169
+ *
170
+ * - if we have reached the end of the old parent, append the new content
171
+ * - if the new content has an id set match with the current insertion point, morph
172
+ * - search for an id set match
173
+ * - if id set match found, morph
174
+ * - otherwise search for a "soft" match
175
+ * - if a soft match is found, morph
176
+ * - otherwise, prepend the new node before the current insertion point
177
+ *
178
+ * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved
179
+ * with the current node. See findIdSetMatch() and findSoftMatch() for details.
180
+ *
181
+ * @param {Element} newParent the parent element of the new content
182
+ * @param {Element } oldParent the old content that we are merging the new content into
183
+ * @param ctx the merge context
184
+ */
185
+ function morphChildren(newParent, oldParent, ctx) {
186
+ let nextNewChild = newParent.firstChild;
187
+ let insertionPoint = oldParent.firstChild;
188
+ let newChild;
189
+
190
+ // run through all the new content
191
+ while (nextNewChild) {
192
+ newChild = nextNewChild;
193
+ nextNewChild = newChild.nextSibling;
194
+
195
+ // if we are at the end of the exiting parent's children, just append
196
+ if (insertionPoint == null) {
197
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
198
+
199
+ oldParent.appendChild(newChild);
200
+ ctx.callbacks.afterNodeAdded(newChild);
201
+ removeIdsFromConsideration(ctx, newChild);
202
+ continue;
203
+ }
204
+
205
+ // if the current node has an id set match then morph
206
+ if (isIdSetMatch(newChild, insertionPoint, ctx)) {
207
+ morphOldNodeTo(insertionPoint, newChild, ctx);
208
+ insertionPoint = insertionPoint.nextSibling;
209
+ removeIdsFromConsideration(ctx, newChild);
210
+ continue;
211
+ }
212
+
213
+ // otherwise search forward in the existing old children for an id set match
214
+ let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);
215
+
216
+ // if we found a potential match, remove the nodes until that point and morph
217
+ if (idSetMatch) {
218
+ insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);
219
+ morphOldNodeTo(idSetMatch, newChild, ctx);
220
+ removeIdsFromConsideration(ctx, newChild);
221
+ continue;
222
+ }
223
+
224
+ // no id set match found, so scan forward for a soft match for the current node
225
+ let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);
226
+
227
+ // if we found a soft match for the current node, morph
228
+ if (softMatch) {
229
+ insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);
230
+ morphOldNodeTo(softMatch, newChild, ctx);
231
+ removeIdsFromConsideration(ctx, newChild);
232
+ continue;
233
+ }
234
+
235
+ // abandon all hope of morphing, just insert the new child before the insertion point
236
+ // and move on
237
+ if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;
238
+
239
+ oldParent.insertBefore(newChild, insertionPoint);
240
+ ctx.callbacks.afterNodeAdded(newChild);
241
+ removeIdsFromConsideration(ctx, newChild);
242
+ }
243
+
244
+ // remove any remaining old nodes that didn't match up with new content
245
+ while (insertionPoint !== null) {
246
+ let tempNode = insertionPoint;
247
+ insertionPoint = insertionPoint.nextSibling;
248
+ removeNode(tempNode, ctx);
249
+ }
250
+ }
251
+
252
+ //=============================================================================
253
+ // Attribute Syncing Code
254
+ //=============================================================================
255
+
256
+ /**
257
+ * @param attr {String} the attribute to be mutated
258
+ * @param to {Element} the element that is going to be updated
259
+ * @param updateType {("update"|"remove")}
260
+ * @param ctx the merge context
261
+ * @returns {boolean} true if the attribute should be ignored, false otherwise
262
+ */
263
+ function ignoreAttribute(attr, to, updateType, ctx) {
264
+ if (attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement) {
265
+ return true;
266
+ }
267
+ return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;
268
+ }
269
+
270
+ /**
271
+ * syncs a given node with another node, copying over all attributes and
272
+ * inner element state from the 'from' node to the 'to' node
273
+ *
274
+ * @param {Element} from the element to copy attributes & state from
275
+ * @param {Element} to the element to copy attributes & state to
276
+ * @param ctx the merge context
277
+ */
278
+ function syncNodeFrom(from, to, ctx) {
279
+ let type = from.nodeType;
280
+
281
+ // if is an element type, sync the attributes from the
282
+ // new node into the new node
283
+ if (type === 1 /* element type */) {
284
+ const fromAttributes = from.attributes;
285
+ const toAttributes = to.attributes;
286
+ for (const fromAttribute of fromAttributes) {
287
+ if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {
288
+ continue;
289
+ }
290
+ if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {
291
+ to.setAttribute(fromAttribute.name, fromAttribute.value);
292
+ }
293
+ }
294
+ // iterate backwards to avoid skipping over items when a delete occurs
295
+ for (let i = toAttributes.length - 1; 0 <= i; i--) {
296
+ const toAttribute = toAttributes[i];
297
+ if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {
298
+ continue;
299
+ }
300
+ if (!from.hasAttribute(toAttribute.name)) {
301
+ to.removeAttribute(toAttribute.name);
302
+ }
303
+ }
304
+ }
305
+
306
+ // sync text nodes
307
+ if (type === 8 /* comment */ || type === 3 /* text */) {
308
+ if (to.nodeValue !== from.nodeValue) {
309
+ to.nodeValue = from.nodeValue;
310
+ }
311
+ }
312
+
313
+ if (!ignoreValueOfActiveElement(to, ctx)) {
314
+ // sync input values
315
+ syncInputValue(from, to, ctx);
316
+ }
317
+ }
318
+
319
+ /**
320
+ * @param from {Element} element to sync the value from
321
+ * @param to {Element} element to sync the value to
322
+ * @param attributeName {String} the attribute name
323
+ * @param ctx the merge context
324
+ */
325
+ function syncBooleanAttribute(from, to, attributeName, ctx) {
326
+ if (from[attributeName] !== to[attributeName]) {
327
+ let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);
328
+ if (!ignoreUpdate) {
329
+ to[attributeName] = from[attributeName];
330
+ }
331
+ if (from[attributeName]) {
332
+ if (!ignoreUpdate) {
333
+ to.setAttribute(attributeName, from[attributeName]);
334
+ }
335
+ } else {
336
+ if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {
337
+ to.removeAttribute(attributeName);
338
+ }
339
+ }
340
+ }
341
+ }
342
+
343
+ /**
344
+ * NB: many bothans died to bring us information:
345
+ *
346
+ * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js
347
+ * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113
348
+ *
349
+ * @param from {Element} the element to sync the input value from
350
+ * @param to {Element} the element to sync the input value to
351
+ * @param ctx the merge context
352
+ */
353
+ function syncInputValue(from, to, ctx) {
354
+ if (
355
+ from instanceof HTMLInputElement &&
356
+ to instanceof HTMLInputElement &&
357
+ from.type !== 'file'
358
+ ) {
359
+ let fromValue = from.value;
360
+ let toValue = to.value;
361
+
362
+ // sync boolean attributes
363
+ syncBooleanAttribute(from, to, 'checked', ctx);
364
+ syncBooleanAttribute(from, to, 'disabled', ctx);
365
+
366
+ if (!from.hasAttribute('value')) {
367
+ if (!ignoreAttribute('value', to, 'remove', ctx)) {
368
+ to.value = '';
369
+ to.removeAttribute('value');
370
+ }
371
+ } else if (fromValue !== toValue) {
372
+ if (!ignoreAttribute('value', to, 'update', ctx)) {
373
+ to.setAttribute('value', fromValue);
374
+ to.value = fromValue;
375
+ }
376
+ }
377
+ } else if (from instanceof HTMLOptionElement) {
378
+ syncBooleanAttribute(from, to, 'selected', ctx);
379
+ } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {
380
+ let fromValue = from.value;
381
+ let toValue = to.value;
382
+ if (ignoreAttribute('value', to, 'update', ctx)) {
383
+ return;
384
+ }
385
+ if (fromValue !== toValue) {
386
+ to.value = fromValue;
387
+ }
388
+ if (to.firstChild && to.firstChild.nodeValue !== fromValue) {
389
+ to.firstChild.nodeValue = fromValue;
390
+ }
391
+ }
392
+ }
393
+
394
+ //=============================================================================
395
+ // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style
396
+ //=============================================================================
397
+ function handleHeadElement(newHeadTag, currentHead, ctx) {
398
+ let added = [];
399
+ let removed = [];
400
+ let preserved = [];
401
+ let nodesToAppend = [];
402
+
403
+ let headMergeStyle = ctx.head.style;
404
+
405
+ // put all new head elements into a Map, by their outerHTML
406
+ let srcToNewHeadNodes = new Map();
407
+ for (const newHeadChild of newHeadTag.children) {
408
+ srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);
409
+ }
410
+
411
+ // for each elt in the current head
412
+ for (const currentHeadElt of currentHead.children) {
413
+ // If the current head element is in the map
414
+ let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);
415
+ let isReAppended = ctx.head.shouldReAppend(currentHeadElt);
416
+ let isPreserved = ctx.head.shouldPreserve(currentHeadElt);
417
+ if (inNewContent || isPreserved) {
418
+ if (isReAppended) {
419
+ // remove the current version and let the new version replace it and re-execute
420
+ removed.push(currentHeadElt);
421
+ } else {
422
+ // this element already exists and should not be re-appended, so remove it from
423
+ // the new content map, preserving it in the DOM
424
+ srcToNewHeadNodes.delete(currentHeadElt.outerHTML);
425
+ preserved.push(currentHeadElt);
426
+ }
427
+ } else {
428
+ if (headMergeStyle === 'append') {
429
+ // we are appending and this existing element is not new content
430
+ // so if and only if it is marked for re-append do we do anything
431
+ if (isReAppended) {
432
+ removed.push(currentHeadElt);
433
+ nodesToAppend.push(currentHeadElt);
434
+ }
435
+ } else {
436
+ // if this is a merge, we remove this content since it is not in the new head
437
+ if (ctx.head.shouldRemove(currentHeadElt) !== false) {
438
+ removed.push(currentHeadElt);
439
+ }
440
+ }
441
+ }
442
+ }
443
+
444
+ // Push the remaining new head elements in the Map into the
445
+ // nodes to append to the head tag
446
+ nodesToAppend.push(...srcToNewHeadNodes.values());
447
+ log('to append: ', nodesToAppend);
448
+
449
+ let promises = [];
450
+ for (const newNode of nodesToAppend) {
451
+ log('adding: ', newNode);
452
+ let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;
453
+ log(newElt);
454
+ if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {
455
+ if (newElt.href || newElt.src) {
456
+ let resolve = null;
457
+ let promise = new Promise(function (_resolve) {
458
+ resolve = _resolve;
459
+ });
460
+ newElt.addEventListener('load', function () {
461
+ resolve();
462
+ });
463
+ promises.push(promise);
464
+ }
465
+ currentHead.appendChild(newElt);
466
+ ctx.callbacks.afterNodeAdded(newElt);
467
+ added.push(newElt);
468
+ }
469
+ }
470
+
471
+ // remove all removed elements, after we have appended the new elements to avoid
472
+ // additional network requests for things like style sheets
473
+ for (const removedElement of removed) {
474
+ if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {
475
+ currentHead.removeChild(removedElement);
476
+ ctx.callbacks.afterNodeRemoved(removedElement);
477
+ }
478
+ }
479
+
480
+ ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});
481
+ return promises;
482
+ }
483
+
484
+ //=============================================================================
485
+ // Misc
486
+ //=============================================================================
487
+
488
+ function log() {
489
+ //console.log(arguments);
490
+ }
491
+
492
+ function noOp() {}
493
+
494
+ /*
495
+ Deep merges the config object and the Idiomoroph.defaults object to
496
+ produce a final configuration object
497
+ */
498
+ function mergeDefaults(config) {
499
+ let finalConfig = {};
500
+ // copy top level stuff into final config
501
+ Object.assign(finalConfig, defaults);
502
+ Object.assign(finalConfig, config);
503
+
504
+ // copy callbacks into final config (do this to deep merge the callbacks)
505
+ finalConfig.callbacks = {};
506
+ Object.assign(finalConfig.callbacks, defaults.callbacks);
507
+ Object.assign(finalConfig.callbacks, config.callbacks);
508
+
509
+ // copy head config into final config (do this to deep merge the head)
510
+ finalConfig.head = {};
511
+ Object.assign(finalConfig.head, defaults.head);
512
+ Object.assign(finalConfig.head, config.head);
513
+ return finalConfig;
514
+ }
515
+
516
+ function createMorphContext(oldNode, newContent, config) {
517
+ config = mergeDefaults(config);
518
+ return {
519
+ target: oldNode,
520
+ newContent: newContent,
521
+ config: config,
522
+ morphStyle: config.morphStyle,
523
+ ignoreActive: config.ignoreActive,
524
+ ignoreActiveValue: config.ignoreActiveValue,
525
+ idMap: createIdMap(oldNode, newContent),
526
+ deadIds: new Set(),
527
+ callbacks: config.callbacks,
528
+ head: config.head,
529
+ };
530
+ }
531
+
532
+ function isIdSetMatch(node1, node2, ctx) {
533
+ if (node1 == null || node2 == null) {
534
+ return false;
535
+ }
536
+ if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {
537
+ if (node1.id !== '' && node1.id === node2.id) {
538
+ return true;
539
+ } else {
540
+ return getIdIntersectionCount(ctx, node1, node2) > 0;
541
+ }
542
+ }
543
+ return false;
544
+ }
545
+
546
+ function isSoftMatch(node1, node2) {
547
+ if (node1 == null || node2 == null) {
548
+ return false;
549
+ }
550
+ return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName;
551
+ }
552
+
553
+ function removeNodesBetween(startInclusive, endExclusive, ctx) {
554
+ while (startInclusive !== endExclusive) {
555
+ let tempNode = startInclusive;
556
+ startInclusive = startInclusive.nextSibling;
557
+ removeNode(tempNode, ctx);
558
+ }
559
+ removeIdsFromConsideration(ctx, endExclusive);
560
+ return endExclusive.nextSibling;
561
+ }
562
+
563
+ //=============================================================================
564
+ // Scans forward from the insertionPoint in the old parent looking for a potential id match
565
+ // for the newChild. We stop if we find a potential id match for the new child OR
566
+ // if the number of potential id matches we are discarding is greater than the
567
+ // potential id matches for the new child
568
+ //=============================================================================
569
+ function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
570
+ // max id matches we are willing to discard in our search
571
+ let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);
572
+
573
+ let potentialMatch = null;
574
+
575
+ // only search forward if there is a possibility of an id match
576
+ if (newChildPotentialIdCount > 0) {
577
+ let potentialMatch = insertionPoint;
578
+ // if there is a possibility of an id match, scan forward
579
+ // keep track of the potential id match count we are discarding (the
580
+ // newChildPotentialIdCount must be greater than this to make it likely
581
+ // worth it)
582
+ let otherMatchCount = 0;
583
+ while (potentialMatch != null) {
584
+ // If we have an id match, return the current potential match
585
+ if (isIdSetMatch(newChild, potentialMatch, ctx)) {
586
+ return potentialMatch;
587
+ }
588
+
589
+ // computer the other potential matches of this new content
590
+ otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);
591
+ if (otherMatchCount > newChildPotentialIdCount) {
592
+ // if we have more potential id matches in _other_ content, we
593
+ // do not have a good candidate for an id match, so return null
594
+ return null;
595
+ }
596
+
597
+ // advanced to the next old content child
598
+ potentialMatch = potentialMatch.nextSibling;
599
+ }
600
+ }
601
+ return potentialMatch;
602
+ }
603
+
604
+ //=============================================================================
605
+ // Scans forward from the insertionPoint in the old parent looking for a potential soft match
606
+ // for the newChild. We stop if we find a potential soft match for the new child OR
607
+ // if we find a potential id match in the old parents children OR if we find two
608
+ // potential soft matches for the next two pieces of new content
609
+ //=============================================================================
610
+ function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {
611
+ let potentialSoftMatch = insertionPoint;
612
+ let nextSibling = newChild.nextSibling;
613
+ let siblingSoftMatchCount = 0;
614
+
615
+ while (potentialSoftMatch != null) {
616
+ if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {
617
+ // the current potential soft match has a potential id set match with the remaining new
618
+ // content so bail out of looking
619
+ return null;
620
+ }
621
+
622
+ // if we have a soft match with the current node, return it
623
+ if (isSoftMatch(newChild, potentialSoftMatch)) {
624
+ return potentialSoftMatch;
625
+ }
626
+
627
+ if (isSoftMatch(nextSibling, potentialSoftMatch)) {
628
+ // the next new node has a soft match with this node, so
629
+ // increment the count of future soft matches
630
+ siblingSoftMatchCount++;
631
+ nextSibling = nextSibling.nextSibling;
632
+
633
+ // If there are two future soft matches, bail to allow the siblings to soft match
634
+ // so that we don't consume future soft matches for the sake of the current node
635
+ if (siblingSoftMatchCount >= 2) {
636
+ return null;
637
+ }
638
+ }
639
+
640
+ // advanced to the next old content child
641
+ potentialSoftMatch = potentialSoftMatch.nextSibling;
642
+ }
643
+
644
+ return potentialSoftMatch;
645
+ }
646
+
647
+ function parseContent(newContent) {
648
+ let parser = new DOMParser();
649
+
650
+ // remove svgs to avoid false-positive matches on head, etc.
651
+ let contentWithSvgsRemoved = newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim, '');
652
+
653
+ // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping
654
+ if (
655
+ contentWithSvgsRemoved.match(/<\/html>/) ||
656
+ contentWithSvgsRemoved.match(/<\/head>/) ||
657
+ contentWithSvgsRemoved.match(/<\/body>/)
658
+ ) {
659
+ let content = parser.parseFromString(newContent, 'text/html');
660
+ // if it is a full HTML document, return the document itself as the parent container
661
+ if (contentWithSvgsRemoved.match(/<\/html>/)) {
662
+ content.generatedByIdiomorph = true;
663
+ return content;
664
+ } else {
665
+ // otherwise return the html element as the parent container
666
+ let htmlElement = content.firstChild;
667
+ if (htmlElement) {
668
+ htmlElement.generatedByIdiomorph = true;
669
+ return htmlElement;
670
+ } else {
671
+ return null;
672
+ }
673
+ }
674
+ } else {
675
+ // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help
676
+ // deal with touchy tags like tr, tbody, etc.
677
+ let responseDoc = parser.parseFromString(
678
+ '<body><template>' + newContent + '</template></body>',
679
+ 'text/html'
680
+ );
681
+ let content = responseDoc.body.querySelector('template').content;
682
+ content.generatedByIdiomorph = true;
683
+ return content;
684
+ }
685
+ }
686
+
687
+ function normalizeContent(newContent) {
688
+ if (newContent == null) {
689
+ // noinspection UnnecessaryLocalVariableJS
690
+ const dummyParent = document.createElement('div');
691
+ return dummyParent;
692
+ } else if (newContent.generatedByIdiomorph) {
693
+ // the template tag created by idiomorph parsing can serve as a dummy parent
694
+ return newContent;
695
+ } else if (newContent instanceof Node) {
696
+ // a single node is added as a child to a dummy parent
697
+ const dummyParent = document.createElement('div');
698
+ dummyParent.append(newContent);
699
+ return dummyParent;
700
+ } else {
701
+ // all nodes in the array or HTMLElement collection are consolidated under
702
+ // a single dummy parent element
703
+ const dummyParent = document.createElement('div');
704
+ for (const elt of [...newContent]) {
705
+ dummyParent.append(elt);
706
+ }
707
+ return dummyParent;
708
+ }
709
+ }
710
+
711
+ function insertSiblings(previousSibling, morphedNode, nextSibling) {
712
+ let stack = [];
713
+ let added = [];
714
+ while (previousSibling != null) {
715
+ stack.push(previousSibling);
716
+ previousSibling = previousSibling.previousSibling;
717
+ }
718
+ while (stack.length > 0) {
719
+ let node = stack.pop();
720
+ added.push(node); // push added preceding siblings on in order and insert
721
+ morphedNode.parentElement.insertBefore(node, morphedNode);
722
+ }
723
+ added.push(morphedNode);
724
+ while (nextSibling != null) {
725
+ stack.push(nextSibling);
726
+ added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add
727
+ nextSibling = nextSibling.nextSibling;
728
+ }
729
+ while (stack.length > 0) {
730
+ morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);
731
+ }
732
+ return added;
733
+ }
734
+
735
+ function findBestNodeMatch(newContent, oldNode, ctx) {
736
+ let currentElement;
737
+ currentElement = newContent.firstChild;
738
+ let bestElement = currentElement;
739
+ let score = 0;
740
+ while (currentElement) {
741
+ let newScore = scoreElement(currentElement, oldNode, ctx);
742
+ if (newScore > score) {
743
+ bestElement = currentElement;
744
+ score = newScore;
745
+ }
746
+ currentElement = currentElement.nextSibling;
747
+ }
748
+ return bestElement;
749
+ }
750
+
751
+ function scoreElement(node1, node2, ctx) {
752
+ if (isSoftMatch(node1, node2)) {
753
+ return 0.5 + getIdIntersectionCount(ctx, node1, node2);
754
+ }
755
+ return 0;
756
+ }
757
+
758
+ function removeNode(tempNode, ctx) {
759
+ removeIdsFromConsideration(ctx, tempNode);
760
+ if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;
761
+
762
+ tempNode.remove();
763
+ ctx.callbacks.afterNodeRemoved(tempNode);
764
+ }
765
+
766
+ //=============================================================================
767
+ // ID Set Functions
768
+ //=============================================================================
769
+
770
+ function isIdInConsideration(ctx, id) {
771
+ return !ctx.deadIds.has(id);
772
+ }
773
+
774
+ function idIsWithinNode(ctx, id, targetNode) {
775
+ let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;
776
+ return idSet.has(id);
777
+ }
778
+
779
+ function removeIdsFromConsideration(ctx, node) {
780
+ let idSet = ctx.idMap.get(node) || EMPTY_SET;
781
+ for (const id of idSet) {
782
+ ctx.deadIds.add(id);
783
+ }
784
+ }
785
+
786
+ function getIdIntersectionCount(ctx, node1, node2) {
787
+ let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;
788
+ let matchCount = 0;
789
+ for (const id of sourceSet) {
790
+ // a potential match is an id in the source and potentialIdsSet, but
791
+ // that has not already been merged into the DOM
792
+ if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {
793
+ ++matchCount;
794
+ }
795
+ }
796
+ return matchCount;
797
+ }
798
+
799
+ /**
800
+ * A bottom up algorithm that finds all elements with ids inside of the node
801
+ * argument and populates id sets for those nodes and all their parents, generating
802
+ * a set of ids contained within all nodes for the entire hierarchy in the DOM
803
+ *
804
+ * @param node {Element}
805
+ * @param {Map<Node, Set<String>>} idMap
806
+ */
807
+ function populateIdMapForNode(node, idMap) {
808
+ let nodeParent = node.parentElement;
809
+ // find all elements with an id property
810
+ let idElements = node.querySelectorAll('[id]');
811
+ for (const elt of idElements) {
812
+ let current = elt;
813
+ // walk up the parent hierarchy of that element, adding the id
814
+ // of element to the parent's id set
815
+ while (current !== nodeParent && current != null) {
816
+ let idSet = idMap.get(current);
817
+ // if the id set doesn't exist, create it and insert it in the map
818
+ if (idSet == null) {
819
+ idSet = new Set();
820
+ idMap.set(current, idSet);
821
+ }
822
+ idSet.add(elt.id);
823
+ current = current.parentElement;
824
+ }
825
+ }
826
+ }
827
+
828
+ /**
829
+ * This function computes a map of nodes to all ids contained within that node (inclusive of the
830
+ * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows
831
+ * for a looser definition of "matching" than tradition id matching, and allows child nodes
832
+ * to contribute to a parent nodes matching.
833
+ *
834
+ * @param {Element} oldContent the old content that will be morphed
835
+ * @param {Element} newContent the new content to morph to
836
+ * @returns {Map<Node, Set<String>>} a map of nodes to id sets for the
837
+ */
838
+ function createIdMap(oldContent, newContent) {
839
+ let idMap = new Map();
840
+ populateIdMapForNode(oldContent, idMap);
841
+ populateIdMapForNode(newContent, idMap);
842
+ return idMap;
843
+ }
844
+
845
+ //=============================================================================
846
+ // This is what ends up becoming the Idiomorph global object
847
+ //=============================================================================
848
+ return {
849
+ morph,
850
+ defaults,
851
+ };
852
+ })();
853
+
854
+ export {Idiomorph};