forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipboard.ts
More file actions
75 lines (66 loc) · 2 KB
/
Copy pathclipboard.ts
File metadata and controls
75 lines (66 loc) · 2 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
/** 是否运行在 Tauri 桌面环境(WKWebView 屏蔽了富文本剪贴板 API) */
function isTauri(): boolean {
return typeof window !== `undefined`
&& (`__TAURI_INTERNALS__` in window || `__TAURI__` in window)
}
/** 桌面端:通过 Tauri 原生剪贴板写入,绕开 WKWebView 的限制 */
async function tauriCopy(cmd: string, args: Record<string, unknown>): Promise<boolean> {
try {
const { invoke } = await import(`@tauri-apps/api/core`)
await invoke(cmd, args)
return true
}
catch {
return false
}
}
function legacyCopy(text: string): Promise<void> {
return new Promise((resolve, reject) => {
try {
const textarea = document.createElement(`textarea`)
textarea.value = text
textarea.setAttribute(`readonly`, `true`)
textarea.style.position = `fixed`
textarea.style.opacity = `0`
document.body.appendChild(textarea)
textarea.select()
const ok = document.execCommand(`copy`)
document.body.removeChild(textarea)
ok ? resolve() : reject(new Error(`execCommand failed`))
}
catch (err) {
reject(err)
}
})
}
export async function copyPlain(text: string): Promise<void> {
if (isTauri() && await tauriCopy(`copy_text`, { text }))
return
if (window.isSecureContext && navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text)
return
}
catch {
}
}
await legacyCopy(text)
}
export async function copyHtml(html: string, fallback?: string): Promise<void> {
const plain = fallback ?? html.replace(/<[^>]+>/g, ``)
if (isTauri() && await tauriCopy(`copy_html`, { html, text: plain }))
return
if (window.isSecureContext && navigator.clipboard?.write) {
try {
const item = new ClipboardItem({
'text/html': new Blob([html], { type: `text/html` }),
'text/plain': new Blob([plain], { type: `text/plain` }),
})
await navigator.clipboard.write([item])
return
}
catch {
}
}
await copyPlain(plain)
}