|
1 | | -<script context="module"> |
2 | | - /*! clipboard-copy. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */ |
3 | | -
|
4 | | - function makeError() { |
5 | | - return new DOMException('The request is not allowed', 'NotAllowedError'); |
6 | | - } |
7 | | -
|
8 | | - /** |
9 | | - * @param {string} text |
10 | | - */ |
11 | | - async function copyClipboardApi(text) { |
12 | | - // Use the Async Clipboard API when available. Requires a secure browsing |
13 | | - // context (i.e. HTTPS) |
14 | | - if (!navigator.clipboard) { |
15 | | - throw makeError(); |
16 | | - } |
17 | | - return navigator.clipboard.writeText(text); |
18 | | - } |
19 | | -
|
20 | | - /** |
21 | | - * @param {string} text |
22 | | - */ |
23 | | - async function copyExecCommand(text) { |
24 | | - // Put the text to copy into a <span> |
25 | | - const span = document.createElement('span'); |
26 | | - span.textContent = text; |
27 | | -
|
28 | | - // Preserve consecutive spaces and newlines |
29 | | - span.style.whiteSpace = 'pre'; |
30 | | - span.style.webkitUserSelect = 'auto'; |
31 | | - span.style.userSelect = 'all'; |
32 | | -
|
33 | | - // Add the <span> to the page |
34 | | - document.body.appendChild(span); |
35 | | -
|
36 | | - // Make a selection object representing the range of text selected by the user |
37 | | - const selection = window.getSelection(); |
38 | | - const range = window.document.createRange(); |
39 | | - selection?.removeAllRanges(); |
40 | | - range.selectNode(span); |
41 | | - selection?.addRange(range); |
42 | | -
|
43 | | - // Copy text to the clipboard |
44 | | - let success = false; |
45 | | - try { |
46 | | - success = window.document.execCommand('copy'); |
47 | | - } finally { |
48 | | - // Cleanup |
49 | | - selection?.removeAllRanges(); |
50 | | - window.document.body.removeChild(span); |
51 | | - } |
52 | | -
|
53 | | - if (!success) throw makeError(); |
54 | | - } |
55 | | -
|
56 | | - /** |
57 | | - * @param {string} text |
58 | | - */ |
59 | | - async function clipboardCopy(text) { |
60 | | - try { |
61 | | - await copyClipboardApi(text); |
62 | | - } catch (err) { |
63 | | - // ...Otherwise, use document.execCommand() fallback |
64 | | - try { |
65 | | - await copyExecCommand(text); |
66 | | - } catch (err2) { |
67 | | - throw err2 || err || makeError(); |
68 | | - } |
69 | | - } |
70 | | - } |
71 | | -</script> |
72 | | -
|
73 | 1 | <script> |
74 | 2 | import { browser } from '$app/environment'; |
75 | 3 | import { page } from '$app/stores'; |
76 | 4 | import { readable, get } from 'svelte/store'; |
| 5 | + import { clipboardCopy } from './clipboardCopy.js'; |
77 | 6 |
|
78 | 7 | let styleInit = false; |
79 | 8 |
|
|
0 commit comments