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

Mix in Turbo Frames to built-in elements. #131

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
Binary file added .DS_Store
Binary file not shown.
20 changes: 12 additions & 8 deletions src/core/frames/frame_controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FrameElement, FrameElementDelegate, FrameLoadingStyle } from "../../elements/frame_element"
import { FrameElement, FrameElementDelegate, FrameLoadingStyle, isTurboFrameElement } from "../../elements/frame_element"
import { FetchMethod, FetchRequest, FetchRequestDelegate, FetchRequestHeaders } from "../../http/fetch_request"
import { FetchResponse } from "../../http/fetch_response"
import { AppearanceObserver, AppearanceObserverDelegate } from "../../observers/appearance_observer"
Expand Down Expand Up @@ -261,21 +261,21 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
const id = CSS.escape(this.id)

try {
if (element = activateElement(container.querySelector(`turbo-frame#${id}`), this.currentURL)) {
if (element = activateElement(container.querySelector(`${this.element.selector}#${id}`), this.currentURL)) {
return element
}

if (element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.currentURL)) {
if (element = activateElement(container.querySelector(`${this.element.selector}[src][recurse~=${id}]`), this.currentURL)) {
await element.loaded
return await this.extractForeignFrameElement(element)
}

console.error(`Response has no matching <turbo-frame id="${id}"> element`)
console.error(`Response has no element matching ${this.element.selector}#${id}`)
} catch (error) {
console.error(error)
}

return new FrameElement()
return new this.elementConstructor()
}

private shouldInterceptNavigation(element: Element, submitter?: Element) {
Expand Down Expand Up @@ -303,6 +303,10 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
return true
}

private get elementConstructor() {
return Object.getPrototypeOf(this.element).constructor
}

// Computed properties

