Skip to content

Commit

Permalink
Extract Morph class, then use it in FrameRenderer
Browse files Browse the repository at this point in the history
Declaring all `Idiomorph`-related logic in the `MorphRenderer` limits
its accessibility to other parts of the system. For example,
`<turbo-frame refresh="morph">` elements are unable to morph their
renders when driven by `<a>` navigations or `<form>` submissions.

This commit extracts the bulk of the morphing logic into a new `Morph`
class. The `Morph` encapsulates the call to `Idiomorph`, along with the
remote `<turbo-frame>` reloading and `[data-turbo-permanent]` checking.

With this extraction, the `MorphRenderer` is implemented in terms of
delegating to the static `Morph.render` method.

With that extraction in place, the `FrameRenderer.renderElement` method
can incorporate the `element.src && element.refresh === "morph"` check,
calling `FrameRenderer.morph` when true, then falling back to the
default `FrameRenderer.replace` when false.

For the sake of consistency, declare all `Renderer` subclasses'
`renderElement` methods in terms of `static replace` and `static morph`
methods to be explicit about which styles they support.

This commit includes test coverage for morphing `<turbo-frame
refresh="morph">` elements driven by typical navigation.

The potential for `<turbo-stream action="morph">`
---

With the `Morph.render` function existing separately from
`MorphRenderer`, there's the potential to add a new
`StreamAction.morph`.

The implementation would look something like:

```js
morph() {
  this.targetElements.forEach((targetElement) => {
    Morph.render(targetElement, this.templateContent)
  })
}
```

I've omitted that from this commit because I'm not sure if that's an
interface we're interested in introducing, but I did want to highlight
the possibility here. It'd be an Idiomorph-powered version of the
[turbo-morph][] package.

[turbo-morph]: https://github.com/marcoroth/turbo-morph
  • Loading branch information
seanpdoyle committed Oct 12, 2023
1 parent 2fb0190 commit 2fd95cf
Show file tree
Hide file tree
Showing 11 changed files with 187 additions and 86 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"access": "public"
},
"dependencies": {
"idiomorph": "https://github.com/basecamp/idiomorph#rollout-build"
"idiomorph": "^0.0.9"
},
"devDependencies": {
"@open-wc/testing": "^3.1.7",
Expand Down
4 changes: 4 additions & 0 deletions src/core/drive/error_renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { Renderer } from "../renderer"

export class ErrorRenderer extends Renderer {
static renderElement(currentElement, newElement) {
ErrorRenderer.replace(currentElement, newElement)
}

static replace(currentElement, newElement) {
const { documentElement, body } = document

documentElement.replaceChild(newElement, body)
Expand Down
87 changes: 7 additions & 80 deletions src/core/drive/morph_renderer.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,20 @@
import Idiomorph from "idiomorph"
import { dispatch, nextAnimationFrame } from "../../util"
import { Renderer } from "../renderer"
import { Morph } from "../morph"

export class MorphRenderer extends Renderer {
static renderElement(currentElement, newElement) {
MorphRenderer.morph(currentElement, newElement)
}

static morph(currentElement, newElement) {
Morph.render(currentElement, newElement)
}

async render() {
if (this.willRender) await this.#morphBody()
if (this.willRender) this.renderElement(this.currentElement, this.newElement)
}

get renderMethod() {
return "morph"
}

// Private

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") {
Idiomorph.morph(currentElement, newElement, {
morphStyle: morphStyle,
callbacks: {
beforeNodeMorphed: this.#shouldMorphElement,
beforeNodeRemoved: this.#shouldRemoveElement,
afterNodeMorphed: this.#reloadStimulusControllers
}
})
}

#reloadRemoteFrames() {
this.#remoteFrames().forEach((frame) => {
if (this.#isFrameReloadedWithMorph(frame)) {
this.#renderFrameWithMorph(frame)
}
frame.reload()
})
}

#renderFrameWithMorph(frame) {
frame.addEventListener("turbo:before-frame-render", (event) => {
event.detail.render = this.#morphFrameUpdate
}, { once: true })
}

#morphFrameUpdate = (currentElement, newElement) => {
dispatch("turbo:before-frame-morph", {
target: currentElement,
detail: { currentElement, newElement }
})
this.#morphElements(currentElement, newElement, "innerHTML")
}

#shouldRemoveElement = (node) => {
return this.#shouldMorphElement(node)
}

#shouldMorphElement = (node) => {
if (node instanceof HTMLElement) {
return !node.hasAttribute("data-turbo-permanent")
} else {
return true
}
}

#reloadStimulusControllers = async (node) => {
if (node instanceof HTMLElement && node.hasAttribute("data-controller")) {
const originalAttribute = node.getAttribute("data-controller")
node.removeAttribute("data-controller")
await nextAnimationFrame()
node.setAttribute("data-controller", originalAttribute)
}
}

