-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathlink_prefetch_observer.js
More file actions
219 lines (166 loc) · 6.28 KB
/
link_prefetch_observer.js
File metadata and controls
219 lines (166 loc) · 6.28 KB
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
import { getLocationForLink } from "../core/url"
import {
dispatch,
getMetaContent,
findClosestRecursively
} from "../util"
import { FetchMethod, FetchRequest } from "../http/fetch_request"
import { prefetchCache, cacheTtl } from "../core/drive/prefetch_cache"
export class LinkPrefetchObserver {
started = false
#prefetchedLink = null
#pendingFetchRequests = new Map()
constructor(delegate, eventTarget) {
this.delegate = delegate
this.eventTarget = eventTarget
}
start() {
if (this.started) return
if (this.eventTarget.readyState === "loading") {
this.eventTarget.addEventListener("DOMContentLoaded", this.#enable, { once: true })
} else {
this.#enable()
}
}
stop() {
if (!this.started) return
this.eventTarget.removeEventListener("mouseenter", this.#tryToPrefetchRequest, {
capture: true,
passive: true
})
this.eventTarget.removeEventListener("mouseleave", this.#cancelRequestIfObsolete, {
capture: true,
passive: true
})
this.eventTarget.removeEventListener("turbo:before-fetch-request", this.#tryToUsePrefetchedRequest, true)
this.eventTarget.removeEventListener("turbo:before-visit", this.#cancelPendingFetchRequests, true)
this.started = false
}
#enable = () => {
this.eventTarget.addEventListener("mouseenter", this.#tryToPrefetchRequest, {
capture: true,
passive: true
})
this.eventTarget.addEventListener("mouseleave", this.#cancelRequestIfObsolete, {
capture: true,
passive: true
})
this.eventTarget.addEventListener("turbo:before-fetch-request", this.#tryToUsePrefetchedRequest, true)
this.eventTarget.addEventListener("turbo:before-visit", this.#cancelPendingFetchRequests, true)
this.started = true
}
#tryToPrefetchRequest = (event) => {
if (getMetaContent("turbo-prefetch") === "false") return
const target = event.target
const isLink = target.matches && target.matches("a[href]:not([target^=_]):not([download])")
if (isLink && this.#isPrefetchable(target)) {
const link = target
const location = getLocationForLink(link)
if (this.delegate.canPrefetchRequestToLocation(link, location)) {
this.#prefetchedLink = link
const fetchRequest = new FetchRequest(
this,
FetchMethod.get,
location,
new URLSearchParams(),
target
)
fetchRequest.fetchOptions.priority = "low"
// Memorize fetch request and cancel previous one to the same URL
const url = location.href
const lastFetchRequest = this.#pendingFetchRequests.get(url)
if(lastFetchRequest) lastFetchRequest.cancel()
this.#pendingFetchRequests.set(url, fetchRequest)
prefetchCache.putLater(location, fetchRequest, this.#cacheTtl)
}
}
}
#cancelPendingFetchRequests = (event) => {
if (event.detail.fetchRequest) return
for (const [url, fetchRequest] of this.#pendingFetchRequests.entries()) {
if (url !== event.detail.url) {
fetchRequest.cancel()
this.#pendingFetchRequests.delete(url)
}
}
}
#cancelRequestIfObsolete = (event) => {
if (event.target === this.#prefetchedLink) this.#cancelPrefetchRequest()
}
#cancelPrefetchRequest = () => {
prefetchCache.clear()
this.#prefetchedLink = null
}
#tryToUsePrefetchedRequest = (event) => {
if (event.target.tagName !== "FORM" && event.detail.fetchOptions.method === "GET") {
const cached = prefetchCache.get(event.detail.url)
if (cached) {
// User clicked link, use cache response
event.detail.fetchRequest = cached
}
prefetchCache.clear()
}
}
prepareRequest(request) {
const link = request.target
request.headers["X-Sec-Purpose"] = "prefetch"
const turboFrame = link.closest("turbo-frame")
const turboFrameTarget = link.getAttribute("data-turbo-frame") || turboFrame?.getAttribute("target") || turboFrame?.id
if (turboFrameTarget && turboFrameTarget !== "_top") {
request.headers["Turbo-Frame"] = turboFrameTarget
}
}
// Fetch request interface
requestSucceededWithResponse() {}
requestStarted(fetchRequest) {}
requestErrored(fetchRequest) {}
requestFinished(fetchRequest) {
const url = fetchRequest.url.href
if(this.#pendingFetchRequests.get(url) === fetchRequest) {
this.#pendingFetchRequests.delete(url)
}
}
requestPreventedHandlingResponse(fetchRequest, fetchResponse) {}
requestFailedWithResponse(fetchRequest, fetchResponse) {}
get #cacheTtl() {
return Number(getMetaContent("turbo-prefetch-cache-time")) || cacheTtl
}
#isPrefetchable(link) {
const href = link.getAttribute("href")
if (!href) return false
if (unfetchableLink(link)) return false
if (linkToTheSamePage(link)) return false
if (linkOptsOut(link)) return false
if (nonSafeLink(link)) return false
if (eventPrevented(link)) return false
return true
}
}
const unfetchableLink = (link) => {
return link.origin !== document.location.origin || !["http:", "https:"].includes(link.protocol) || link.hasAttribute("target")
}
const linkToTheSamePage = (link) => {
return (link.pathname + link.search === document.location.pathname + document.location.search) || link.href.startsWith("#")
}
const linkOptsOut = (link) => {
if (link.getAttribute("data-turbo-prefetch") === "false") return true
if (link.getAttribute("data-turbo") === "false") return true
const turboPrefetchParent = findClosestRecursively(link, "[data-turbo-prefetch]")
if (turboPrefetchParent && turboPrefetchParent.getAttribute("data-turbo-prefetch") === "false") return true
return false
}
const nonSafeLink = (link) => {
const turboMethod = link.getAttribute("data-turbo-method")
if (turboMethod && turboMethod.toLowerCase() !== "get") return true
if (isUJS(link)) return true
if (link.hasAttribute("data-turbo-confirm")) return true
if (link.hasAttribute("data-turbo-stream")) return true
return false
}
const isUJS = (link) => {
return link.hasAttribute("data-remote") || link.hasAttribute("data-behavior") || link.hasAttribute("data-confirm") || link.hasAttribute("data-method")
}
const eventPrevented = (link) => {
const event = dispatch("turbo:before-prefetch", { target: link, cancelable: true })
return event.defaultPrevented
}