okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
1.8 KiB34 linesraw
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) {
15  const [copied, setCopied] = useState(false);
16  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
17  useEffect(() => () => clearTimeout(timer.current), []);
18  const 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.
20    const { pushToast } = await import('./store');
21    let value: string;
22    try { value = typeof text === 'function' ? await text() : text; }
23    catch { 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.
25    const ok = await copyText(value, label, { toast: (tone, title, body) => { if (tone !== 'success') pushToast(tone, title, body); } });
26    if (ok) {
27      setCopied(true);
28      clearTimeout(timer.current);
29      timer.current = setTimeout(() => setCopied(false), hold);
30    }
31    return ok;
32  }, [hold]);
33  return { copied, copy };
34}