-
Notifications
You must be signed in to change notification settings - Fork 434
/
frame_controller.ts
602 lines (494 loc) · 17.8 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import {
FrameElement,
FrameElementDelegate,
FrameLoadingStyle,
FrameElementObservedAttribute,
} from "../../elements/frame_element"
import { FetchMethod, FetchRequest, FetchRequestDelegate } from "../../http/fetch_request"
import { FetchResponse } from "../../http/fetch_response"
import { AppearanceObserver, AppearanceObserverDelegate } from "../../observers/appearance_observer"
import {
clearBusyState,
dispatch,
getAttribute,
parseHTMLDocument,
markAsBusy,
uuid,
getHistoryMethodForAction,
getVisitAction,
} from "../../util"
import { FormSubmission, FormSubmissionDelegate } from "../drive/form_submission"
import { Snapshot } from "../snapshot"
import { ViewDelegate, ViewRenderOptions } from "../view"
import { Locatable, getAction, expandURL, urlsAreEqual, locationIsVisitable } from "../url"
import { FormSubmitObserver, FormSubmitObserverDelegate } from "../../observers/form_submit_observer"
import { FrameView } from "./frame_view"
import { LinkInterceptor, LinkInterceptorDelegate } from "./link_interceptor"
import { FormLinkClickObserver, FormLinkClickObserverDelegate } from "../../observers/form_link_click_observer"
import { FrameRenderer } from "./frame_renderer"
import { session } from "../index"
import { Action } from "../types"
import { VisitOptions } from "../drive/visit"
import { TurboBeforeFrameRenderEvent } from "../session"
import { StreamMessage } from "../streams/stream_message"
import { PageSnapshot } from "../drive/page_snapshot"
type VisitFallback = (location: Response | Locatable, options: Partial<VisitOptions>) => Promise<void>
export type TurboFrameMissingEvent = CustomEvent<{ response: Response; visit: VisitFallback }>
export class FrameController
implements
AppearanceObserverDelegate<FrameElement>,
FetchRequestDelegate,
FormSubmitObserverDelegate,
FormSubmissionDelegate,
FrameElementDelegate,
FormLinkClickObserverDelegate,
LinkInterceptorDelegate,
ViewDelegate<FrameElement, Snapshot<FrameElement>>
{
readonly element: FrameElement
readonly view: FrameView
readonly appearanceObserver: AppearanceObserver<FrameElement>
readonly formLinkClickObserver: FormLinkClickObserver
readonly linkInterceptor: LinkInterceptor
readonly formSubmitObserver: FormSubmitObserver
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
readonly restorationIdentifier: string
private previousFrameElement?: FrameElement
private currentNavigationElement?: Element
constructor(element: FrameElement) {
this.element = element
this.view = new FrameView(this, this.element)
this.appearanceObserver = new AppearanceObserver(this, this.element)
this.formLinkClickObserver = new FormLinkClickObserver(this, this.element)
this.linkInterceptor = new LinkInterceptor(this, this.element)
this.restorationIdentifier = uuid()
this.formSubmitObserver = new FormSubmitObserver(this, this.element)
}
connect() {
if (!this.connected) {
this.connected = true
if (this.loadingStyle == FrameLoadingStyle.lazy) {
this.appearanceObserver.start()
} else {
this.loadSourceURL()
}
this.formLinkClickObserver.start()
this.linkInterceptor.start()
this.formSubmitObserver.start()
}
}
disconnect() {
if (this.connected) {
this.connected = false
this.appearanceObserver.stop()
this.formLinkClickObserver.stop()
this.linkInterceptor.stop()
this.formSubmitObserver.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()
}
}
sourceURLReloaded() {
const { src } = this.element
this.ignoringChangesToAttribute("complete", () => {
this.element.removeAttribute("complete")
})
this.element.src = null
this.element.src = src
return this.element.loaded
}
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 newFrameElement = await this.extractForeignFrameElement(body)
if (newFrameElement) {
const snapshot = new Snapshot(newFrameElement)
const renderer = new FrameRenderer(
this,
this.view.snapshot,
snapshot,
FrameRenderer.renderElement,
false,
false
)
if (this.view.renderPromise) await this.view.renderPromise
this.changeHistory()
await this.view.render(renderer)
this.complete = true
session.frameRendered(fetchResponse, this.element)
session.frameLoaded(this.element)
this.fetchResponseLoaded(fetchResponse)
} else if (this.willHandleFrameMissingFromResponse(fetchResponse)) {
console.warn(
`A matching frame for #${this.element.id} was missing from the response, transforming into full-page Visit.`
)
this.visitResponse(fetchResponse.response)
}
}
} catch (error) {
console.error(error)
this.view.invalidate()
} finally {
this.fetchResponseLoaded = () => {}
}
}
// Appearance observer delegate
elementAppearedInViewport(element: FrameElement) {
this.proposeVisitIfNavigatedWithAction(element, element)
this.loadSourceURL()
}
// Form link click observer delegate
willSubmitFormLinkToLocation(link: Element): boolean {
return this.shouldInterceptNavigation(link)
}
submittedFormLinkToLocation(link: Element, _location: URL, form: HTMLFormElement): void {
const frame = this.findFrameElement(link)
if (frame) form.setAttribute("data-turbo-frame", frame.id)
}
// Link interceptor delegate
shouldInterceptLinkClick(element: Element, _location: string, _event: MouseEvent) {
return this.shouldInterceptNavigation(element)
}
linkClickIntercepted(element: Element, location: string) {
this.navigateFrame(element, location)
}
// Form submit observer delegate
willSubmitForm(element: HTMLFormElement, submitter?: HTMLElement) {
return element.closest("turbo-frame") == this.element && this.shouldInterceptNavigation(element, submitter)
}
formSubmitted(element: HTMLFormElement, submitter?: HTMLElement) {
if (this.formSubmission) {
this.formSubmission.stop()
}
this.formSubmission = new FormSubmission(this, element, submitter)
const { fetchRequest } = this.formSubmission
this.prepareRequest(fetchRequest)
this.formSubmission.start()
}
// Fetch request delegate
prepareRequest(request: FetchRequest) {
request.headers["Turbo-Frame"] = this.id
if (this.currentNavigationElement?.hasAttribute("data-turbo-stream")) {
request.acceptResponseType(StreamMessage.contentType)
}
}
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()
}
async requestFailedWithResponse(request: FetchRequest, response: FetchResponse) {
console.error(response)
await this.loadResponse(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)
frame.delegate.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({ element: newFrame }: Snapshot<FrameElement>, options: ViewRenderOptions<FrameElement>) {
const event = dispatch<TurboBeforeFrameRenderEvent>("turbo:before-frame-render", {
target: this.element,
detail: { newFrame, ...options },
cancelable: true,
})
const {
defaultPrevented,
detail: { render },
} = event
if (this.view.renderer && render) {
this.view.renderer.renderElement = render
}
return !defaultPrevented
}
viewRenderedSnapshot(_snapshot: Snapshot, _isPreview: boolean) {}
preloadOnLoadLinksForView(element: Element) {
session.preloadOnLoadLinksForView(element)
}
viewInvalidated() {}
// Frame renderer delegate
willRenderFrame(currentElement: FrameElement, _newElement: FrameElement) {
this.previousFrameElement = currentElement.cloneNode(true)
}
visitCachedSnapshot = ({ element }: Snapshot) => {
const frame = element.querySelector("#" + this.element.id)
if (frame && this.previousFrameElement) {
frame.replaceChildren(...this.previousFrameElement.children)
}
delete this.previousFrameElement
}
// 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)
frame.delegate.proposeVisitIfNavigatedWithAction(frame, element, submitter)
this.withCurrentNavigationElement(element, () => {
frame.src = url
})
}
proposeVisitIfNavigatedWithAction(frame: FrameElement, element: Element, submitter?: HTMLElement) {
this.action = getVisitAction(submitter, element, frame)
if (this.action) {
const pageSnapshot = PageSnapshot.fromElement(frame).clone()
const { visitCachedSnapshot } = frame.delegate
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,
snapshot: pageSnapshot,
}
if (this.action) options.action = this.action
session.visit(frame.src, options)
}
}
}
}
changeHistory() {
if (this.action) {
const method = getHistoryMethodForAction(this.action)
session.history.update(method, expandURL(this.element.src || ""), this.restorationIdentifier)
}
}
private willHandleFrameMissingFromResponse(fetchResponse: FetchResponse): boolean {
this.element.setAttribute("complete", "")
const response = fetchResponse.response
const visit = async (url: Locatable | Response, options: Partial<VisitOptions> = {}) => {
if (url instanceof Response) {
this.visitResponse(url)
} else {
session.visit(url, options)
}
}
const event = dispatch<TurboFrameMissingEvent>("turbo:frame-missing", {
target: this.element,
detail: { response, visit },
cancelable: true,
})
return !event.defaultPrevented
}
private async visitResponse(response: Response): Promise<void> {
const wrapped = new FetchResponse(response)
const responseHTML = await wrapped.responseHTML
const { location, redirected, statusCode } = wrapped
return session.visit(location, { response: { redirected, statusCode, responseHTML } })
}
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 | null> {
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)
}
} catch (error) {
console.error(error)
return new FrameElement()
}
return null
}
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.elementIsNavigatable(element)) {
return false
}
if (submitter && !session.elementIsNavigatable(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)
}
private withCurrentNavigationElement(element: Element, callback: () => void) {
this.currentNavigationElement = element
callback()
delete this.currentNavigationElement
}
}
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
}
}
}