Skip to content

Commit

Permalink
Add Turbo stream morph action
Browse files Browse the repository at this point in the history
  • Loading branch information
omarluq committed Feb 15, 2024
1 parent fccb3a4 commit c3257f4
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/core/drive/morph_renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ export class MorphRenderer extends PageRenderer {
})

return !event.defaultPrevented
} else {
return false
}

return false
}
}

Expand Down
37 changes: 37 additions & 0 deletions src/core/streams/stream_actions.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { session } from "../"
import { morph } from "idiomorph"
import { dispatch } from "../../util"


export const StreamActions = {
after() {
Expand Down Expand Up @@ -37,4 +40,38 @@ export const StreamActions = {
refresh() {
session.refresh(this.baseURI, this.requestId)
}

morph() {
this.targetElements.forEach((targetElement) => {
try {
const morphStyle = this.getAttribute("data-turbo-morph-style") || "outerHTML"
const ignoreActive = this.getAttribute("data-turbo-morph-ignore-active") || true
const ignoreActiveValue = this.getAttribute("data-turbo-morph-ignore-active-value") || true
const head = this.getAttribute("data-turbo-morph-head") || 'merge'
morph(targetElement, this.templateContent, {
morphStyle: morphStyle,
ignoreActive: ignoreActive,
ignoreActiveValue: ignoreActiveValue,
head: head,
callbacks: {
beforeNodeAdded: (node) => {
return !(node.id && node.hasAttribute("data-turbo-permanent") && document.getElementById(node.id))
},
afterNodeMorphed: (oldNode, newNode) => {
if (newNode instanceof HTMLElement) {
dispatch("turbo:morph-element", {
target: oldNode,
detail: {
newElement: newNode
}
})
}
}
}
})
} catch (error) {
console.error(error)
}
})
}
}
13 changes: 13 additions & 0 deletions src/tests/unit/stream_element_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,16 @@ test("test action=refresh discarded when matching request id", async () => {

assert.ok(document.body.hasAttribute("data-modified"))
})

test("action=morph", async () => {
const templateElement = createTemplateElement(`<div id="hello">Hello Turbo Morphed</div>`)
const element = createStreamElement("morph", "hello", templateElement)

assert.equal(subject.find("#hello")?.textContent, "Hello Turbo")

subject.append(element)
await nextAnimationFrame()

assert.notOk(subject.find("#hello")?.textContent, "Hello Turbo")
assert.equal(subject.find("#hello")?.textContent, "Hello Turbo Morphed")
})

0 comments on commit c3257f4

Please sign in to comment.