Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract Morph class, then use it in FrameRenderer #1029

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
"publishConfig": {
"access": "public"
},
"dependencies": {
"idiomorph": "^0.0.9"
},
"devDependencies": {
"@open-wc/testing": "^3.1.7",
"@playwright/test": "^1.28.0",
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
15 changes: 15 additions & 0 deletions src/core/drive/limited_set.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export class LimitedSet extends Set {
constructor(maxSize) {
super()
this.maxSize = maxSize
}

add(value) {
if (this.size >= this.maxSize) {
const iterator = this.values()
const oldestValue = iterator.next().value
this.delete(oldestValue)
}
super.add(value)
}
}
20 changes: 20 additions & 0 deletions src/core/drive/morph_renderer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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) this.renderElement(this.currentElement, this.newElement)
}

get renderMethod() {
return "morph"
}
}
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
8 changes: 8 additions & 0 deletions src/core/drive/page_snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ export class PageSnapshot extends Snapshot {
return this.headSnapshot.getMetaValue("view-transition") === "same-origin"
}

get shouldMorphPage() {
return this.getSetting("refresh-method") === "morph"
}

get shouldPreserveScrollPosition() {
return this.getSetting("refresh-scroll") === "preserve"
}

// Private

getSetting(name) {
Expand Down
12 changes: 10 additions & 2 deletions src/core/drive/page_view.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { nextEventLoopTick } from "../../util"
import { View } from "../view"
import { ErrorRenderer } from "./error_renderer"
import { MorphRenderer } from "./morph_renderer"
import { PageRenderer } from "./page_renderer"
import { PageSnapshot } from "./page_snapshot"
import { SnapshotCache } from "./snapshot_cache"
Expand All @@ -15,7 +16,10 @@ export class PageView extends View {
}

renderPage(snapshot, isPreview = false, willRender = true, visit) {
const renderer = new PageRenderer(this.snapshot, snapshot, PageRenderer.renderElement, isPreview, willRender)
const shouldMorphPage = this.isPageRefresh(visit) && this.snapshot.shouldMorphPage
const rendererClass = shouldMorphPage ? MorphRenderer : PageRenderer

const renderer = new rendererClass(this.snapshot, snapshot, isPreview, willRender)

if (!renderer.shouldRender) {
this.forceReloaded = true
Expand All @@ -28,7 +32,7 @@ export class PageView extends View {

renderError(snapshot, visit) {
visit?.changeHistory()
const renderer = new ErrorRenderer(this.snapshot, snapshot, ErrorRenderer.renderElement, false)
const renderer = new ErrorRenderer(this.snapshot, snapshot, false)
return this.render(renderer)
}

Expand All @@ -55,6 +59,10 @@ export class PageView extends View {
return this.snapshotCache.get(location)
}

isPageRefresh(visit) {
return visit && this.lastRenderedLocation.href === visit.location.href
}

get snapshot() {
return PageSnapshot.fromElement(this.element)
}
Expand Down
18 changes: 9 additions & 9 deletions src/core/drive/visit.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,10 @@ export class Visit {
}
}

issueRequest() {
async issueRequest() {
if (this.hasPreloadedResponse()) {
this.simulateRequest()
} else if (this.shouldIssueRequest() && !this.request) {
} else if (!this.request && await this.shouldIssueRequest()) {
this.request = new FetchRequest(this, FetchMethod.get, this.location)
this.request.perform()
}
Expand Down Expand Up @@ -231,14 +231,14 @@ export class Visit {
}
}

hasCachedSnapshot() {
return this.getCachedSnapshot() != null
async hasCachedSnapshot() {
return (await this.getCachedSnapshot()) != null
}

async loadCachedSnapshot() {
const snapshot = await this.getCachedSnapshot()
if (snapshot) {
const isPreview = this.shouldIssueRequest()
const isPreview = await this.shouldIssueRequest()
this.render(async () => {
this.cacheSnapshot()
if (this.isSamePage) {
Expand Down Expand Up @@ -335,7 +335,7 @@ export class Visit {
// Scrolling

performScroll() {
if (!this.scrolled && !this.view.forceReloaded) {
if (!this.scrolled && !this.view.forceReloaded && !this.view.snapshot.shouldPreserveScrollPosition) {
if (this.action == "restore") {
this.scrollToRestoredPosition() || this.scrollToAnchor() || this.view.scrollToTop()
} else {
Expand Down Expand Up @@ -391,11 +391,11 @@ export class Visit {
return typeof this.response == "object"
}

shouldIssueRequest() {
async shouldIssueRequest() {
if (this.isSamePage) {
return false
} else if (this.action == "restore") {
return !this.hasCachedSnapshot()
} else if (this.action === "restore") {
return !(await this.hasCachedSnapshot())
} else {
return this.willRender
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/frames/frame_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export class FrameController {
return !defaultPrevented
}

viewRenderedSnapshot(_snapshot, _isPreview) {}
viewRenderedSnapshot(_snapshot, _isPreview, _renderMethod) {}

preloadOnLoadLinksForView(element) {
session.preloadOnLoadLinksForView(element)
Expand Down Expand Up @@ -307,7 +307,7 @@ export class FrameController {

if (newFrameElement) {
const snapshot = new Snapshot(newFrameElement)
const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, FrameRenderer.renderElement, false, false)
const renderer = new FrameRenderer(this, this.view.snapshot, snapshot, false, false)
if (this.view.renderPromise) await this.view.renderPromise
this.changeHistory()

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
4 changes: 3 additions & 1 deletion src/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import { PageRenderer } from "./drive/page_renderer"
import { PageSnapshot } from "./drive/page_snapshot"
import { FrameRenderer } from "./frames/frame_renderer"
import { FormSubmission } from "./drive/form_submission"
import { LimitedSet } from "./drive/limited_set"

const session = new Session()
const cache = new Cache(session)
const recentRequests = new LimitedSet(20)
const { navigator } = session
export { navigator, session, cache, PageRenderer, PageSnapshot, FrameRenderer }
export { navigator, session, cache, recentRequests, PageRenderer, PageSnapshot, FrameRenderer }

export { StreamActions } from "./streams/stream_actions"

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,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ignoreActiveValue: option was introduced in 0.0.9, and feels important enough to include as a default for the sake of focus preservation and to minimize disruptions to the element with focus.

Progressing this branch forward hinges on bigskysoftware/idiomorph#12 being merged. Without it, the package needs to depend on window.Idiomorph.

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)
}
}
6 changes: 1 addition & 5 deletions src/core/native/browser_adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ export class BrowserAdapter {

visitRequestStarted(visit) {
this.progressBar.setValue(0)
if (visit.hasCachedSnapshot() || visit.action != "restore") {
this.showVisitProgressBarAfterDelay()
} else {
this.showProgressBar()
}
this.showVisitProgressBarAfterDelay()
}

visitRequestCompleted(visit) {
Expand Down
12 changes: 10 additions & 2 deletions src/core/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ import { Bardo } from "./bardo"
export class Renderer {
#activeElement = null

constructor(currentSnapshot, newSnapshot, renderElement, isPreview, willRender = true) {
static renderElement(currentElement, newElement) {
// Abstract method
}

constructor(currentSnapshot, newSnapshot, isPreview, willRender = true) {
this.currentSnapshot = currentSnapshot
this.newSnapshot = newSnapshot
this.isPreview = isPreview
this.willRender = willRender
this.renderElement = renderElement
this.renderElement = this.constructor.renderElement
this.promise = new Promise((resolve, reject) => (this.resolvingFunctions = { resolve, reject }))
}

Expand Down Expand Up @@ -79,4 +83,8 @@ export class Renderer {
get permanentElementMap() {
return this.currentSnapshot.getPermanentElementMapForSnapshot(this.newSnapshot)
}

get renderMethod() {
return "replace"
}
}
8 changes: 4 additions & 4 deletions src/core/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,9 @@ export class Session {
return !defaultPrevented
}

viewRenderedSnapshot(_snapshot, isPreview) {
viewRenderedSnapshot(_snapshot, isPreview, renderMethod) {
this.view.lastRenderedLocation = this.history.location
this.notifyApplicationAfterRender(isPreview)
this.notifyApplicationAfterRender(isPreview, renderMethod)
}

preloadOnLoadLinksForView(element) {
Expand Down Expand Up @@ -328,8 +328,8 @@ export class Session {
})
}

notifyApplicationAfterRender(isPreview) {
return dispatch("turbo:render", { detail: { isPreview } })
notifyApplicationAfterRender(isPreview, renderMethod) {
return dispatch("turbo:render", { detail: { isPreview, renderMethod } })
}

notifyApplicationAfterPageLoad(timing = {}) {
Expand Down
9 changes: 9 additions & 0 deletions src/core/streams/stream_actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@ export const StreamActions = {
targetElement.innerHTML = ""
targetElement.append(this.templateContent)
})
},

refresh() {
const requestId = this.getAttribute("request-id")
const isRecentRequest = requestId && window.Turbo.recentRequests.has(requestId)
if (!isRecentRequest) {
window.Turbo.cache.exemptPageFromPreview()
window.Turbo.visit(window.location.href, { action: "replace" })
}
}
}
Loading
Loading