okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1import { useCallback , useEffect , useRef , useState } from 'react' ; 2import { copyText } from './clipboard' ; 3 4/** How long a copy button shows that it worked (#4748). */ 5export const COPIED_MS = 1800 ; 6/** A menu item shows it a little shorter and then closes its menu. */ 7export const COPIED_MENU_MS = 900 ; 8 9/** 10* One behaviour for every Copy control: copy the text (with the older fallback of copyText; only a failure gets a toast), and when it worked, 11* `copied` is true for a moment so the control itself can show it. A failed copy leaves the control as it was and the toast says so. 12* The text may be a function, for a value that has to be fetched first. 13*/ 14export function useCopy ( hold = COPIED_MS ) { 15const [ copied , setCopied ] = useState ( false ); 16const timer = useRef < ReturnType < typeof setTimeout > | undefined >( undefined ); 17useEffect (() => () => clearTimeout ( timer . current ), []); 18const copy = useCallback ( async ( text :string | (() => string | Promise < string >), label :string ) :Promise < boolean > => { 19// The toast store needs a browser, so it is loaded when someone copies: a renderer using this hook must render without one. 20const { pushToast} = await import ( './store' ); 21let value :string ; 22try { value = typeof text === 'function' ?await text () :text ; } 23catch { pushToast ( 'warn' , 'Couldn’t copy' ); return false ; } 24// A copy that worked is shown on the control itself (the icon turns into a check): no "Copied" popover at the corner. A copy that failed still says so. 25const ok = await copyText ( value , label , { toast :( tone , title , body ) => { if ( tone !== 'success' ) pushToast ( tone , title , body ); } }); 26if ( ok ) { 27setCopied ( true ); 28clearTimeout ( timer . current ); 29timer . current = setTimeout (() => setCopied ( false ), hold ); 30} 31return ok ; 32}, [ hold ]); 33return { copied, copy}; 34}