UNPKG

@mui/internal-docs-infra

Version:

MUI Infra - internal documentation creation tools.

35 lines 1.01 kB
import * as React from 'react'; import copyToClipboard from 'clipboard-copy'; export function useCopier(contents, opts) { const { onCopied, onError, onClick, timeout = 2000 } = opts || {}; const copyTimeoutRef = React.useRef(undefined); const [recentlySuccessful, setRecentlySuccessful] = React.useState(false); const copy = React.useCallback(async event => { clearTimeout(copyTimeoutRef.current); setRecentlySuccessful(false); try { const content = typeof contents === 'function' ? contents() : contents; if (content) { await copyToClipboard(content); } setRecentlySuccessful(true); onCopied?.(); copyTimeoutRef.current = setTimeout(() => { clearTimeout(copyTimeoutRef.current); setRecentlySuccessful(false); }, timeout); } catch (error) { onError?.(error); } onClick?.(event); }, [contents, timeout, onCopied, onError, onClick]); return { copy, recentlySuccessful }; }