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 9, 2023
1 parent 2fb0190 commit fae93de
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 81 deletions.
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, "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
53 changes: 53 additions & 0 deletions src/core/morph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Idiomorph from "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") {
Idiomorph.morph(this.currentElement, this.newElement, {
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)
}
}
12 changes: 12 additions & 0 deletions src/tests/functional/rendering_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
nextBody,
nextBodyMutation,
nextEventNamed,
nextEventOnTarget,
noNextBodyMutation,
pathname,
propertyForSelector,
Expand Down Expand Up @@ -440,6 +441,17 @@ test("test restores focus during turbo-frame rendering when transposing the acti
assert.ok(await selectorHasFocus(page, "#permanent-input-in-frame"), "restores focus after page loads")
})

test("test restores focus during turbo-frame morphing when transposing the activeElement", async ({ page }) => {
const input = await page.locator("#permanent-input-in-frame")
const frame = await page.locator("turbo-frame#hello")

await frame.evaluate((frame) => frame.setAttribute("refresh", "morph"))
await input.press("Enter")
await nextEventOnTarget(page, "hello", "turbo:frame-load")

assert.ok(await selectorHasFocus(page, "#permanent-input-in-frame"), "restores focus after page loads")
})

test("test restores focus during turbo-frame rendering when transposing a descendant of the activeElement", async ({
page
}) => {
Expand Down

0 comments on commit fae93de

Please sign in to comment.