get id() {
Expand Down Expand Up @@ -356,7 +360,7 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
function getFrameElementById(id: string | null) {
if (id != null) {
const element = document.getElementById(id)
if (element instanceof FrameElement) {
if (isTurboFrameElement(element)) {
return element
}
}
Expand All @@ -366,13 +370,13 @@ function activateElement(element: Element | null, currentURL?: string | null) {
if (element) {
const src = element.getAttribute("src")
if (src != null && currentURL != null && urlsAreEqual(src, currentURL)) {
throw new Error(`Matching <turbo-frame id="${element.id}"> element has a source URL which references itself`)
throw new Error(`Matching <${element.tagName.toLowerCase()} id="${element.id}"> element has a source URL which references itself`)
}
if (element.ownerDocument !== document) {
element = document.importNode(element, true)
}

if (element instanceof FrameElement) {
if (isTurboFrameElement(element)) {
element.connectedCallback()
return element
}
Expand Down
6 changes: 3 additions & 3 deletions src/core/frames/frame_redirector.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FormInterceptor, FormInterceptorDelegate } from "./form_interceptor"
import { FrameElement } from "../../elements/frame_element"
import { isTurboFrameElement } from "../../elements/frame_element"
import { LinkInterceptor, LinkInterceptorDelegate } from "./link_interceptor"

export class FrameRedirector implements LinkInterceptorDelegate, FormInterceptorDelegate {
Expand Down Expand Up @@ -49,14 +49,14 @@ export class FrameRedirector implements LinkInterceptorDelegate, FormInterceptor

private shouldRedirect(element: Element, submitter?: HTMLElement) {
const frame = this.findFrameElement(element, submitter)
return frame ? frame != element.closest("turbo-frame") : false
return frame ? frame != element.closest(`turbo-frame, [is^="turbo-frame-"]`) : false
inopinatus marked this conversation as resolved.
Show resolved Hide resolved
}

private findFrameElement(element: Element, submitter?: HTMLElement) {
const id = submitter?.getAttribute("data-turbo-frame") || element.getAttribute("data-turbo-frame")
if (id && id != "_top") {
const frame = this.element.querySelector(`#${id}:not([disabled])`)
if (frame instanceof FrameElement) {
if (isTurboFrameElement(frame)) {
return frame
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/frames/link_interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,6 @@ export class LinkInterceptor {
: target instanceof Node
? target.parentElement
: null
return element && element.closest("turbo-frame, html") == this.element
return element && element.closest(`turbo-frame, [is^="turbo-frame-"], html`) == this.element
}
}
4 changes: 4 additions & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,7 @@ export function setProgressBarDelay(delay: number) {
export function setConfirmMethod(confirmMethod: (message: string, element: HTMLFormElement)=>boolean) {
FormSubmission.confirmMethod = confirmMethod
}

export function defineCustomFrameElement(name: string) {
session.defineCustomFrameElement(name)
}
5 changes: 5 additions & 0 deletions src/core/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BrowserAdapter } from "./native/browser_adapter"
import { CacheObserver } from "../observers/cache_observer"
import { FormSubmitObserver, FormSubmitObserverDelegate } from "../observers/form_submit_observer"
import { FrameRedirector } from "./frames/frame_redirector"
import { defineCustomFrameElement } from "../elements"
import { History, HistoryDelegate } from "./drive/history"
import { LinkClickObserver, LinkClickObserverDelegate } from "../observers/link_click_observer"
import { expandURL, locationIsVisitable, Locatable } from "./url"
Expand Down Expand Up @@ -102,6 +103,10 @@ export class Session implements FormSubmitObserverDelegate, HistoryDelegate, Lin
this.progressBarDelay = delay
}

defineCustomFrameElement(name: string) {
defineCustomFrameElement(name)
}

get location() {
return this.history.location
}
Expand Down
15 changes: 15 additions & 0 deletions src/elements/custom_frame_element.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { builtinTurboFrameElement } from "./frame_element"

export function defineCustomFrameElement(name: string) {
customElements.define(`turbo-frame-${name}`, builtinTurboFrameElement(name), { extends: name })
}

defineCustomFrameElement("div")
Copy link
Contributor

@seanpdoyle seanpdoyle Oct 19, 2021

Choose a reason for hiding this comment

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

Maybe I'm misunderstanding the motivations behind pre-defining "main default container elements", but what is the value in supporting a generic element like <div is="turbo-frame-div"> instead of using a <turbo-frame> in its place?

Is this about semantics? Would <turbo-frame role="region"> be compatible with <section is="turbo-frame-section">?

As I understood the initial version of this PR, it was to add support for <turbo-frame> elements within a <table> element only because browsers hoist <table> elements in a specialized way compared to other elements. Would it be best to keep this pre-definitions constrained to table elements like <thead>, <tbody>, <tr>, <td>, <th>?

Copy link
Member

Choose a reason for hiding this comment

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

Often it's about integration into existing setups that have set expectations about DOM structure. Like right now I'm dealing with a sortable setup in Basecamp where we're converting some div's to turbo frames, but the existing JS expects a certain DOM structure that doesn't work with an additional container inserted.

It's similar to the stimulus approach vs custom elements in general.

defineCustomFrameElement("article")
defineCustomFrameElement("tbody")
defineCustomFrameElement("header")
defineCustomFrameElement("footer")
defineCustomFrameElement("section")
defineCustomFrameElement("aside")
defineCustomFrameElement("main")
defineCustomFrameElement("nav")
84 changes: 59 additions & 25 deletions src/elements/frame_element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@ import { FetchResponse } from "../http/fetch_response"

export enum FrameLoadingStyle { eager = "eager", lazy = "lazy" }

export interface FrameElement extends HTMLElement {
isTurboFrameElement: boolean
selector: string
delegate: FrameElementDelegate
loaded: Promise<FetchResponse | void>
src: string | null
disabled: boolean
loading: string
isActive: boolean
autoscroll: boolean
connectedCallback(): void
disconnectedCallback(): void
attributeChangedCallback(name: string): void
}

export namespace FrameElement {
export let delegateConstructor: new (element: FrameElement) => FrameElementDelegate
}

export interface FrameElementDelegate {
connect(): void
disconnect(): void
Expand All @@ -13,25 +32,9 @@ export interface FrameElementDelegate {
isLoading: boolean
}

/**
* Contains a fragment of HTML which is updated based on navigation within
* it (e.g. via links or form submissions).
*
* @customElement turbo-frame
* @example
* <turbo-frame id="messages">
* <a href="/messages/expanded">
* Show all expanded messages in this frame.
* </a>
*
* <form action="/messages">
* Show response from this form within this frame.
* </form>
* </turbo-frame>
*/
export class FrameElement extends HTMLElement {
static delegateConstructor: new (element: FrameElement) => FrameElementDelegate

export function frameElementFactory(Base: new() => HTMLElement) {
return class extends Base implements FrameElement {
readonly isTurboFrameElement: boolean = true
loaded: Promise<FetchResponse | void> = Promise.resolve()
readonly delegate: FrameElementDelegate

Expand All @@ -41,6 +44,9 @@ export class FrameElement extends HTMLElement {

constructor() {
super()
if (!this.autonomous) {
this.setAttribute("is", this.isValue)
Copy link

@WebReflection WebReflection Mar 15, 2022

Choose a reason for hiding this comment

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

the is attribute is used by custom elements builtin extends ... if this property overrides the attribute no polyfill can possibly upgrade this element later on. Please avoid setting this attribute completely, use a different name for custom elements builtin extends, or set such attribute only if this.getAttribute('is') is not defined yet.

Copy link
Author

Choose a reason for hiding this comment

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

That is intentional, and necessary when the element is programatically created, due to this part of that same section of the HTML standard: "when creating a customized built-in element programmatically, the is attribute will not be present in the DOM, since it was not explicitly set".

To implement its own behaviour, Turbo usually depends on the element name. Since that is no longer possible in this case, it must instead depend instead on the is attribute being present in the DOM, to identify the element for update. Setting any other attribute would be a) DOM pollution, and b) a potential namespace clash. Using any other means would break the general design promise of progressively enhancing the HTML we already have, and amount to a redesign of Turbo's core behaviour which is definitely out of scope for this PR.

However I agree that it only needs setting if not already defined.

I hope to revisit this PR sometime this month, maybe with the revised polyfill it can even work on Safari, thanks!

Choose a reason for hiding this comment

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

Using CE since 2014 and wrote all polyfills to date that work with built-in extends too, no need to explain me what's the is attribute about ;-) and yes, I do that in vanilla-elements too, but the reason I've mentioned that is that the polyfill also does that so you don't need to care.

Anyway, a simple check if the attribute is not defined yet is all I am pointing out, and shame on me I didn't check what was the isValue value, but if it's the custom element name, as builtin extend, then all good, this shouldn't interfere with the polyfill, I thought it was something else, like Vue 3 abuse it.

Apparently it's not 👍

}
this.delegate = new FrameElement.delegateConstructor(this)
}

Expand All @@ -52,12 +58,6 @@ export class FrameElement extends HTMLElement {
this.delegate.disconnect()
}

reload() {
const { src } = this;
this.src = null;
this.src = src;
}

attributeChangedCallback(name: string) {
if (name == "loading") {
this.delegate.loadingStyleChanged()
Expand All @@ -68,6 +68,28 @@ export class FrameElement extends HTMLElement {
}
}

reload() {
const { src } = this;
this.src = null;
this.src = src;
}

get selector(): string {
if (this.autonomous) {
return this.localName
} else {
return `${this.localName}[is="${this.isValue}"]`
}
}

get isValue(): string {
return `turbo-frame-${this.localName}`
}

get autonomous(): boolean {
return Base === HTMLElement
}

/**
* Gets the URL to lazily load source HTML from
*/
Expand Down Expand Up @@ -173,10 +195,22 @@ export class FrameElement extends HTMLElement {
return this.ownerDocument?.documentElement?.hasAttribute("data-turbo-preview")
}
}
}

function frameLoadingStyleFromString(style: string) {
switch (style.toLowerCase()) {
case "lazy": return FrameLoadingStyle.lazy
default: return FrameLoadingStyle.eager
}
}

export function builtinTurboFrameElement(name: string) {
const baseElementConstructor = Object.getPrototypeOf(document.createElement(name)).constructor
return frameElementFactory(baseElementConstructor)
}

export function isTurboFrameElement(arg: any): arg is FrameElement {
return arg && arg.isTurboFrameElement && arg instanceof HTMLElement
}

export const TurboFrameElement = frameElementFactory(HTMLElement)
5 changes: 3 additions & 2 deletions src/elements/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { FrameController } from "../core/frames/frame_controller"
import { FrameElement } from "./frame_element"
import { FrameElement, TurboFrameElement } from "./frame_element"
import { StreamElement } from "./stream_element"

FrameElement.delegateConstructor = FrameController

export * from "./frame_element"
export * from "./stream_element"
export * from "./custom_frame_element"

customElements.define("turbo-frame", FrameElement)
customElements.define("turbo-frame", TurboFrameElement)
customElements.define("turbo-stream", StreamElement)
9 changes: 9 additions & 0 deletions src/tests/fixtures/frames.html
Original file line number Diff line number Diff line change
Expand Up @@ -77,5 +77,14 @@ <h2>Frames: #nested-child</h2>
<form data-turbo-frame="frame" method="get" action="/src/tests/fixtures/frames/frame.html">
<input id="outer-frame-submit" type="submit" value="Outer form submit">
</form>

<table>
<thead id="thead0">
<tr><th>table thead0</th></tr>
</thead>
<tbody id="tbody0" is="turbo-frame-tbody">
<tr><td><a href="/src/tests/fixtures/frames/table.html">Set table</a></td></tr>
</tbody>
</table>
</body>
</html>
15 changes: 15 additions & 0 deletions src/tests/fixtures/frames/table.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Frame</title>
<script src="/dist/turbo.es2017-umd.js" data-turbo-track="reload"></script>
</head>
<body>
<table>
<tbody id="tbody0" is="turbo-frame-tbody">
<tr><td>Table service</td></tr>
</tbody>
</table>
</body>
</html>
11 changes: 11 additions & 0 deletions src/tests/functional/frame_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ export class FrameTests extends TurboDriveTestCase {
this.assert.ok(await this.nextEventOnTarget("frame", "turbo:before-fetch-response"))
}

async "test loading a tbody element"() {
await this.clickSelector("#tbody0 a")
await this.nextBeat

const contentsTd = await this.querySelector("#tbody0 td")
this.assert.equal(await contentsTd.getVisibleText(), "Table service")

const contentsTh = await this.querySelector("#thead0 th")
this.assert.equal(await contentsTh.getVisibleText(), "table thead0")
}

get frameScriptEvaluationCount(): Promise<number | undefined> {
return this.evaluate(() => window.frameScriptEvaluationCount)
}
Expand Down