@dinoreic/fez 0.1.0

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