UNPKG

@react-hook/copy

Version:
1 lines 2.88 kB
{"version":3,"file":"index.mjs","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\n\nfunction useCopy(text: string) {\n const [copied, setCopied] = React.useState(false)\n const reset = React.useRef(() => setCopied(false))\n // Resets 'copied' if text changes\n React.useEffect(() => reset.current, [text])\n return {\n copied,\n copy: React.useCallback(\n () =>\n copyToClipboard(text)\n .then(() => setCopied(true))\n .catch(() => setCopied((copied) => copied)),\n [text]\n ),\n reset: reset.current,\n } as const\n}\n/* istanbul ignore next */\nfunction copyToClipboard(text: string) {\n // uses the Async Clipboard API when available. Requires a secure browing\n // context (i.e. HTTPS)\n if (navigator.clipboard) return navigator.clipboard.writeText(text)\n // puts the text to copy into a <span>\n const span = document.createElement('span')\n span.textContent = text\n // preserves consecutive spaces and newlines\n span.style.whiteSpace = 'pre'\n // adds the <span> to the page\n document.body.appendChild(span)\n // makes a selection object representing the range of text selected by the user\n const selection = window.getSelection()\n if (!selection) return Promise.reject()\n const range = window.document.createRange()\n selection.removeAllRanges()\n range.selectNode(span)\n selection.addRange(range)\n // copies text to the clipboard\n try {\n window.document.execCommand('copy')\n } catch (err) {\n return Promise.reject()\n }\n // cleans up the dom element and selection\n selection.removeAllRanges()\n window.document.body.removeChild(span)\n // the Async Clipboard API returns a promise that may reject with `undefined`\n // so we match that here for consistency\n return Promise.resolve()\n}\n\nexport default useCopy\n"],"names":["copied","text","setCopied","React","reset","current","copy","navigator","clipboard","writeText","span","document","createElement","textContent","style","whiteSpace","body","appendChild","selection","window","getSelection","Promise","reject","range","createRange","removeAllRanges","selectNode","addRange","execCommand","err","removeChild","resolve","copyToClipboard","then","catch"],"mappings":"AAaiC,WAACA,UAAWA,8FAX7C,SAAiBC,uBAUKC,EAAU,uBACTA,SAVdF,EAAQE,GAAaC,EAAe,GACrCC,EAAQD,EAAa,IAAMD,EAAU,WAE3CC,EAAgB,IAAMC,EAAMC,QAAS,CAACJ,IAC/B,CACLD,OAAAA,EACAM,KAAMH,EACJ,IAUN,SAAyBF,MAGnBM,UAAUC,UAAW,OAAOD,UAAUC,UAAUC,UAAUR,OAExDS,EAAOC,SAASC,cAAc,QACpCF,EAAKG,YAAcZ,EAEnBS,EAAKI,MAAMC,WAAa,MAExBJ,SAASK,KAAKC,YAAYP,OAEpBQ,EAAYC,OAAOC,mBACpBF,EAAW,OAAOG,QAAQC,aACzBC,EAAQJ,OAAOR,SAASa,cAC9BN,EAAUO,kBACVF,EAAMG,WAAWhB,GACjBQ,EAAUS,SAASJ,OAGjBJ,OAAOR,SAASiB,YAAY,QAC5B,MAAOC,UACAR,QAAQC,gBAGjBJ,EAAUO,kBACVN,OAAOR,SAASK,KAAKc,YAAYpB,GAG1BW,QAAQU,UAtCTC,CAAgB/B,GACbgC,QACAC,SACL,CAACjC,IAEHG,MAAOA,EAAMC"}