Skip to content

Commit

Permalink
workaround for corner case where a data-turbo-permanent node is moved…
Browse files Browse the repository at this point in the history
… to a random spot in the doc before morphing.
  • Loading branch information
botandrose-machine committed Dec 23, 2024
1 parent f84b5bc commit 0b5715e
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/core/morphing.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import { Idiomorph } from "idiomorph/dist/idiomorph.esm.js"
import { dispatch } from "../util"

export function morphElements(currentElement, newElement, { callbacks, ...options } = {}) {
const cbs = new DefaultIdiomorphCallbacks(callbacks)
Idiomorph.morph(currentElement, newElement, {
...options,
twoPass: true,
callbacks: new DefaultIdiomorphCallbacks(callbacks)
callbacks: cbs
})
cbs.pruneDuplicatedPermanentNodes(currentElement)
}

export function morphChildren(currentElement, newElement) {
Expand All @@ -22,6 +24,25 @@ class DefaultIdiomorphCallbacks {
this.#beforeNodeMorphed = beforeNodeMorphed || (() => true)
}

// workaround for data-turbo-permanent elements being moved to a weird location in the DOM pre-morph
#permanentNodesWithDuplicates = []

beforeNodePantried = (node) => {
if (node.id && node.hasAttribute("data-turbo-permanent") && document.getElementById(node.id)) {
this.#permanentNodesWithDuplicates.push(node)
return false
}
}

pruneDuplicatedPermanentNodes(root) {
this.#permanentNodesWithDuplicates.forEach(node => {
root.querySelectorAll(`[id=${node.id}]`).forEach(dup => {
if (dup !== node) dup.remove()
})
})
}
// end workaround

beforeNodeAdded = (node) => {
return !(node.id && node.hasAttribute("data-turbo-permanent") && document.getElementById(node.id))
}
Expand Down

0 comments on commit 0b5715e

Please sign in to comment.