-
Notifications
You must be signed in to change notification settings - Fork 433
/
util.js
247 lines (199 loc) · 6.31 KB
/
util.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
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
import { expandURL } from "./core/url"
export function activateScriptElement(element) {
if (element.getAttribute("data-turbo-eval") == "false") {
return element
} else {
const createdScriptElement = document.createElement("script")
const cspNonce = getMetaContent("csp-nonce")
if (cspNonce) {
createdScriptElement.nonce = cspNonce
}
createdScriptElement.textContent = element.textContent
createdScriptElement.async = false
copyElementAttributes(createdScriptElement, element)
return createdScriptElement
}
}
function copyElementAttributes(destinationElement, sourceElement) {
for (const { name, value } of sourceElement.attributes) {
destinationElement.setAttribute(name, value)
}
}
export function createDocumentFragment(html) {
const template = document.createElement("template")
template.innerHTML = html
return template.content
}
export function dispatch(eventName, { target, cancelable, detail } = {}) {
const event = new CustomEvent(eventName, {
cancelable,
bubbles: true,
composed: true,
detail
})
if (target && target.isConnected) {
target.dispatchEvent(event)
} else {
document.documentElement.dispatchEvent(event)
}
return event
}
export function nextRepaint() {
if (document.visibilityState === "hidden") {
return nextEventLoopTick()
} else {
return nextAnimationFrame()
}
}
export function nextAnimationFrame() {
return new Promise((resolve) => requestAnimationFrame(() => resolve()))
}
export function nextEventLoopTick() {
return new Promise((resolve) => setTimeout(() => resolve(), 0))
}
export function nextMicrotask() {
return Promise.resolve()
}
export function parseHTMLDocument(html = "") {
return new DOMParser().parseFromString(html, "text/html")
}
export function unindent(strings, ...values) {
const lines = interpolate(strings, values).replace(/^\n/, "").split("\n")
const match = lines[0].match(/^\s+/)
const indent = match ? match[0].length : 0
return lines.map((line) => line.slice(indent)).join("\n")
}
function interpolate(strings, values) {
return strings.reduce((result, string, i) => {
const value = values[i] == undefined ? "" : values[i]
return result + string + value
}, "")
}
export function uuid() {
return Array.from({ length: 36 })
.map((_, i) => {
if (i == 8 || i == 13 || i == 18 || i == 23) {
return "-"
} else if (i == 14) {
return "4"
} else if (i == 19) {
return (Math.floor(Math.random() * 4) + 8).toString(16)
} else {
return Math.floor(Math.random() * 15).toString(16)
}
})
.join("")
}
export function getAttribute(attributeName, ...elements) {
for (const value of elements.map((element) => element?.getAttribute(attributeName))) {
if (typeof value == "string") return value
}
return null
}
export function hasAttribute(attributeName, ...elements) {
return elements.some((element) => element && element.hasAttribute(attributeName))
}
export function markAsBusy(...elements) {
for (const element of elements) {
if (element.localName == "turbo-frame") {
element.setAttribute("busy", "")
}
element.setAttribute("aria-busy", "true")
}
}
export function clearBusyState(...elements) {
for (const element of elements) {
if (element.localName == "turbo-frame") {
element.removeAttribute("busy")
}
element.removeAttribute("aria-busy")
}
}
export function waitForLoad(element, timeoutInMilliseconds = 2000) {
return new Promise((resolve) => {
const onComplete = () => {
element.removeEventListener("error", onComplete)
element.removeEventListener("load", onComplete)
resolve()
}
element.addEventListener("load", onComplete, { once: true })
element.addEventListener("error", onComplete, { once: true })
setTimeout(resolve, timeoutInMilliseconds)
})
}
export function getHistoryMethodForAction(action) {
switch (action) {
case "replace":
return history.replaceState
case "advance":
case "restore":
return history.pushState
}
}
export function isAction(action) {
return action == "advance" || action == "replace" || action == "restore"
}
export function getVisitAction(...elements) {
const action = getAttribute("data-turbo-action", ...elements)
return isAction(action) ? action : null
}
export function getMetaElement(name) {
return document.querySelector(`meta[name="${name}"]`)
}
export function getMetaContent(name) {
const element = getMetaElement(name)
return element && element.content
}
export function setMetaContent(name, content) {
let element = getMetaElement(name)
if (!element) {
element = document.createElement("meta")
element.setAttribute("name", name)
document.head.appendChild(element)
}
element.setAttribute("content", content)
return element
}
export function findClosestRecursively(element, selector) {
if (element instanceof Element) {
return (
element.closest(selector) || findClosestRecursively(element.assignedSlot || element.getRootNode()?.host, selector)
)
}
}
export function elementIsFocusable(element) {
const inertDisabledOrHidden = "[inert], :disabled, [hidden], details:not([open]), dialog:not([open])"
return !!element && element.closest(inertDisabledOrHidden) == null && typeof element.focus == "function"
}
export function queryAutofocusableElement(elementOrDocumentFragment) {
return Array.from(elementOrDocumentFragment.querySelectorAll("[autofocus]")).find(elementIsFocusable)
}
export async function around(callback, reader) {
const before = reader()
callback()
await nextAnimationFrame()
const after = reader()
return [before, after]
}
export function doesNotTargetIFrame(anchor) {
if (anchor.hasAttribute("target")) {
for (const element of document.getElementsByName(anchor.target)) {
if (element instanceof HTMLIFrameElement) return false
}
}
return true
}
export function findLinkFromClickTarget(target) {
return findClosestRecursively(target, "a[href]:not([target^=_]):not([download])")
}
export function getLocationForLink(link) {
return expandURL(link.getAttribute("href") || "")
}
export function debounce(fn, delay) {
let timeoutId = null
return (...args) => {
const callback = () => fn.apply(this, args)
clearTimeout(timeoutId)
timeoutId = setTimeout(callback, delay)
}
}