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 [#1083]
Related to [@hotwired/turbo-rails#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]`.

Along with `turbo:before-morph`, this commit also introduces a
`turbo:before-morph-attribute` to correspond to the
`beforeAttributeUpdated` callback that Idiomorph provides. When
listeners (like an `HTMLDetailsElement`, an `HTMLDialogElement`, or a
Stimulus controller) want to preserve the state of an attribute, they
can cancel the `turbo:before-morph-attribute` event that corresponds
with the attribute name (through `event.detail.attributeName`).

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]: 9944490
[#1083]: #1083
[@hotwired/turbo-rails#533]: hotwired/turbo-rails#533
  • Loading branch information
seanpdoyle committed Jan 25, 2024
1 parent 617e6d0 commit ade7649
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 12 deletions.
42 changes: 33 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,9 @@ export class MorphRenderer extends Renderer {
callbacks: {
beforeNodeAdded: this.#shouldAddElement,
beforeNodeMorphed: this.#shouldMorphElement,
beforeNodeRemoved: this.#shouldRemoveElement
beforeAttributeUpdated: this.#shouldUpdateAttribute,
beforeNodeRemoved: this.#shouldRemoveElement,
afterNodeMorphed: this.#didMorphElement
}
})
}
Expand All @@ -44,12 +39,41 @@ 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
}
}

#shouldUpdateAttribute = (attributeName, target, mutationType) => {
const event = dispatch("turbo:before-morph-attribute", { cancelable: true, target, detail: { attributeName, mutationType } })

return !event.defaultPrevented
}

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

#shouldRemoveElement = (node) => {
return this.#shouldMorphElement(node)
}
Expand Down
46 changes: 44 additions & 2 deletions src/tests/fixtures/page_refresh.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,45 @@
<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()
}
}
})

addEventListener("turbo:before-morph-attribute", (event) => {
const { target, detail: { attributeName, mutationType } } = event

for (const { element, context } of application.controllers) {
const pattern = new RegExp(`data-${context.identifier}-\\w+-value`)

if (element === target) {
event.preventDefault()
}
}
})

application.register("test", class extends Controller {
static targets = ["output"]
static values = { state: String }

capture({ target }) {
this.stateValue = target.value
}

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

<style>
body {
Expand Down Expand Up @@ -42,15 +81,18 @@ <h2>Frame to be preserved</h2>
</turbo-frame>
</div>

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

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

<p><a id="replace-link" data-turbo-action="replace" href="/src/tests/fixtures/page_refresh.html?param=something">Link with params to refresh the page</a></p>
<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
55 changes: 54 additions & 1 deletion src/tests/functional/page_refresh_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,60 @@ test("renders a page refresh with morphing", async ({ page }) => {
await nextEventNamed(page, "turbo:render", { renderMethod: "morph" })
})

test("renders a page refresh with morphing when the paths are the same but search params are diferent", async ({ page }) => {
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("turbo:before-morph-attribute Stimulus listeners can handle morphing attributes", async ({ page }) => {
await page.goto("/src/tests/fixtures/page_refresh.html")
const controller = page.locator("#stimulus-controller")
const input = controller.locator("input")

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

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

await expect(controller).toHaveAttribute("data-test-state-value", "controller state")
await expect(page.locator("#form-text")).toHaveValue("")
await expect(page.locator("#test-output")).toHaveText("connected")
})


test("renders a page refresh with morphing when the paths are the same but search params are different", async ({ page }) => {
await page.goto("/src/tests/fixtures/page_refresh.html")

await page.click("#replace-link")
Expand Down

0 comments on commit ade7649

Please sign in to comment.