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

Expand rendering capabilities of <turbo-frame> #146

Closed
wants to merge 3 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
4 changes: 3 additions & 1 deletion src/core/drive/form_submission.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { FetchRequest, FetchMethod, fetchMethodFromString, FetchRequestHeaders } from "../../http/fetch_request"
import { FetchResponse } from "../../http/fetch_response"
import { expandURL } from "../url"
import { dispatch } from "../../util"
import { clearBusyState, dispatch, markAsBusy } from "../../util"
import { StreamMessage } from "../streams/stream_message"

export interface FormSubmissionDelegate {
Expand Down Expand Up @@ -146,6 +146,7 @@ export class FormSubmission {

requestStarted(request: FetchRequest) {
this.state = FormSubmissionState.waiting
markAsBusy(this.formElement)
this.submitter?.setAttribute("disabled", "")
dispatch("turbo:submit-start", { target: this.formElement, detail: { formSubmission: this } })
this.delegate.formSubmissionStarted(this)
Expand Down Expand Up @@ -181,6 +182,7 @@ export class FormSubmission {
requestFinished(request: FetchRequest) {
this.state = FormSubmissionState.stopped
this.submitter?.removeAttribute("disabled")
clearBusyState(this.formElement)
dispatch("turbo:submit-end", { target: this.formElement, detail: { formSubmission: this, ...this.result }})
this.delegate.formSubmissionFinished(this)
}
Expand Down
11 changes: 4 additions & 7 deletions src/core/drive/navigator.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Action, isAction } from "../types"
import { Action } from "../types"
import { FetchMethod } from "../../http/fetch_request"
import { FetchResponse } from "../../http/fetch_response"
import { FormSubmission } from "./form_submission"
import { expandURL, getAnchor, getRequestURL, Locatable, locationIsVisitable } from "../url"
import { getAttribute } from "../../util"
import { Visit, VisitDelegate, VisitOptions } from "./visit"
import { Visit, VisitDelegate, VisitOptions, getVisitAction } from "./visit"
import { PageSnapshot } from "./page_snapshot"

export type NavigatorDelegate = VisitDelegate & {
Expand Down Expand Up @@ -157,9 +156,7 @@ export class Navigator {
return this.history.restorationIdentifier
}

getActionForFormSubmission(formSubmission: FormSubmission): Action {
const { formElement, submitter } = formSubmission
const action = getAttribute("data-turbo-action", submitter, formElement)
return isAction(action) ? action : "advance"
getActionForFormSubmission({ formElement, submitter }: FormSubmission): Action {
return getVisitAction(submitter, formElement) || "advance"
}
}
7 changes: 7 additions & 0 deletions src/core/drive/page_renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ import { Renderer } from "../renderer"
import { PageSnapshot } from "./page_snapshot"

export class PageRenderer extends Renderer<HTMLBodyElement, PageSnapshot> {
private readonly willRender: boolean

constructor(currentSnapshot: PageSnapshot, newSnapshot: PageSnapshot, isPreview: boolean, willRender = true) {
super(currentSnapshot, newSnapshot, isPreview)
this.willRender = willRender
}

get shouldRender() {
return this.newSnapshot.isVisitable && this.trackedElementsAreIdentical
}
Expand Down
10 changes: 8 additions & 2 deletions src/core/drive/visit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { History } from "./history"
import { getAnchor } from "../url"
import { Snapshot } from "../snapshot"
import { PageSnapshot } from "./page_snapshot"
import { Action } from "../types"
import { uuid } from "../../util"
import { Action, isAction } from "../types"
import { getAttribute, uuid } from "../../util"
import { PageView } from "./page_view"

export interface VisitDelegate {
Expand Down Expand Up @@ -419,6 +419,12 @@ export class Visit implements FetchRequestDelegate {
}
}

export function getVisitAction(...elements: (Element|undefined)[]): Action | null {
const action = getAttribute("data-turbo-action", ...elements)

return isAction(action) ? action : null
}

function isSuccessful(statusCode: number) {
return statusCode >= 200 && statusCode < 300
}
199 changes: 73 additions & 126 deletions src/core/frames/frame_controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { FrameElement, FrameElementDelegate, FrameLoadingStyle } from "../../elements/frame_element"
import { FetchMethod, FetchRequest, FetchRequestDelegate, FetchRequestHeaders } from "../../http/fetch_request"
import { FrameVisit, FrameVisitDelegate, FrameVisitOptions } from "./frame_visit"
import { FetchResponse } from "../../http/fetch_response"
import { AppearanceObserver, AppearanceObserverDelegate } from "../../observers/appearance_observer"
import { clearBusyState, getAttribute, parseHTMLDocument, markAsBusy } from "../../util"
import { FormSubmission, FormSubmissionDelegate } from "../drive/form_submission"
import { Snapshot } from "../snapshot"
import { ViewDelegate } from "../view"
import { getAction, expandURL, urlsAreEqual, locationIsVisitable } from "../url"
Expand All @@ -12,19 +11,17 @@ import { FrameView } from "./frame_view"
import { LinkInterceptor, LinkInterceptorDelegate } from "./link_interceptor"
import { FrameRenderer } from "./frame_renderer"
import { session } from "../index"
import { isAction } from "../types"
import { Action } from "../types"
import { StreamAction } from "../streams/stream_actions"

export class FrameController implements AppearanceObserverDelegate, FetchRequestDelegate, FormInterceptorDelegate, FormSubmissionDelegate, FrameElementDelegate, LinkInterceptorDelegate, ViewDelegate<Snapshot<FrameElement>> {
export class FrameController implements AppearanceObserverDelegate, FormInterceptorDelegate, FrameElementDelegate, FrameVisitDelegate, LinkInterceptorDelegate, ViewDelegate<Snapshot<FrameElement>> {
readonly element: FrameElement
readonly view: FrameView
readonly appearanceObserver: AppearanceObserver
readonly linkInterceptor: LinkInterceptor
readonly formInterceptor: FormInterceptor
currentURL?: string | null
formSubmission?: FormSubmission
fetchResponseLoaded = (fetchResponse: FetchResponse) => {}
private currentFetchRequest: FetchRequest | null = null
private resolveVisitPromise = () => {}
frameVisit?: FrameVisit
private connected = false
private hasBeenLoaded = false
private settingSourceURL = false
Expand Down Expand Up @@ -61,13 +58,13 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest

disabledChanged() {
if (this.loadingStyle == FrameLoadingStyle.eager) {
this.loadSourceURL()
this.visit({ url: this.sourceURL })
}
}

sourceURLChanged() {
if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {
this.loadSourceURL()
this.visit({ url: this.sourceURL })
}
}

Expand All @@ -76,29 +73,65 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
this.appearanceObserver.start()
} else {
this.appearanceObserver.stop()
this.loadSourceURL()
this.visit({ url: this.sourceURL })
}
}

async loadSourceURL() {
if (!this.settingSourceURL && this.enabled && this.isActive && (this.reloadable || this.sourceURL != this.currentURL)) {
const previousURL = this.currentURL
this.currentURL = this.sourceURL
if (this.sourceURL) {
try {
this.element.loaded = this.visit(expandURL(this.sourceURL))
this.appearanceObserver.stop()
await this.element.loaded
this.hasBeenLoaded = true
} catch (error) {
this.currentURL = previousURL
throw error
}
}
visit(options: Partial<FrameVisitOptions> = {}) {
const frameVisit = new FrameVisit(this, this.element, options)
frameVisit.start()
}

submit(options: Partial<FrameVisitOptions> = {}) {
const { submit } = options

if (submit) {
const frameVisit = new FrameVisit(this, this.element, options)
frameVisit.start()
}
}

// Frame visit delegate

shouldVisit({ isFormSubmission }: FrameVisit) {
return !this.settingSourceURL && this.enabled && this.isActive && (this.reloadable || (this.sourceURL != this.currentURL || isFormSubmission))
}

visitStarted(frameVisit: FrameVisit) {
this.frameVisit?.stop()
this.frameVisit = frameVisit

if (frameVisit.options.url) {
this.currentURL = frameVisit.options.url
}

this.appearanceObserver.stop()
markAsBusy(this.element)
}

async visitSucceeded({ action, rendering }: FrameVisit, response: FetchResponse) {
await this.loadResponse(response, action, rendering)
}

async visitFailed({ action, rendering }: FrameVisit, response: FetchResponse) {
await this.loadResponse(response, action, rendering)
}

async loadResponse(fetchResponse: FetchResponse) {
visitErrored(frameVisit: FrameVisit, error: Error) {
console.error(error)
this.currentURL = frameVisit.previousURL
this.view.invalidate()
throw error
}

visitCompleted(frameVisit: FrameVisit) {
clearBusyState(this.element)
this.hasBeenLoaded = true
}

async loadResponse(fetchResponse: FetchResponse, action: Action | null, rendering: StreamAction) {
const fetchResponseLoaded = this.proposeVisitIfNavigatedWithAction(this.element, action)

if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {
this.sourceURL = fetchResponse.response.url
}
Expand All @@ -108,25 +141,23 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
if (html) {
const { body } = parseHTMLDocument(html)
const snapshot = new Snapshot(await this.extractForeignFrameElement(body))
const renderer = new FrameRenderer(this.view.snapshot, snapshot, false, false)
const renderer = new FrameRenderer(this.view.snapshot, snapshot, false, rendering)
if (this.view.renderPromise) await this.view.renderPromise
await this.view.render(renderer)
session.frameRendered(fetchResponse, this.element)
session.frameLoaded(this.element)
this.fetchResponseLoaded(fetchResponse)
fetchResponseLoaded(fetchResponse)
}
} catch (error) {
console.error(error)
this.view.invalidate()
} finally {
this.fetchResponseLoaded = () => {}
}
}

// Appearance observer delegate

elementAppearedInViewport(element: Element) {
this.loadSourceURL()
this.visit({ url: this.sourceURL })
}

// Link interceptor delegate
Expand All @@ -151,74 +182,9 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
}

formSubmissionIntercepted(element: HTMLFormElement, submitter?: HTMLElement) {
if (this.formSubmission) {
this.formSubmission.stop()
}

this.reloadable = false
this.formSubmission = new FormSubmission(this, element, submitter)
const { fetchRequest } = this.formSubmission
this.prepareHeadersForRequest(fetchRequest.headers, fetchRequest)
this.formSubmission.start()
}

// Fetch request delegate

prepareHeadersForRequest(headers: FetchRequestHeaders, request: FetchRequest) {
headers["Turbo-Frame"] = this.id
}

requestStarted(request: FetchRequest) {
markAsBusy(this.element)
}

requestPreventedHandlingResponse(request: FetchRequest, response: FetchResponse) {
this.resolveVisitPromise()
}

async requestSucceededWithResponse(request: FetchRequest, response: FetchResponse) {
await this.loadResponse(response)
this.resolveVisitPromise()
}

requestFailedWithResponse(request: FetchRequest, response: FetchResponse) {
console.error(response)
this.resolveVisitPromise()
}

requestErrored(request: FetchRequest, error: Error) {
console.error(error)
this.resolveVisitPromise()
}

requestFinished(request: FetchRequest) {
clearBusyState(this.element)
}

// Form submission delegate

formSubmissionStarted({ formElement }: FormSubmission) {
markAsBusy(formElement, this.findFrameElement(formElement))
}

formSubmissionSucceededWithResponse(formSubmission: FormSubmission, response: FetchResponse) {
const frame = this.findFrameElement(formSubmission.formElement, formSubmission.submitter)

this.proposeVisitIfNavigatedWithAction(frame, formSubmission.formElement, formSubmission.submitter)

frame.delegate.loadResponse(response)
}

formSubmissionFailedWithResponse(formSubmission: FormSubmission, fetchResponse: FetchResponse) {
this.element.delegate.loadResponse(fetchResponse)
}

formSubmissionErrored(formSubmission: FormSubmission, error: Error) {
console.error(error)
}

formSubmissionFinished({ formElement }: FormSubmission) {
clearBusyState(formElement, this.findFrameElement(formElement))
const frame = this.findFrameElement(element, submitter)
frame.removeAttribute("reloadable")
frame.delegate.submit(FrameVisit.optionsForSubmit(element, submitter))
}

// View delegate
Expand All @@ -235,37 +201,16 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest

// Private

private async visit(url: URL) {
const request = new FetchRequest(this, FetchMethod.get, url, new URLSearchParams, this.element)

this.currentFetchRequest?.cancel()
this.currentFetchRequest = request

return new Promise<void>(resolve => {
this.resolveVisitPromise = () => {
this.resolveVisitPromise = () => {}
this.currentFetchRequest = null
resolve()
}
request.perform()
})
}

private navigateFrame(element: Element, url: string, submitter?: HTMLElement) {
const frame = this.findFrameElement(element, submitter)

this.proposeVisitIfNavigatedWithAction(frame, element, submitter)

frame.setAttribute("reloadable", "")
frame.src = url
frame.delegate.visit(FrameVisit.optionsForClick(element, url))
}

private proposeVisitIfNavigatedWithAction(frame: FrameElement, element: Element, submitter?: HTMLElement) {
const action = getAttribute("data-turbo-action", submitter, element, frame)

if (isAction(action)) {
private proposeVisitIfNavigatedWithAction(frame: FrameElement, action: Action | null): (fetchResponse: FetchResponse) => void {
if (action) {
const { visitCachedSnapshot } = new SnapshotSubstitution(frame)
frame.delegate.fetchResponseLoaded = (fetchResponse: FetchResponse) => {
return (fetchResponse: FetchResponse) => {
if (frame.src) {
const { statusCode, redirected } = fetchResponse
const responseHTML = frame.ownerDocument.documentElement.outerHTML
Expand All @@ -274,6 +219,8 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
session.visit(frame.src, { action, response, visitCachedSnapshot, willRender: false })
}
}
} else {
return () => {}
}
}

Expand Down Expand Up @@ -381,7 +328,7 @@ export class FrameController implements AppearanceObserverDelegate, FetchRequest
}

get isLoading() {
return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined
return this.frameVisit !== undefined
}

get isActive() {
Expand Down
Loading