okami.mom/strata

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

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
1.7 KiB35 linesraw
1/**
2 * Copy text for the person. The browser clipboard call can be refused (the desktop web view asks for permission, or has no clipboard
3 * object); the older copy command through a hidden field still works there. The answer is always a toast: "Copied", or one plain
4 * sentence and what to do next (#3731).
5 */
6export interface ClipboardDeps {
7  clipboard?: { writeText(text: string): Promise<void> } | null;
8  legacyCopy?: (text: string) => boolean;
9  toast: (tone: 'success' | 'warn', title: string, body?: string) => void;
10}
11
12function legacyCopy(text: string): boolean {
13  if (typeof document === 'undefined') return false;
14  const field = document.createElement('textarea');
15  field.value = text;
16  field.setAttribute('readonly', '');
17  field.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
18  document.body.appendChild(field);
19  const active = document.activeElement as HTMLElement | null;
20  try {
21    field.select();
22    return document.execCommand('copy');
23  } catch { return false; }
24  finally { field.remove(); active?.focus?.(); }
25}
26
27export async function copyText(text: string, label: string, deps: ClipboardDeps): Promise<boolean> {
28  const clipboard = deps.clipboard === undefined ? (typeof navigator === 'undefined' ? null : navigator.clipboard) : deps.clipboard;
29  let done = false;
30  try { if (clipboard) { await clipboard.writeText(text); done = true; } } catch { /* the fallback is next */ }
31  if (!done) { try { done = (deps.legacyCopy ?? legacyCopy)(text); } catch { done = false; } }
32  if (done) deps.toast('success', 'Copied', label);
33  else deps.toast('warn', 'Couldn’t copy', 'Select the text and copy it with Ctrl+C.');
34  return done;
35}