#isFrameReloadedWithMorph(element) {
return element.src && element.refresh === "morph"
}

#remoteFrames() {
return document.querySelectorAll("turbo-frame[src]")
}
}
4 changes: 4 additions & 0 deletions src/core/drive/page_renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import { activateScriptElement, waitForLoad } from "../../util"

export class PageRenderer extends Renderer {
static renderElement(currentElement, newElement) {
PageRenderer.replace(currentElement, newElement)
}

static replace(currentElement, newElement) {
if (document.body && newElement instanceof HTMLBodyElement) {
document.body.replaceWith(newElement)
} else {
Expand Down
28 changes: 27 additions & 1 deletion src/core/frames/frame_renderer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import { activateScriptElement, nextAnimationFrame } from "../../util"
import { activateScriptElement, nextAnimationFrame, dispatch } from "../../util"
import { Renderer } from "../renderer"
import { Morph } from "../morph"

export class FrameRenderer extends Renderer {
static renderElement(currentElement, newElement) {
if (currentElement.src && currentElement.refresh === "morph") {
FrameRenderer.morph(currentElement, newElement)
} else {
FrameRenderer.replace(currentElement, newElement)
}
}

static replace(currentElement, newElement) {
const destinationRange = document.createRange()
destinationRange.selectNodeContents(currentElement)
destinationRange.deleteContents()
Expand All @@ -15,6 +24,15 @@ export class FrameRenderer extends Renderer {
}
}

static morph(currentElement, newElement) {
dispatch("turbo:before-frame-morph", {
target: currentElement,
detail: { currentElement, newElement }
})

Morph.render(currentElement, newElement.children, "innerHTML")
}

constructor(delegate, currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {
super(currentSnapshot, newSnapshot, renderElement, isPreview, willRender)
this.delegate = delegate
Expand All @@ -24,6 +42,14 @@ export class FrameRenderer extends Renderer {
return true
}

get renderMethod() {
if (this.currentElement.refresh === "morph") {
return "morph"
} else {
return super.renderMethod
}
}

async render() {
await nextAnimationFrame()
this.preservingPermanentElements(() => {
Expand Down
54 changes: 54 additions & 0 deletions src/core/morph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import "idiomorph"
import { nextAnimationFrame } from "../util"

export class Morph {
static render(currentElement, newElement, morphStyle) {
const morph = new this(currentElement, newElement)

morph.render(morphStyle)
}

constructor(currentElement, newElement) {
this.currentElement = currentElement
this.newElement = newElement
}

render(morphStyle = "outerHTML") {
window.Idiomorph.morph(this.currentElement, this.newElement, {
ignoreActiveValue: true,
morphStyle: morphStyle,
callbacks: {
beforeNodeMorphed: shouldMorphElement,
beforeNodeRemoved: shouldRemoveElement,
afterNodeMorphed: reloadStimulusControllers
}
})

this.#remoteFrames.forEach((frame) => frame.reload())
}

get #remoteFrames() {
return this.currentElement.querySelectorAll("turbo-frame[src]")
}
}

function shouldRemoveElement(node) {
return shouldMorphElement(node)
}

function shouldMorphElement(node) {
if (node instanceof HTMLElement) {
return !node.hasAttribute("data-turbo-permanent")
} else {
return true
}
}

async function reloadStimulusControllers(node) {
if (node instanceof HTMLElement && node.hasAttribute("data-controller")) {
const originalAttribute = node.getAttribute("data-controller")
node.removeAttribute("data-controller")
await nextAnimationFrame()
node.setAttribute("data-controller", originalAttribute)
}
}
11 changes: 11 additions & 0 deletions src/tests/fixtures/frames.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ <h2>Frames: #hello</h2>

</turbo-frame>

<turbo-frame id="refresh-morph" refresh="morph">
<h2>Source: #refresh-morph</h2>

<a href="/src/tests/fixtures/frames/refresh_morph.html">Navigate #refresh-morph</a>

<form action="/__turbo/redirect">
<input type="hidden" name="path" value="/src/tests/fixtures/frames/refresh_morph.html">
<input id="input-in-refresh-morph" type="text" name="query" placeholder="input in turbo-frame[refresh=morph]">
</form>
</turbo-frame>

<a id="link-hello-advance" href="/src/tests/fixtures/frames/hello.html" data-turbo-frame="hello" data-turbo-action="advance">advance #hello</a>

<turbo-frame id="nested-root" target="frame">
Expand Down
23 changes: 23 additions & 0 deletions src/tests/fixtures/frames/refresh_morph.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Frames: Refresh=Morph</title>
<script src="/dist/turbo.es2017-umd.js" data-turbo-track="reload"></script>
<script src="/src/tests/fixtures/test.js"></script>
</head>
<body>
<h1>Refresh=Morph</h1>

<turbo-frame id="refresh-morph">
<h2>Destination: #refresh-morph</h2>

<a href="/src/tests/fixtures/frames.html">Navigate #refresh-morph</a>

<form action="/__turbo/redirect">
<input type="hidden" name="path" value="/src/tests/fixtures/frames.html">
<input id="input-in-refresh-morph" type="text" name="query" placeholder="input in turbo-frame[refresh=morph]">
</form>
</turbo-frame>
</body>
</html>
47 changes: 47 additions & 0 deletions src/tests/functional/frame_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
attributeForSelector,
hasSelector,
listenForEventOnTarget,
locatorHasFocus,
nextAttributeMutationNamed,
noNextAttributeMutationNamed,
nextBeat,
Expand Down Expand Up @@ -882,6 +883,52 @@ test("test navigating a eager frame with a link[method=get] that does not fetch
assert.equal(pathname(page.url()), "/src/tests/fixtures/page_with_eager_frame.html")
})

test("test driving a morph frame with link preserves focus", async ({ page }) => {
const frame = await page.locator("turbo-frame#refresh-morph")
const link = await frame.locator("a:first-of-type")

assert.include(await frame.textContent("h2"), "Source: #refresh-morph")

await link.focus()
await link.press("Enter")
await nextEventOnTarget(page, "refresh-morph", "turbo:frame-render")

assert.ok(await locatorHasFocus(link), "restores focus after page loads")
assert.include(await frame.textContent("h2"), "Destination: #refresh-morph")
assert.equal(await frame.count("#input-in-morph"), 1)

await link.press("Enter")
await nextEventOnTarget(page, "refresh-morph", "turbo:frame-render")

assert.ok(await locatorHasFocus(link), "restores focus after page loads")
assert.include(await frame.textContent("h2"), "Source: #refresh-morph")
assert.equal(await frame.count("#input-in-morph"), 1)
})

test("test driving a morph frame with form preserves focus", async ({ page }) => {
const frame = await page.locator("turbo-frame#refresh-morph")
const input = await frame.locator("#input-in-refresh-morph")

assert.include(await frame.textContent("h2"), "Source: #refresh-morph")

await input.type("hello")
await input.press("Enter")
await nextEventOnTarget(page, "refresh-morph", "turbo:frame-render")

assert.ok(await locatorHasFocus(input), "restores focus after page loads")
assert.include(await frame.textContent("h2"), "Destination: #refresh-morph")
await expect(input).toHaveValue("hello")
assert.equal(await frame.count("#input-in-morph"), 1)

await input.press("Enter")
await nextEventOnTarget(page, "refresh-morph", "turbo:frame-render")

assert.ok(await locatorHasFocus(input), "restores focus after page loads")
assert.include(await frame.textContent("h2"), "Source: #refresh-morph")
await expect(input).toHaveValue("hello")
assert.equal(await frame.count("#input-in-morph"), 1)
})

test("form submissions from frames clear snapshot cache", async ({ page }) => {
await page.evaluate(() => {
document.querySelector("h1").textContent = "Changed"
Expand Down
6 changes: 5 additions & 1 deletion src/tests/helpers/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,11 @@ export function searchParams(url) {
}

export function selectorHasFocus(page, selector) {
return page.locator(selector).evaluate((element) => element === document.activeElement)
return locatorHasFocus(page.locator(selector))
}

export function locatorHasFocus(locator) {
return locator.evaluate((element) => element === document.activeElement)
}

export function setLocalStorageFromEvent(page, eventName, storageKey, storageValue) {
Expand Down
7 changes: 4 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1865,9 +1865,10 @@ [email protected]:
dependencies:
safer-buffer ">= 2.1.2 < 3"

"idiomorph@https://github.com/basecamp/idiomorph#rollout-build":
version "0.0.8"
resolved "https://github.com/basecamp/idiomorph#e906820368e4c9c52489a3336b8c3826b1bf6de5"
idiomorph@^0.0.9:
version "0.0.9"
resolved "https://registry.yarnpkg.com/idiomorph/-/idiomorph-0.0.9.tgz#938d5964031381b0713398fb283aa3754306fa1b"
integrity sha512-X7SGsldE5jQD+peLjNLAnIJDEZtGpuLrNRUBrTWMMnzrx9gwy5U+SCRhaifO2v2Z+8j09IY2J+EYaxHsOLTD0A==

ieee754@^1.1.13:
version "1.2.1"
Expand Down

0 comments on commit 2fd95cf

Please sign in to comment.