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