|
| 1 | +import { onDestroy } from 'svelte'; |
| 2 | +import { toast } from 'svelte-sonner'; |
| 3 | + |
| 4 | +const DEFAULT_SUCCESS_MESSAGE = 'Copied to clipboard'; |
| 5 | +const DEFAULT_ERROR_MESSAGE = 'Failed to copy to clipboard'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Writes text to the clipboard and toasts the outcome. Fire-and-forget — use |
| 9 | + * when no reactive feedback is needed. For a reactive `copied` flag, use the |
| 10 | + * `Clipboard` class. |
| 11 | + */ |
| 12 | +export async function copyToClipboard( |
| 13 | + text: string, |
| 14 | + successMessage: string = DEFAULT_SUCCESS_MESSAGE |
| 15 | +): Promise<boolean> { |
| 16 | + try { |
| 17 | + await navigator.clipboard.writeText(text); |
| 18 | + toast.success(successMessage); |
| 19 | + return true; |
| 20 | + } catch { |
| 21 | + // Insecure context, permission denied, tab not focused, etc. |
| 22 | + toast.error(DEFAULT_ERROR_MESSAGE); |
| 23 | + return false; |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +export interface ClipboardOptions { |
| 28 | + /** How long `copied` stays true after a successful copy, in ms. Defaults to 2000. */ |
| 29 | + resetDelay?: number; |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Clipboard wrapper with a reactive `copied` flag that auto-resets. Call |
| 34 | + * `dispose()` when done (or use `useClipboard` to do that automatically). |
| 35 | + */ |
| 36 | +export class Clipboard { |
| 37 | + readonly #resetDelay: number; |
| 38 | + #timeout?: ReturnType<typeof setTimeout>; |
| 39 | + #copied = $state(false); |
| 40 | + |
| 41 | + constructor(options: ClipboardOptions = {}) { |
| 42 | + this.#resetDelay = options.resetDelay ?? 2000; |
| 43 | + } |
| 44 | + |
| 45 | + get copied() { |
| 46 | + return this.#copied; |
| 47 | + } |
| 48 | + |
| 49 | + async copy(text: string, successMessage?: string): Promise<boolean> { |
| 50 | + const ok = await copyToClipboard(text, successMessage); |
| 51 | + if (!ok) return false; |
| 52 | + |
| 53 | + this.#copied = true; |
| 54 | + clearTimeout(this.#timeout); |
| 55 | + this.#timeout = setTimeout(() => (this.#copied = false), this.#resetDelay); |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + /** Clears any pending reset timeout. */ |
| 60 | + dispose() { |
| 61 | + clearTimeout(this.#timeout); |
| 62 | + this.#timeout = undefined; |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** Component-aware `Clipboard` that clears pending reset timeouts on unmount. */ |
| 67 | +export function useClipboard(options?: ClipboardOptions): Clipboard { |
| 68 | + const clip = new Clipboard(options); |
| 69 | + onDestroy(() => clip.dispose()); |
| 70 | + return clip; |
| 71 | +} |
0 commit comments