Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useCopyToClipboard.ts

331 lines10.4 KB

1import * as React from "react";
2import { Marked } from "@t3tools/client-runtime/errors";
3import * as Schema from "effect/Schema";
4import {
5 COMPOSER_CONTEXT_CLIPBOARD_MIME,
6 encodeComposerContextClipboardHtml,
7} from "@t3tools/shared/composerContextClipboard";
8import { msg, type Msg } from "gt-react";
9​
10import { m } from "../i18n/messages";
11import { useStableCallback } from "./useStableCallback";
12​
13/** `msg()` sentences, resolved when the error is shown, so users read whole ones. */
14export interface ClipboardTarget {
15 /** An English noun for logs. */
16 readonly target: string;
17 /** Shown when the clipboard API is missing. */
18 readonly unavailableMessage: string | Msg;
19 /** Shown when the browser rejects the copy or read. */
20 readonly failureMessage: string | Msg;
22​
23/** Copying something the user named, such as a file: its name goes into the sentences as is. */
24export function namedClipboardTarget(name: string): ClipboardTarget {
25 return {
26 target: name,
27 unavailableMessage: msg`Clipboard API is unavailable while copying ${{ target: name }}.`,
28 failureMessage: msg`Failed to copy ${{ target: name }} to the clipboard.`,
29 };
31​
32const DEFAULT_CLIPBOARD_TARGET = "text";
33​
34function clipboardTargetFields(
35 target: ClipboardTarget | undefined,
36 failure: "unavailable" | "failure",
37) {
38 if (target === undefined) return { target: DEFAULT_CLIPBOARD_TARGET };
39 return {
40 target: target.target,
41 displayMessage: failure === "unavailable" ? target.unavailableMessage : target.failureMessage,
42 };
44​
45export class ClipboardApiUnavailableError extends Schema.TaggedError<ClipboardApiUnavailableError>()(
46 "ClipboardApiUnavailableError",
47 {
48 target: Schema.String,
49 displayMessage: Schema.optional(Marked),
50 },
51) {
52 override get message(): string {
53 if (this.displayMessage !== undefined) return m(this.displayMessage);
54 return m(msg("Clipboard API is unavailable while copying text."));
55 }
57​
58export class ClipboardWriteError extends Schema.TaggedError<ClipboardWriteError>()(
59 "ClipboardWriteError",
60 {
61 target: Schema.String,
62 displayMessage: Schema.optional(Marked),
63 cause: Schema.Defect(),
64 },
65) {
66 override get message(): string {
67 if (this.displayMessage !== undefined) return m(this.displayMessage);
68 return m(msg("Failed to copy text to the clipboard."));
69 }
71​
72export class ClipboardReadUnavailableError extends Schema.TaggedError<ClipboardReadUnavailableError>()(
73 "ClipboardReadUnavailableError",
74 {
75 target: Schema.String,
76 displayMessage: Schema.optional(Marked),
77 },
78) {
79 override get message(): string {
80 if (this.displayMessage !== undefined) return m(this.displayMessage);
81 return m(msg("Clipboard API is unavailable while reading text."));
82 }
84​
85export class ClipboardReadError extends Schema.TaggedError<ClipboardReadError>()(
86 "ClipboardReadError",
87 {
88 target: Schema.String,
89 displayMessage: Schema.optional(Marked),
90 cause: Schema.Defect(),
91 },
92) {
93 override get message(): string {
94 if (this.displayMessage !== undefined) return m(this.displayMessage);
95 return m(msg("Failed to read text from the clipboard."));
96 }
98​
99function writeTextWithExecCommand(
100 value: string,
101 extraFlavors?: Readonly<Record<string, string>>,
102 requireHtml = false,
103): boolean {
104 if (typeof document === "undefined" || typeof document.execCommand !== "function") return false;
105​
106 const textarea = document.createElement("textarea");
107 textarea.value = value;
108 textarea.setAttribute("readonly", "");
109 textarea.setAttribute("aria-hidden", "true");
110 textarea.style.position = "fixed";
111 textarea.style.top = "0";
112 textarea.style.left = "0";
113 textarea.style.opacity = "0";
114 textarea.style.fontSize = "16px";
115​
116 const previouslyFocused = document.activeElement;
117 let copiedHtml = false;
118 const copy = (event: ClipboardEvent) => {
119 if (!extraFlavors || !event.clipboardData) return;
120 event.clipboardData.setData("text/plain", value);
121 for (const [type, data] of Object.entries(extraFlavors))
122 event.clipboardData.setData(type, data);
123 event.preventDefault();
124 copiedHtml = Boolean(extraFlavors["text/html"]);
125 };
126 document.body.appendChild(textarea);
127 textarea.addEventListener("copy", copy);
128 try {
129 textarea.focus({ preventScroll: true });
130 textarea.select();
131 textarea.setSelectionRange(0, value.length);
132 return document.execCommand("copy") && (!requireHtml || copiedHtml);
133 } catch {
134 return false;
135 } finally {
136 textarea.removeEventListener("copy", copy);
137 textarea.remove();
138 const restoreFocus = (previouslyFocused as { focus?: unknown } | null)?.focus;
139 if (typeof restoreFocus === "function") {
140 restoreFocus.call(previouslyFocused);
141 }
142 }
144​
145export async function writeTextToClipboard(
146 value: string,
147 target?: ClipboardTarget,
148 extraFlavors?: Readonly<Record<string, string>>,
149 options?: { requireHtml?: boolean },
150) {
151 if (typeof window === "undefined") {
152 throw new ClipboardApiUnavailableError(clipboardTargetFields(target, "unavailable"));
153 }
154​
155 if (!value) return false;
156 if (extraFlavors) {
157 extraFlavors = Object.fromEntries(
158 Object.entries(extraFlavors).filter(([type]) => type !== "text/plain"),
159 );
160 }
161 const contextFragment = extraFlavors?.[COMPOSER_CONTEXT_CLIPBOARD_MIME];
162 if (contextFragment)
163 extraFlavors = {
164 ...extraFlavors,
165 "text/html": encodeComposerContextClipboardHtml(
166 value,
167 contextFragment,
168 extraFlavors?.["text/html"],
169 ),
170 };
171​
172 if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
173 if (writeTextWithExecCommand(value, extraFlavors, options?.requireHtml)) return true;
174 throw new ClipboardApiUnavailableError(clipboardTargetFields(target, "unavailable"));
175 }
176​
177 try {
178 if (extraFlavors && typeof ClipboardItem !== "undefined" && navigator.clipboard.write) {
179 try {
180 await navigator.clipboard.write([
181 new ClipboardItem({
182 "text/plain": new Blob([value], { type: "text/plain" }),
183 ...Object.fromEntries(
184 Object.entries(extraFlavors).map(([type, data]) => [
185 type,
186 new Blob([data], { type }),
187 ]),
188 ),
189 }),
190 ]);
191 return true;
192 } catch {
193 // Safari/native bridges may accept HTML but reject Chromium's custom web flavor.
194 const html = extraFlavors["text/html"];
195 if (html) {
196 try {
197 await navigator.clipboard.write([
198 new ClipboardItem({
199 "text/plain": new Blob([value], { type: "text/plain" }),
200 "text/html": new Blob([html], { type: "text/html" }),
201 }),
202 ]);
203 return true;
204 } catch {}
205 }
206 }
207 }
208 if (options?.requireHtml) {
209 if (writeTextWithExecCommand(value, extraFlavors, true)) return true;
210 throw new Error("HTML clipboard writing is unavailable or was rejected");
211 }
212 await navigator.clipboard.writeText(value);
213 return true;
214 } catch (cause) {
215 throw new ClipboardWriteError({ ...clipboardTargetFields(target, "failure"), cause });
216 }
218​
219/** Takes a factory so the write starts inside the click while the PNG is still being made. */
220export async function writePngToClipboard(
221 png: () => Promise<Blob>,
222 target?: ClipboardTarget,
223): Promise<boolean> {
224 if (
225 typeof navigator === "undefined" ||
226 !navigator.clipboard?.write ||
227 typeof ClipboardItem === "undefined"
228 ) {
229 throw new ClipboardApiUnavailableError(clipboardTargetFields(target, "unavailable"));
230 }
231 try {
232 const image = png();
233 // The clipboard can refuse before it reads the image; its rejection then reports the copy.
234 void image.catch(() => undefined);
235 // Safari rejects a clipboard write that starts after an await, so hand it the promise.
236 await navigator.clipboard.write([new ClipboardItem({ "image/png": image })]);
237 return true;
238 } catch (cause) {
239 throw new ClipboardWriteError({ ...clipboardTargetFields(target, "failure"), cause });
240 }
242​
243export async function readTextFromClipboard(target?: ClipboardTarget): Promise<string> {
244 if (
245 typeof window === "undefined" ||
246 typeof navigator === "undefined" ||
247 !navigator.clipboard?.readText
248 ) {
249 throw new ClipboardReadUnavailableError(clipboardTargetFields(target, "unavailable"));
250 }
251​
252 try {
253 return await navigator.clipboard.readText();
254 } catch (cause) {
255 throw new ClipboardReadError({ ...clipboardTargetFields(target, "failure"), cause });
256 }
258​
259export function useCopyToClipboard<TContext = void>({
260 timeout = 2000,
261 target,
262 onCopy,
263 onError,
264 extraFlavors,
265}: {
266 timeout?: number;
267 target?: ClipboardTarget;
268 onCopy?: (ctx: TContext) => void;
269 onError?: (error: Error, ctx: TContext) => void;
270 extraFlavors?: Readonly<Record<string, string>>;
271} = {}): {
272 copyToClipboard: (
273 value: string,
274 ctx: TContext,
275 flavors?: Readonly<Record<string, string>>,
276 options?: { requireHtml?: boolean },
277 ) => void;
278 copyPngToClipboard: (png: () => Promise<Blob>, ctx: TContext) => void;
279 isCopied: boolean;
280} {
281 const [isCopied, setIsCopied] = React.useState(false);
282 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
283 const settleCopy = (write: Promise<boolean>, ctx: TContext): void => {
284 void write.then(
285 (didCopy) => {
286 if (!didCopy) return;
287 if (timeoutIdRef.current) {
288 clearTimeout(timeoutIdRef.current);
289 }
290 setIsCopied(true);
291​
292 onCopy?.(ctx);
293​
294 if (timeout !== 0) {
295 timeoutIdRef.current = setTimeout(() => {
296 setIsCopied(false);
297 timeoutIdRef.current = null;
298 }, timeout);
299 }
300 },
301 (error) => {
302 console.error(error);
303 onError?.(error, ctx);
304 },
305 );
306 };
307 const copyToClipboard = useStableCallback(
308 (
309 value: string,
310 ctx: TContext,
311 flavors: Readonly<Record<string, string>> | undefined = extraFlavors,
312 options?: { requireHtml?: boolean },
313 ): void => {
314 settleCopy(writeTextToClipboard(value, target, flavors, options), ctx);
315 },
316 );
317 const copyPngToClipboard = useStableCallback((png: () => Promise<Blob>, ctx: TContext): void => {
318 settleCopy(writePngToClipboard(png, target), ctx);
319 });
320​
321 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the copied-state reset timer on unmount
322 React.useEffect(() => {
323 return (): void => {
324 if (timeoutIdRef.current) {
325 clearTimeout(timeoutIdRef.current);
326 }
327 };
328 }, []);
329​
330 return { copyToClipboard, copyPngToClipboard, isCopied };