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

Add cancelable turbo:frame-click event #788

Closed
wants to merge 2 commits into from
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
18 changes: 15 additions & 3 deletions src/core/frames/frame_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { FrameRenderer } from "./frame_renderer"
import { session } from "../index"
import { isAction, Action } from "../types"
import { VisitOptions } from "../drive/visit"
import { TurboBeforeFrameRenderEvent } from "../session"
import { TurboBeforeFrameRenderEvent, TurboFrameClickEvent } from "../session"
import { StreamMessage } from "../streams/stream_message"
import { PageSnapshot } from "../drive/page_snapshot"

Expand Down Expand Up @@ -215,8 +215,10 @@ export class FrameController

// Link interceptor delegate

shouldInterceptLinkClick(element: Element, _location: string, _event: MouseEvent) {
return this.shouldInterceptNavigation(element)
shouldInterceptLinkClick(element: Element, location: string, event: MouseEvent) {
return (
this.shouldInterceptNavigation(element) && this.frameAllowsVisitingLocation(element, expandURL(location), event)
)
}

linkClickIntercepted(element: Element, location: string) {
Expand Down Expand Up @@ -557,6 +559,16 @@ export class FrameController
return expandURL(root)
}

private frameAllowsVisitingLocation(target: Element, { href: url }: URL, originalEvent: MouseEvent): boolean {
const event = dispatch<TurboFrameClickEvent>("turbo:frame-click", {
target,
detail: { url, originalEvent },
cancelable: true,
})

return !event.defaultPrevented
}

private isIgnoringChangesTo(attributeName: FrameElementObservedAttribute): boolean {
return this.ignoredAttributes.has(attributeName)
}
Expand Down
17 changes: 14 additions & 3 deletions src/core/frames/frame_redirector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { FormSubmitObserver, FormSubmitObserverDelegate } from "../../observers/
import { FrameElement } from "../../elements/frame_element"
import { LinkInterceptor, LinkInterceptorDelegate } from "./link_interceptor"
import { expandURL, getAction, locationIsVisitable } from "../url"
import { Session } from "../session"
import { Session, TurboFrameClickEvent } from "../session"
import { dispatch } from "../../util"
export class FrameRedirector implements LinkInterceptorDelegate, FormSubmitObserverDelegate {
readonly session: Session
readonly element: Element
Expand All @@ -26,8 +27,8 @@ export class FrameRedirector implements LinkInterceptorDelegate, FormSubmitObser
this.formSubmitObserver.stop()
}

shouldInterceptLinkClick(element: Element, _location: string, _event: MouseEvent) {
return this.shouldRedirect(element)
shouldInterceptLinkClick(element: Element, location: string, event: MouseEvent) {
return this.shouldRedirect(element) && this.frameAllowsVisitingLocation(element, expandURL(location), event)
}

linkClickIntercepted(element: Element, url: string, event: MouseEvent) {
Expand All @@ -52,6 +53,16 @@ export class FrameRedirector implements LinkInterceptorDelegate, FormSubmitObser
}
}

private frameAllowsVisitingLocation(target: Element, { href: url }: URL, originalEvent: MouseEvent): boolean {
const event = dispatch<TurboFrameClickEvent>("turbo:frame-click", {
target,
detail: { url, originalEvent },
cancelable: true,
})

return !event.defaultPrevented
}

private shouldSubmit(form: HTMLFormElement, submitter?: HTMLElement) {
const action = getAction(form, submitter)
const meta = this.element.ownerDocument.querySelector<HTMLMetaElement>(`meta[name="turbo-root"]`)
Expand Down
1 change: 1 addition & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export {
TurboBeforeRenderEvent,
TurboBeforeVisitEvent,
TurboClickEvent,
TurboFrameClickEvent,
TurboBeforeFrameRenderEvent,
TurboFrameLoadEvent,
TurboFrameRenderEvent,
Expand Down
1 change: 1 addition & 0 deletions src/core/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export type TurboBeforeCacheEvent = CustomEvent
export type TurboBeforeRenderEvent = CustomEvent<{ newBody: HTMLBodyElement } & PageViewRenderOptions>
export type TurboBeforeVisitEvent = CustomEvent<{ url: string }>
export type TurboClickEvent = CustomEvent<{ url: string; originalEvent: MouseEvent }>
export type TurboFrameClickEvent = CustomEvent<{ url: string; originalEvent: MouseEvent }>
export type TurboFrameLoadEvent = CustomEvent
export type TurboBeforeFrameRenderEvent = CustomEvent<{ newFrame: FrameElement } & FrameViewRenderOptions>
export type TurboFrameRenderEvent = CustomEvent<{ fetchResponse: FetchResponse }>
Expand Down
2 changes: 1 addition & 1 deletion src/tests/fixtures/frames.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html id="html" data-skip-event-details="turbo:click turbo:before-render">
<html id="html" data-skip-event-details="turbo:click turbo:frame-click turbo:before-render">
<head>
<meta charset="utf-8">
<title>Frame</title>
Expand Down
21 changes: 11 additions & 10 deletions src/tests/fixtures/test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
(function(eventNames) {
;(function (eventNames) {
function serializeToChannel(object, visited = new Set()) {
const returned = {}

Expand All @@ -10,7 +10,7 @@
} else if (value instanceof Element) {
returned[key] = value.outerHTML
} else if (typeof value == "object") {
if (visited.has(value)) {
if (visited.has(value)) {
returned[key] = "skipped to prevent infinitely recursing"
} else {
visited.add(value)
Expand Down Expand Up @@ -39,15 +39,16 @@
}
window.mutationLogs = []

new MutationObserver((mutations) => {
for (const { attributeName, target } of mutations.filter(({ type }) => type == "attributes")) {
if (target instanceof Element) {
mutationLogs.push([attributeName, target.id, target.getAttribute(attributeName)])
}
}
}).observe(document, { subtree: true, childList: true, attributes: true })
new MutationObserver((mutations) => {
for (const { attributeName, target } of mutations.filter(({ type }) => type == "attributes")) {
if (target instanceof Element) {
mutationLogs.push([attributeName, target.id, target.getAttribute(attributeName)])
}
}
}).observe(document, { subtree: true, childList: true, attributes: true })
})([
"turbo:click",
"turbo:frame-click",
"turbo:before-stream-render",
"turbo:before-cache",
"turbo:before-render",
Expand All @@ -64,5 +65,5 @@
"turbo:frame-load",
"turbo:frame-render",
"turbo:frame-missing",
"turbo:reload"
"turbo:reload",
])
10 changes: 10 additions & 0 deletions src/tests/functional/frame_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
scrollPosition,
scrollToSelector,
searchParams,
cancelNextEvent,
} from "../helpers/page"

assert.equal = function (actual: any, expected: any, message?: string) {
Expand Down Expand Up @@ -446,6 +447,7 @@ test("test navigating a frame from an outer link fires events", async ({ page })
await page.click("#outside-frame-form")

await nextEventOnTarget(page, "outside-frame-form", "turbo:click")
await nextEventOnTarget(page, "outside-frame-form", "turbo:frame-click")
await nextEventOnTarget(page, "frame", "turbo:before-fetch-request")
await nextEventOnTarget(page, "frame", "turbo:before-fetch-response")
const { fetchResponse } = await nextEventOnTarget(page, "frame", "turbo:frame-render")
Expand All @@ -462,6 +464,7 @@ test("test navigating a frame from an inner link fires events", async ({ page })
await page.click("#link-frame")

await nextEventOnTarget(page, "link-frame", "turbo:click")
await nextEventOnTarget(page, "link-frame", "turbo:frame-click")
await nextEventOnTarget(page, "frame", "turbo:before-fetch-request")
await nextEventOnTarget(page, "frame", "turbo:before-fetch-response")
const { fetchResponse } = await nextEventOnTarget(page, "frame", "turbo:frame-render")
Expand All @@ -488,6 +491,13 @@ test("test navigating a frame targeting _top from an outer link fires events", a
assert.equal(otherEvents.length, 0, "no more events")
})

test("test canceling a turbo:frame-click event falls back to built-in browser navigation", async ({ page }) => {
await cancelNextEvent(page, "turbo:frame-click")
await Promise.all([page.waitForNavigation(), page.click("#link-frame")])

assert.equal(pathname(page.url()), "/src/tests/fixtures/frames/frame.html")
})

test("test invoking .reload() re-fetches the frame's content", async ({ page }) => {
await page.click("#link-frame")
await nextEventOnTarget(page, "frame", "turbo:frame-load")
Expand Down
2 changes: 1 addition & 1 deletion src/tests/helpers/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function attributeForSelector(page: Page, selector: string, attributeName
return page.locator(selector).getAttribute(attributeName)
}

type CancellableEvent = "turbo:click" | "turbo:before-visit"
type CancellableEvent = "turbo:click" | "turbo:before-visit" | "turbo:frame-click"

export function cancelNextEvent(page: Page, eventName: CancellableEvent): Promise<void> {
return page.evaluate(
Expand Down