-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathsession.ts
459 lines (378 loc) · 14.2 KB
/
session.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
import { Adapter } from "./native/adapter"
import { BrowserAdapter, ReloadReason } 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 { History, HistoryDelegate } from "./drive/history"
import { LinkClickObserver, LinkClickObserverDelegate } from "../observers/link_click_observer"
import { FormLinkClickObserver, FormLinkClickObserverDelegate } from "../observers/form_link_click_observer"
import { getAction, expandURL, locationIsVisitable, Locatable } from "./url"
import { Navigator, NavigatorDelegate } from "./drive/navigator"
import { PageObserver, PageObserverDelegate } from "../observers/page_observer"
import { ScrollObserver } from "../observers/scroll_observer"
import { StreamMessage } from "./streams/stream_message"
import { StreamMessageRenderer } from "./streams/stream_message_renderer"
import { StreamObserver } from "../observers/stream_observer"
import { Action, Position, StreamSource } from "./types"
import { clearBusyState, dispatch, findClosestRecursively, getVisitAction, markAsBusy } from "../util"
import { PageView, PageViewDelegate, PageViewRenderOptions } from "./drive/page_view"
import { Visit, VisitOptions } from "./drive/visit"
import { PageSnapshot } from "./drive/page_snapshot"
import { FrameElement } from "../elements/frame_element"
import { FrameViewRenderOptions } from "./frames/frame_view"
import { FetchResponse } from "../http/fetch_response"
import { Preloader, PreloaderDelegate } from "./drive/preloader"
export type FormMode = "on" | "off" | "optin"
export type TimingData = unknown
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 TurboFrameLoadEvent = CustomEvent
export type TurboBeforeFrameRenderEvent = CustomEvent<{ newFrame: FrameElement } & FrameViewRenderOptions>
export type TurboFrameRenderEvent = CustomEvent<{ fetchResponse: FetchResponse }>
export type TurboLoadEvent = CustomEvent<{ url: string; timing: TimingData }>
export type TurboRenderEvent = CustomEvent
export type TurboVisitEvent = CustomEvent<{ url: string; action: Action }>
export class Session
implements
FormSubmitObserverDelegate,
HistoryDelegate,
FormLinkClickObserverDelegate,
LinkClickObserverDelegate,
NavigatorDelegate,
PageObserverDelegate,
PageViewDelegate,
PreloaderDelegate
{
readonly navigator = new Navigator(this)
readonly history = new History(this)
readonly preloader = new Preloader(this)
readonly view = new PageView(this, document.documentElement as HTMLBodyElement)
adapter: Adapter = new BrowserAdapter(this)
readonly pageObserver = new PageObserver(this)
readonly cacheObserver = new CacheObserver()
readonly linkClickObserver = new LinkClickObserver(this, window)
readonly formSubmitObserver = new FormSubmitObserver(this, document)
readonly scrollObserver = new ScrollObserver(this)
readonly streamObserver = new StreamObserver(this)
readonly formLinkClickObserver = new FormLinkClickObserver(this, document.documentElement)
readonly frameRedirector = new FrameRedirector(this, document.documentElement)
readonly streamMessageRenderer = new StreamMessageRenderer()
drive = true
enabled = true
progressBarDelay = 500
started = false
formMode: FormMode = "on"
start() {
if (!this.started) {
this.pageObserver.start()
this.cacheObserver.start()
this.formLinkClickObserver.start()
this.linkClickObserver.start()
this.formSubmitObserver.start()
this.scrollObserver.start()
this.streamObserver.start()
this.frameRedirector.start()
this.history.start()
this.preloader.start()
this.started = true
this.enabled = true
}
}
disable() {
this.enabled = false
}
stop() {
if (this.started) {
this.pageObserver.stop()
this.cacheObserver.stop()
this.formLinkClickObserver.stop()
this.linkClickObserver.stop()
this.formSubmitObserver.stop()
this.scrollObserver.stop()
this.streamObserver.stop()
this.frameRedirector.stop()
this.history.stop()
this.started = false
}
}
registerAdapter(adapter: Adapter) {
this.adapter = adapter
}
visit(location: Locatable, options: Partial<VisitOptions> = {}) {
const frameElement = options.frame ? document.getElementById(options.frame) : null
if (frameElement instanceof FrameElement) {
frameElement.src = location.toString()
frameElement.loaded
} else {
this.navigator.proposeVisit(expandURL(location), options)
}
}
connectStreamSource(source: StreamSource) {
this.streamObserver.connectStreamSource(source)
}
disconnectStreamSource(source: StreamSource) {
this.streamObserver.disconnectStreamSource(source)
}
renderStreamMessage(message: StreamMessage | string) {
this.streamMessageRenderer.render(StreamMessage.wrap(message))
}
clearCache() {
this.view.clearSnapshotCache()
}
setProgressBarDelay(delay: number) {
this.progressBarDelay = delay
}
setFormMode(mode: FormMode) {
this.formMode = mode
}
get location() {
return this.history.location
}
get restorationIdentifier() {
return this.history.restorationIdentifier
}
// History delegate
historyPoppedToLocationWithRestorationIdentifier(location: URL, restorationIdentifier: string) {
if (this.enabled) {
this.navigator.startVisit(location, restorationIdentifier, {
action: "restore",
historyChanged: true,
})
} else {
this.adapter.pageInvalidated({
reason: "turbo_disabled",
})
}
}
// Scroll observer delegate
scrollPositionChanged(position: Position) {
this.history.updateRestorationData({ scrollPosition: position })
}
// Form click observer delegate
willSubmitFormLinkToLocation(link: Element, location: URL): boolean {
return this.elementIsNavigatable(link) && locationIsVisitable(location, this.snapshot.rootLocation)
}
submittedFormLinkToLocation() {}
// Link click observer delegate
willFollowLinkToLocation(link: Element, location: URL, event: MouseEvent) {
return (
this.elementIsNavigatable(link) &&
locationIsVisitable(location, this.snapshot.rootLocation) &&
this.applicationAllowsFollowingLinkToLocation(link, location, event)
)
}
followedLinkToLocation(link: Element, location: URL) {
const action = this.getActionForLink(link)
const acceptsStreamResponse = link.hasAttribute("data-turbo-stream")
this.visit(location.href, { action, acceptsStreamResponse })
}
// Navigator delegate
allowsVisitingLocationWithAction(location: URL, action?: Action) {
return this.locationWithActionIsSamePage(location, action) || this.applicationAllowsVisitingLocation(location)
}
visitProposedToLocation(location: URL, options: Partial<VisitOptions>) {
extendURLWithDeprecatedProperties(location)
this.adapter.visitProposedToLocation(location, options)
}
visitStarted(visit: Visit) {
if (!visit.acceptsStreamResponse) {
markAsBusy(document.documentElement)
}
extendURLWithDeprecatedProperties(visit.location)
if (!visit.silent) {
this.notifyApplicationAfterVisitingLocation(visit.location, visit.action)
}
}
visitCompleted(visit: Visit) {
clearBusyState(document.documentElement)
this.notifyApplicationAfterPageLoad(visit.getTimingMetrics())
}
locationWithActionIsSamePage(location: URL, action?: Action): boolean {
return this.navigator.locationWithActionIsSamePage(location, action)
}
visitScrolledToSamePageLocation(oldURL: URL, newURL: URL) {
this.notifyApplicationAfterVisitingSamePageLocation(oldURL, newURL)
}
// Form submit observer delegate
willSubmitForm(form: HTMLFormElement, submitter?: HTMLElement): boolean {
const action = getAction(form, submitter)
return (
this.submissionIsNavigatable(form, submitter) &&
locationIsVisitable(expandURL(action), this.snapshot.rootLocation)
)
}
formSubmitted(form: HTMLFormElement, submitter?: HTMLElement) {
this.navigator.submitForm(form, submitter)
}
// Page observer delegate
pageBecameInteractive() {
this.view.lastRenderedLocation = this.location
this.notifyApplicationAfterPageLoad()
}
pageLoaded() {
this.history.assumeControlOfScrollRestoration()
}
pageWillUnload() {
this.history.relinquishControlOfScrollRestoration()
}
// Stream observer delegate
receivedMessageFromStream(message: StreamMessage) {
this.renderStreamMessage(message)
}
// Page view delegate
viewWillCacheSnapshot() {
if (!this.navigator.currentVisit?.silent) {
this.notifyApplicationBeforeCachingSnapshot()
}
}
allowsImmediateRender({ element }: PageSnapshot, options: PageViewRenderOptions) {
const event = this.notifyApplicationBeforeRender(element, options)
const {
defaultPrevented,
detail: { render },
} = event
if (this.view.renderer && render) {
this.view.renderer.renderElement = render
}
return !defaultPrevented
}
viewRenderedSnapshot(_snapshot: PageSnapshot, _isPreview: boolean) {
this.view.lastRenderedLocation = this.history.location
this.notifyApplicationAfterRender()
}
preloadOnLoadLinksForView(element: Element) {
this.preloader.preloadOnLoadLinksForView(element)
}
viewInvalidated(reason: ReloadReason) {
this.adapter.pageInvalidated(reason)
}
// Frame element
frameLoaded(frame: FrameElement) {
this.notifyApplicationAfterFrameLoad(frame)
}
frameRendered(fetchResponse: FetchResponse, frame: FrameElement) {
this.notifyApplicationAfterFrameRender(fetchResponse, frame)
}
// Application events
applicationAllowsFollowingLinkToLocation(link: Element, location: URL, ev: MouseEvent) {
const event = this.notifyApplicationAfterClickingLinkToLocation(link, location, ev)
return !event.defaultPrevented
}
applicationAllowsVisitingLocation(location: URL) {
const event = this.notifyApplicationBeforeVisitingLocation(location)
return !event.defaultPrevented
}
notifyApplicationAfterClickingLinkToLocation(link: Element, location: URL, event: MouseEvent) {
return dispatch<TurboClickEvent>("turbo:click", {
target: link,
detail: { url: location.href, originalEvent: event },
cancelable: true,
})
}
notifyApplicationBeforeVisitingLocation(location: URL) {
return dispatch<TurboBeforeVisitEvent>("turbo:before-visit", {
detail: { url: location.href },
cancelable: true,
})
}
notifyApplicationAfterVisitingLocation(location: URL, action: Action) {
return dispatch<TurboVisitEvent>("turbo:visit", { detail: { url: location.href, action } })
}
notifyApplicationBeforeCachingSnapshot() {
return dispatch<TurboBeforeCacheEvent>("turbo:before-cache")
}
notifyApplicationBeforeRender(newBody: HTMLBodyElement, options: PageViewRenderOptions) {
return dispatch<TurboBeforeRenderEvent>("turbo:before-render", {
detail: { newBody, ...options },
cancelable: true,
})
}
notifyApplicationAfterRender() {
return dispatch<TurboRenderEvent>("turbo:render")
}
notifyApplicationAfterPageLoad(timing: TimingData = {}) {
return dispatch<TurboLoadEvent>("turbo:load", {
detail: { url: this.location.href, timing },
})
}
notifyApplicationAfterVisitingSamePageLocation(oldURL: URL, newURL: URL) {
dispatchEvent(
new HashChangeEvent("hashchange", {
oldURL: oldURL.toString(),
newURL: newURL.toString(),
})
)
}
notifyApplicationAfterFrameLoad(frame: FrameElement) {
return dispatch<TurboFrameLoadEvent>("turbo:frame-load", { target: frame })
}
notifyApplicationAfterFrameRender(fetchResponse: FetchResponse, frame: FrameElement) {
return dispatch<TurboFrameRenderEvent>("turbo:frame-render", {
detail: { fetchResponse },
target: frame,
cancelable: true,
})
}
// Helpers
submissionIsNavigatable(form: HTMLFormElement, submitter?: HTMLElement): boolean {
if (this.formMode == "off") {
return false
} else {
const submitterIsNavigatable = submitter ? this.elementIsNavigatable(submitter) : true
if (this.formMode == "optin") {
return submitterIsNavigatable && form.closest('[data-turbo="true"]') != null
} else {
return submitterIsNavigatable && this.elementIsNavigatable(form)
}
}
}
elementIsNavigatable(element: Element): boolean {
const container = findClosestRecursively(element, "[data-turbo]")
const withinFrame = findClosestRecursively(element, "turbo-frame")
// Check if Drive is enabled on the session or we're within a Frame.
if (this.drive || withinFrame) {
// Element is navigatable by default, unless `data-turbo="false"`.
if (container) {
return container.getAttribute("data-turbo") != "false"
} else {
return true
}
} else {
// Element isn't navigatable by default, unless `data-turbo="true"`.
if (container) {
return container.getAttribute("data-turbo") == "true"
} else {
return false
}
}
}
// Private
getActionForLink(link: Element): Action {
return getVisitAction(link) || "advance"
}
get snapshot() {
return this.view.snapshot
}
}
// Older versions of the Turbo Native adapters referenced the
// `Location#absoluteURL` property in their implementations of
// the `Adapter#visitProposedToLocation()` and `#visitStarted()`
// methods. The Location class has since been removed in favor
// of the DOM URL API, and accordingly all Adapter methods now
// receive URL objects.
//
// We alias #absoluteURL to #toString() here to avoid crashing
// older adapters which do not expect URL objects. We should
// consider removing this support at some point in the future.
function extendURLWithDeprecatedProperties(url: URL) {
Object.defineProperties(url, deprecatedLocationPropertyDescriptors)
}
const deprecatedLocationPropertyDescriptors = {
absoluteURL: {
get() {
return this.toString()
},
},
}