|
| 1 | +import morphdom from "../morphdom/2.6.1/morphdom.js"; |
| 2 | + |
| 3 | + |
| 4 | +export class MorphdomMorpher { |
| 5 | + constructor(options) { |
| 6 | + this.options = options; |
| 7 | + } |
| 8 | + |
| 9 | + morph(dom, htmlElement) { |
| 10 | + return morphdom(dom, htmlElement, this.getOptions()); |
| 11 | + } |
| 12 | + |
| 13 | + getOptions() { |
| 14 | + const reloadScriptElements = this.options.RELOAD_SCRIPT_ELEMENTS || false; |
| 15 | + return { |
| 16 | + childrenOnly: false, |
| 17 | + // eslint-disable-next-line consistent-return |
| 18 | + getNodeKey(node) { |
| 19 | + // A node's unique identifier. Used to rearrange elements rather than |
| 20 | + // creating and destroying an element that already exists. |
| 21 | + if (node.attributes) { |
| 22 | + const key = |
| 23 | + node.getAttribute("unicorn:key") || |
| 24 | + node.getAttribute("u:key") || |
| 25 | + node.id; |
| 26 | + |
| 27 | + if (key) { |
| 28 | + return key; |
| 29 | + } |
| 30 | + } |
| 31 | + }, |
| 32 | + // eslint-disable-next-line consistent-return |
| 33 | + onBeforeElUpdated(fromEl, toEl) { |
| 34 | + // Because morphdom also supports vDom nodes, it uses isSameNode to detect |
| 35 | + // sameness. When dealing with DOM nodes, we want isEqualNode, otherwise |
| 36 | + // isSameNode will ALWAYS return false. |
| 37 | + if (fromEl.isEqualNode(toEl)) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + if (reloadScriptElements) { |
| 42 | + if (fromEl.nodeName === "SCRIPT" && toEl.nodeName === "SCRIPT") { |
| 43 | + // https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769 |
| 44 | + const script = document.createElement("script"); |
| 45 | + // copy over the attributes |
| 46 | + [...toEl.attributes].forEach((attr) => { |
| 47 | + script.setAttribute(attr.nodeName, attr.nodeValue); |
| 48 | + }); |
| 49 | + |
| 50 | + script.innerHTML = toEl.innerHTML; |
| 51 | + fromEl.replaceWith(script); |
| 52 | + |
| 53 | + return false; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return true; |
| 58 | + }, |
| 59 | + onNodeAdded(node) { |
| 60 | + if (reloadScriptElements) { |
| 61 | + if (node.nodeName === "SCRIPT") { |
| 62 | + // https://github.com/patrick-steele-idem/morphdom/issues/178#issuecomment-652562769 |
| 63 | + const script = document.createElement("script"); |
| 64 | + // copy over the attributes |
| 65 | + [...node.attributes].forEach((attr) => { |
| 66 | + script.setAttribute(attr.nodeName, attr.nodeValue); |
| 67 | + }); |
| 68 | + |
| 69 | + script.innerHTML = node.innerHTML; |
| 70 | + node.replaceWith(script); |
| 71 | + } |
| 72 | + } |
| 73 | + }, |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments