forked from github/turbo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frame_controller.ts
503 lines (410 loc) · 14.3 KB
/
frame_controller.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import {
FrameElement,
FrameElementDelegate,
FrameLoadingStyle,
FrameElementObservedAttribute,
} 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"
import {
clearBusyState,
getAttribute,
parseHTMLDocument,
markAsBusy,
uuid,
getHistoryMethodForAction,
getVisitAction,
} from "../../util"
import { FormSubmission, FormSubmissionDelegate } from "../drive/form_submission"
import { Snapshot } from "../snapshot"
import { ViewDelegate } from "../view"
import { getAction, expandURL, urlsAreEqual, locationIsVisitable } from "../url"
import { FormInterceptor, FormInterceptorDelegate } from "./form_interceptor"
import { FrameView } from "./frame_view"
import { LinkInterceptor, LinkInterceptorDelegate } from "./link_interceptor"
import { FrameRenderer } from "./frame_renderer"
import { session } from "../index"
import { isAction, Action } from "../types"
import { VisitOptions } from "../drive/visit"
export class FrameController
implements
AppearanceObserverDelegate,
FetchRequestDelegate,
FormInterceptorDelegate,
FormSubmissionDelegate,
FrameElementDelegate,
LinkInterceptorDelegate,
ViewDelegate<Snapshot<FrameElement>>
{
readonly element: FrameElement
readonly view: FrameView
readonly appearanceObserver: AppearanceObserver
readonly linkInterceptor: LinkInterceptor
readonly formInterceptor: FormInterceptor
formSubmission?: FormSubmission
fetchResponseLoaded = (_fetchResponse: FetchResponse) => {}
private currentFetchRequest: FetchRequest | null = null
private resolveVisitPromise = () => {}
private connected = false
private hasBeenLoaded = false
private ignoredAttributes: Set<FrameElementObservedAttribute> = new Set()
private action: Action | null = null
private frame?: FrameElement
private resolveInterceptionPromise = (_value: any) => {}
readonly restorationIdentifier: string
constructor(element: FrameElement) {
this.element = element
this.view = new FrameView(this, this.element)
this.appearanceObserver = new AppearanceObserver(this, this.element)
this.linkInterceptor = new LinkInterceptor(this, this.element)
this.formInterceptor = new FormInterceptor(this, this.element)
this.restorationIdentifier = uuid()
}
connect() {
if (!this.connected) {
this.connected = true
if (this.loadingStyle == FrameLoadingStyle.lazy) {
this.appearanceObserver.start()
} else {
this.loadSourceURL()
}
this.linkInterceptor.start()
this.formInterceptor.start()
}
}
disconnect() {
if (this.connected) {
this.connected = false
this.appearanceObserver.stop()
this.linkInterceptor.stop()
this.formInterceptor.stop()
}
}
disabledChanged() {
if (this.loadingStyle == FrameLoadingStyle.eager) {
this.loadSourceURL()
}
}
sourceURLChanged() {
if (this.isIgnoringChangesTo("src")) return
if (this.element.isConnected) {
this.complete = false
}
if (this.loadingStyle == FrameLoadingStyle.eager || this.hasBeenLoaded) {
this.loadSourceURL()
}
}
completeChanged() {
if (this.isIgnoringChangesTo("complete")) return
this.loadSourceURL()
}
loadingStyleChanged() {
if (this.loadingStyle == FrameLoadingStyle.lazy) {
this.appearanceObserver.start()
} else {
this.appearanceObserver.stop()
this.loadSourceURL()
}
}
private async loadSourceURL() {
if (this.enabled && this.isActive && !this.complete && this.sourceURL) {
this.element.loaded = this.visit(expandURL(this.sourceURL))
this.appearanceObserver.stop()
await this.element.loaded
this.hasBeenLoaded = true
}
}
async loadResponse(fetchResponse: FetchResponse) {
if (fetchResponse.redirected || (fetchResponse.succeeded && fetchResponse.isHTML)) {
this.sourceURL = fetchResponse.response.url
}
try {
const html = await fetchResponse.responseHTML
if (html) {
const { body } = parseHTMLDocument(html)
const snapshot = new Snapshot(await this.extractForeignFrameElement(body))
const renderer = new FrameRenderer(this.view.snapshot, snapshot, false, false)
if (this.view.renderPromise) await this.view.renderPromise
this.changeHistory()
const renderInterception = new Promise((resolve) => (this.resolveInterceptionPromise = resolve))
const immediateRender = session.frameWillRender(fetchResponse, this.element, this.resolveInterceptionPromise)
if (!immediateRender) await renderInterception
await this.view.render(renderer)
this.complete = true
session.frameRendered(fetchResponse, this.element)
session.frameLoaded(this.element)
this.fetchResponseLoaded(fetchResponse)
}
} catch (error) {
console.error(error)
this.view.invalidate()
} finally {
this.fetchResponseLoaded = () => {}
}
}
// Appearance observer delegate
elementAppearedInViewport(_element: Element) {
this.loadSourceURL()
}
// Link interceptor delegate
shouldInterceptLinkClick(element: Element, _url: string) {
if (element.hasAttribute("data-turbo-method")) {
return false
} else {
return this.shouldInterceptNavigation(element)
}
}
linkClickIntercepted(element: Element, url: string) {
this.navigateFrame(element, url)
}
// Form interceptor delegate
shouldInterceptFormSubmission(element: HTMLFormElement, submitter?: HTMLElement) {
return this.shouldInterceptNavigation(element, submitter)
}
formSubmissionIntercepted(element: HTMLFormElement, submitter?: HTMLElement) {
if (this.formSubmission) {
this.formSubmission.stop()
}
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))
}
// View delegate
allowsImmediateRender(_snapshot: Snapshot, _resume: (value: any) => void) {
return true
}
viewRenderedSnapshot(_snapshot: Snapshot, _isPreview: boolean) {}
preloadOnLoadLinksForView(element: Element) {
session.preloadOnLoadLinksForView(element)
}
viewInvalidated() {}
// 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.src = url
}
private proposeVisitIfNavigatedWithAction(frame: FrameElement, element: Element, submitter?: HTMLElement) {
this.action = getVisitAction(submitter, element, frame)
this.frame = frame
if (isAction(this.action)) {
const { visitCachedSnapshot } = new SnapshotSubstitution(frame)
frame.delegate.fetchResponseLoaded = (fetchResponse: FetchResponse) => {
if (frame.src) {
const { statusCode, redirected } = fetchResponse
const responseHTML = frame.ownerDocument.documentElement.outerHTML
const response = { statusCode, redirected, responseHTML }
const options: Partial<VisitOptions> = {
response,
visitCachedSnapshot,
willRender: false,
updateHistory: false,
restorationIdentifier: this.restorationIdentifier,
}
if (this.action) options.action = this.action
session.visit(frame.src, options)
}
}
}
}
changeHistory() {
if (this.action && this.frame) {
const method = getHistoryMethodForAction(this.action)
session.history.update(method, expandURL(this.frame.src || ""), this.restorationIdentifier)
}
}
private findFrameElement(element: Element, submitter?: HTMLElement) {
const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target")
return getFrameElementById(id) ?? this.element
}
async extractForeignFrameElement(container: ParentNode): Promise<FrameElement> {
let element
const id = CSS.escape(this.id)
try {
element = activateElement(container.querySelector(`turbo-frame#${id}`), this.sourceURL)
if (element) {
return element
}
element = activateElement(container.querySelector(`turbo-frame[src][recurse~=${id}]`), this.sourceURL)
if (element) {
await element.loaded
return await this.extractForeignFrameElement(element)
}
console.error(`Response has no matching <turbo-frame id="${id}"> element`)
} catch (error) {
console.error(error)
}
return new FrameElement()
}
private formActionIsVisitable(form: HTMLFormElement, submitter?: HTMLElement) {
const action = getAction(form, submitter)
return locationIsVisitable(expandURL(action), this.rootLocation)
}
private shouldInterceptNavigation(element: Element, submitter?: HTMLElement) {
const id = getAttribute("data-turbo-frame", submitter, element) || this.element.getAttribute("target")
if (element instanceof HTMLFormElement && !this.formActionIsVisitable(element, submitter)) {
return false
}
if (!this.enabled || id == "_top") {
return false
}
if (id) {
const frameElement = getFrameElementById(id)
if (frameElement) {
return !frameElement.disabled
}
}
if (!session.elementDriveEnabled(element)) {
return false
}
if (submitter && !session.elementDriveEnabled(submitter)) {
return false
}
return true
}
// Computed properties
get id() {
return this.element.id
}
get enabled() {
return !this.element.disabled
}
get sourceURL() {
if (this.element.src) {
return this.element.src
}
}
set sourceURL(sourceURL: string | undefined) {
this.ignoringChangesToAttribute("src", () => {
this.element.src = sourceURL ?? null
})
}
get loadingStyle() {
return this.element.loading
}
get isLoading() {
return this.formSubmission !== undefined || this.resolveVisitPromise() !== undefined
}
get complete() {
return this.element.hasAttribute("complete")
}
set complete(value: boolean) {
this.ignoringChangesToAttribute("complete", () => {
if (value) {
this.element.setAttribute("complete", "")
} else {
this.element.removeAttribute("complete")
}
})
}
get isActive() {
return this.element.isActive && this.connected
}
get rootLocation() {
const meta = this.element.ownerDocument.querySelector<HTMLMetaElement>(`meta[name="turbo-root"]`)
const root = meta?.content ?? "/"
return expandURL(root)
}
private isIgnoringChangesTo(attributeName: FrameElementObservedAttribute): boolean {
return this.ignoredAttributes.has(attributeName)
}
private ignoringChangesToAttribute(attributeName: FrameElementObservedAttribute, callback: () => void) {
this.ignoredAttributes.add(attributeName)
callback()
this.ignoredAttributes.delete(attributeName)
}
}
class SnapshotSubstitution {
private readonly clone: Node
private readonly id: string
constructor(element: FrameElement) {
this.clone = element.cloneNode(true)
this.id = element.id
}
visitCachedSnapshot = ({ element }: Snapshot) => {
const { id, clone } = this
element.querySelector("#" + id)?.replaceWith(clone)
}
}
function getFrameElementById(id: string | null) {
if (id != null) {
const element = document.getElementById(id)
if (element instanceof FrameElement) {
return element
}
}
}
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`)
}
if (element.ownerDocument !== document) {
element = document.importNode(element, true)
}
if (element instanceof FrameElement) {
element.connectedCallback()
element.disconnectedCallback()
return element
}
}
}