Skip to content

Commit

Permalink
Introduce turbo:before-morph and re-purpose turbo:morph
Browse files Browse the repository at this point in the history
Follow-up to [9944490][]
Related to [hotwired#1083]
Related to [@hotwired/turbo-railshotwired#533][]

The problem
---

Some client-side plugins are losing their state when elements are
morphed.

Without resorting to `MutationObserver` instances to determine when a
node is morphed, uses of those plugins don't have the ability to prevent
(without `[data-turbo-permanent]`) or respond to the morphing.

The proposal
---

This commit introduces a `turbo:before-morph` event that'll dispatch as
part of the Idiomorph `beforeNodeMorphed` callback. It'll give
interested parties access to the nodes before and after a morph. If that
event is cancelled via `event.preventDefault()`, it'll skip the morph as
if the element were marked with `[data-turbo-permanent]`.

Similarly, this commit re-purposes the new `turbo:morph` event to be
dispatched for every morphed node (via Idiomorph's `afterNodeMorphed`
callback). The original implementation dispatched the event for the
`<body>` element as part of `MorphRenderer`'s lifecycle. That event will
still be dispatched, since `<body>` is the first element the callback
will fire for. In addition to that event, each individual morphed node
will dispatch one.

This commit re-introduced test coverage for a Stimulus controller to
demonstrate how an interested party might respond. It isn't immediately
clear with that code should live, but once we iron out the details, it
could be part of a `@hotwired/turbo/stimulus` package, or a
`@hotwired/stimulus/turbo` package that users (or
`@hotwired/turbo-rails`) could opt-into.

[9944490]: hotwired@9944490
[hotwired#1083]: hotwired#1083
[@hotwired/turbo-railshotwired#533]: hotwired/turbo-rails#533
  • Loading branch information
seanpdoyle committed Dec 3, 2023
1 parent 5c48398 commit 3aa2039
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 10 deletions.
35 changes: 26 additions & 9 deletions src/core/drive/morph_renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,6 @@ export class MorphRenderer extends Renderer {
async #morphBody() {
this.#morphElements(this.currentElement, this.newElement)
this.#reloadRemoteFrames()

dispatch("turbo:morph", {
detail: {
currentElement: this.currentElement,
newElement: this.newElement
}
})
}

#morphElements(currentElement, newElement, morphStyle = "outerHTML") {
Expand All @@ -33,7 +26,8 @@ export class MorphRenderer extends Renderer {
callbacks: {
beforeNodeAdded: this.#shouldAddElement,
beforeNodeMorphed: this.#shouldMorphElement,
beforeNodeRemoved: this.#shouldRemoveElement
beforeNodeRemoved: this.#shouldRemoveElement,
afterNodeMorphed: this.#didMorphElement
}
})
}
Expand All @@ -44,12 +38,35 @@ export class MorphRenderer extends Renderer {

#shouldMorphElement = (oldNode, newNode) => {
if (oldNode instanceof HTMLElement) {
return !oldNode.hasAttribute("data-turbo-permanent") && (this.isMorphingTurboFrame || !this.#isFrameReloadedWithMorph(oldNode))
if (!oldNode.hasAttribute("data-turbo-permanent") && (this.isMorphingTurboFrame || !this.#isFrameReloadedWithMorph(oldNode))) {
const event = dispatch("turbo:before-morph", {
cancelable: true,
target: oldNode,
detail: {
newElement: newNode
}
})

return !event.defaultPrevented
} else {
return false
}
} else {
return true
}
}

#didMorphElement = (oldNode, newNode) => {
if (newNode instanceof HTMLElement) {
dispatch("turbo:morph", {
target: oldNode,
detail: {
newElement: newNode
}
})
}
}

#shouldRemoveElement = (node) => {
return this.#shouldMorphElement(node)
}
Expand Down
26 changes: 25 additions & 1 deletion src/tests/fixtures/page_refresh.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,28 @@
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script src="/dist/turbo.es2017-umd.js" data-turbo-track="reload"></script>
<script src="/src/tests/fixtures/test.js"></script>
<script type="module">
import { Application, Controller } from "https://unpkg.com/@hotwired/stimulus/dist/stimulus.js"

const application = Application.start()

addEventListener("turbo:morph", ({ target }) => {
for (const { element, context } of application.controllers) {
if (element === target) {
context.disconnect()
context.connect()
}
}
})

application.register("test", class extends Controller {
static targets = ["output"]

outputTargetConnected(target) {
target.textContent = "connected"
}
})
</script>

<style>
body {
Expand Down Expand Up @@ -42,12 +64,14 @@ <h2>Frame to be preserved</h2>

<div id="stimulus-controller" data-controller="test">
<h3>Element with Stimulus controller</h3>

<div id="test-output" data-test-target="output">reset</div>
</div>

<p><a id="link" href="/src/tests/fixtures/one.html">Link to another page</a></p>

<form id="form" action="/__turbo/refresh" method="post" class="redirect">
<input type="text" name="text" value="">
<input id="form-text" type="text" name="text" value="">
<input type="hidden" name="path" value="/src/tests/fixtures/page_refresh.html">
<input type="hidden" name="sleep" value="50">
<input id="form-submit" type="submit" value="form[method=post]">
Expand Down
2 changes: 2 additions & 0 deletions src/tests/fixtures/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@
"turbo:frame-load",
"turbo:frame-render",
"turbo:frame-missing",
"turbo:before-morph",
"turbo:before-frame-morph",
"turbo:morph",
"turbo:reload"
])

Expand Down
36 changes: 36 additions & 0 deletions src/tests/functional/page_refresh_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,42 @@ test("renders a page refresh with morphing", async ({ page }) => {
await nextEventNamed(page, "turbo:render", { renderMethod: "morph" })
})

test("dispatches a turbo:before-morph and turbo:morph event for each morphed element", async ({ page }) => {
await page.goto("/src/tests/fixtures/page_refresh.html")
await page.fill("#form-text", "Morph me")
await page.click("#form-submit")

await nextEventOnTarget(page, "form-text", "turbo:before-morph")
await nextEventOnTarget(page, "form-text", "turbo:morph")
})

test("preventing a turbo:before-morph prevents the morph", async ({ page }) => {
const input = await page.locator("#form-text")
const submit = await page.locator("#form-submit")

await page.goto("/src/tests/fixtures/page_refresh.html")
await input.evaluate((input) => input.addEventListener("turbo:before-morph", (event) => event.preventDefault()))
await input.fill("Morph me")
await submit.click()

await nextEventOnTarget(page, "form-text", "turbo:before-morph")
await noNextEventOnTarget(page, "form-text", "turbo:morph")

await expect(input).toHaveValue("Morph me")
})

test("turbo:morph Stimulus listeners can handle morphing", async ({ page }) => {
await page.goto("/src/tests/fixtures/page_refresh.html")

await expect(page.locator("#test-output")).toHaveText("connected")

await page.fill("#form-text", "Ignore me")
await page.click("#form-submit")

await expect(page.locator("#form-text")).toHaveValue("")
await expect(page.locator("#test-output")).toHaveText("connected")
})

test("doesn't morph when the turbo-refresh-method meta tag is not 'morph'", async ({ page }) => {
await page.goto("/src/tests/fixtures/page_refresh_replace.html")

Expand Down

0 comments on commit 3aa2039

Please sign in to comment.