-
Notifications
You must be signed in to change notification settings - Fork 415
/
link_prefetch_observer.js
190 lines (143 loc) · 5.26 KB
/
link_prefetch_observer.js
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
import {
dispatch,
getLocationForLink,
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
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.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.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
)
prefetchCache.setLater(location.toString(), fetchRequest, this.#cacheTtl)
}
}
}
#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.toString())
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) {}
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
}