-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
index.ts
80 lines (67 loc) · 2.16 KB
/
index.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
export async function copyToClipboard(text: string) {
try {
return await navigator.clipboard.writeText(text)
} catch {
const element = document.createElement("textarea")
const previouslyFocusedElement = document.activeElement
element.value = text
// Prevent keyboard from showing on mobile
element.setAttribute("readonly", "")
element.style.contain = "strict"
element.style.position = "absolute"
element.style.left = "-9999px"
element.style.fontSize = "12pt" // Prevent zooming on iOS
const selection = document.getSelection()
const originalRange = selection
? selection.rangeCount > 0 && selection.getRangeAt(0)
: null
document.body.appendChild(element)
element.select()
// Explicit selection workaround for iOS
element.selectionStart = 0
element.selectionEnd = text.length
document.execCommand("copy")
document.body.removeChild(element)
if (originalRange) {
selection!.removeAllRanges() // originalRange can't be truthy when selection is falsy
selection!.addRange(originalRange)
}
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
;(previouslyFocusedElement as HTMLElement).focus()
}
}
}
export function isMobile() {
return /Mobi|Android|iPhone/i.test(navigator.userAgent)
}
export function dateFormat(date: Date, fmt = "YYYY-mm-dd HH:MM") {
let ret
const opt = {
"Y+": date.getFullYear().toString(),
"m+": (date.getMonth() + 1).toString(),
"d+": date.getDate().toString(),
"H+": date.getHours().toString(),
"M+": date.getMinutes().toString(),
"S+": date.getSeconds().toString() // second
}
Object.entries(opt).forEach(([k, v]) => {
ret = new RegExp("(" + k + ")").exec(fmt)
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? v : v.padStart(ret[1].length, "0")
)
}
})
return fmt
}
export function splitKeys(keys: string) {
return keys
.trim()
.split(/\s*[\|\n]\s*/)
.filter(k => /sk-\w{48}/.test(k))
}
export function randomKey(keys: string[]) {
return keys.length ? keys[Math.floor(Math.random() * keys.length)] : ""
}