createCopy
Reactive clipboard primitive with duration-based status, ClipboardItem support, and an execCommand fallback.
createCopy writes strings or ClipboardItem values to the clipboard and tracks the result as reactive state. It writes through the Clipboard API, falls back to document.execCommand('copy') when that API is missing or the write fails, and holds a copied or failed status for a set delay before returning to idle. For a ready-made button, use CopyButton.
Import#
Features#
- Writes strings with
navigator.clipboard.writeTextandClipboardItemvalues withnavigator.clipboard.write. It falls back todocument.execCommand('copy')when the matching method is missing or the write throws. - Accepts a
string,ClipboardItem,ClipboardItem[], aPromiseof any of these, or a function returning them. - In the fallback path, extracts plain text from a
ClipboardItem, or serializes the data withJSON.stringifywhen no text type is present. - Exposes
isCopied(),isError(), andstatus()('idle' | 'copied' | 'failed'). Both active states reset toidleafterresetDelaymilliseconds. - A newer
copy()call supersedes an earlier pending one. The superseded call resolves tofalseand sets no state. - Resolves
copy()tofalsewithout touching the clipboard on the server, after the owner disposes, or when there is no source (neither the argument noroptions.value).
Signature#
Usage Example#
src/ClipboardSnippet.tsx
Fallback Mechanics#
When navigator.clipboard is missing or its write call throws, createCopy falls back to document.execCommand('copy'):
- For a string, it adds a visually hidden read-only
<textarea>, selects the content, and runs the command. - For a
ClipboardItemorClipboardItem[], it looks for atext/plainortext/*type, reads it throughitem.getType(type)andblob.text(), then runs the command on that text. If no text type is found or reading fails, it runs the command onJSON.stringify(data).