UNPKG

foxact

Version:

React Hooks/Utils done right. For browser, SSR, and React Server Components.

1 lines 1.18 kB
import"client-only";import{useState as r,useRef as o}from"react";import{noop as e}from"../noop/index.mjs";import{useStableHandler as t}from"../use-stable-handler-only-when-you-know-what-you-are-doing-or-you-will-be-fired/index.mjs";import{useCallback as i}from"../use-typescript-happy-callback/index.mjs";class a extends Error{constructor(r){super(r),this.name="UseClipboardError"}}function l(){let{timeout:l=1e3,usePromptAsFallback:n=!1,promptFallbackText:c="Failed to copy to clipboard automatically, please manually copy the text below.",onCopyError:p}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const[s,u]=r(null),[d,m]=r(!1),y=o(null),w=t(p||e),b=i(r=>{y.current&&clearTimeout(y.current),r&&(y.current=window.setTimeout(()=>m(!1),l)),m(r)},[l]),h=i(r=>{u(r),w(r)},[w]);return{copy:i(async r=>{try{if("clipboard"in navigator)await navigator.clipboard.writeText(r),b(!0);else throw new a("[foxact/use-clipboard] navigator.clipboard is not supported")}catch(o){if(n)try{window.prompt(c,r)}catch(r){h(r)}else h(o)}},[b,c,h,n]),reset:i(()=>{m(!1),u(null),y.current&&clearTimeout(y.current)},[]),error:s,copied:d}}export{a as UseClipboardError,l as useClipboard};