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

useCopyToClipboard.ts

255 lines7.0 KB

1import * as React from "react";
2import * as Schema from "effect/Schema";
3import {
4 COMPOSER_CONTEXT_CLIPBOARD_MIME,
5 encodeComposerContextClipboardHtml,
6} from "@t3tools/shared/composerContextClipboard";
7​
8export class ClipboardApiUnavailableError extends Schema.TaggedError<ClipboardApiUnavailableError>()(
9 "ClipboardApiUnavailableError",
10 {
11 target: Schema.String,
12 },
13) {
14 override get message(): string {
15 return `Clipboard API is unavailable while copying ${this.target}.`;
16 }
18​
19export class ClipboardWriteError extends Schema.TaggedError<ClipboardWriteError>()(
20 "ClipboardWriteError",
21 {
22 target: Schema.String,
23 cause: Schema.Defect(),
24 },
25) {
26 override get message(): string {
27 return `Failed to copy ${this.target} to the clipboard.`;
28 }
30​
31export class ClipboardReadUnavailableError extends Schema.TaggedError<ClipboardReadUnavailableError>()(
32 "ClipboardReadUnavailableError",
33 {
34 target: Schema.String,
35 },
36) {
37 override get message(): string {
38 return `Clipboard API is unavailable while reading ${this.target}.`;
39 }
41​
42export class ClipboardReadError extends Schema.TaggedError<ClipboardReadError>()(
43 "ClipboardReadError",
44 {
45 target: Schema.String,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return `Failed to read ${this.target} from the clipboard.`;
51 }
53​
54function writeTextWithExecCommand(
55 value: string,
56 extraFlavors?: Readonly<Record<string, string>>,
57): boolean {
58 if (typeof document === "undefined" || typeof document.execCommand !== "function") return false;
59​
60 const textarea = document.createElement("textarea");
61 textarea.value = value;
62 textarea.setAttribute("readonly", "");
63 textarea.setAttribute("aria-hidden", "true");
64 textarea.style.position = "fixed";
65 textarea.style.top = "0";
66 textarea.style.left = "0";
67 textarea.style.opacity = "0";
68 textarea.style.fontSize = "16px";
69​
70 const previouslyFocused = document.activeElement;
71 const copy = (event: ClipboardEvent) => {
72 if (!extraFlavors || !event.clipboardData) return;
73 event.clipboardData.setData("text/plain", value);
74 for (const [type, data] of Object.entries(extraFlavors))
75 event.clipboardData.setData(type, data);
76 event.preventDefault();
77 };
78 document.body.appendChild(textarea);
79 textarea.addEventListener("copy", copy);
80 try {
81 textarea.focus({ preventScroll: true });
82 textarea.select();
83 textarea.setSelectionRange(0, value.length);
84 return document.execCommand("copy");
85 } catch {
86 return false;
87 } finally {
88 textarea.removeEventListener("copy", copy);
89 textarea.remove();
90 const restoreFocus = (previouslyFocused as { focus?: unknown } | null)?.focus;
91 if (typeof restoreFocus === "function") {
92 restoreFocus.call(previouslyFocused);
93 }
94 }
96​
97export async function writeTextToClipboard(
98 value: string,
99 target = "text",
100 extraFlavors?: Readonly<Record<string, string>>,
101) {
102 if (typeof window === "undefined") {
103 throw new ClipboardApiUnavailableError({
104 target,
105 });
106 }
107​
108 if (!value) return false;
109 if (extraFlavors) {
110 extraFlavors = Object.fromEntries(
111 Object.entries(extraFlavors).filter(([type]) => type !== "text/plain"),
112 );
113 }
114 const contextFragment = extraFlavors?.[COMPOSER_CONTEXT_CLIPBOARD_MIME];
115 if (contextFragment)
116 extraFlavors = {
117 ...extraFlavors,
118 "text/html": encodeComposerContextClipboardHtml(
119 value,
120 contextFragment,
121 extraFlavors?.["text/html"],
122 ),
123 };
124​
125 if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
126 if (writeTextWithExecCommand(value, extraFlavors)) return true;
127 throw new ClipboardApiUnavailableError({
128 target,
129 });
130 }
131​
132 try {
133 if (extraFlavors && typeof ClipboardItem !== "undefined" && navigator.clipboard.write) {
134 try {
135 await navigator.clipboard.write([
136 new ClipboardItem({
137 "text/plain": new Blob([value], { type: "text/plain" }),
138 ...Object.fromEntries(
139 Object.entries(extraFlavors).map(([type, data]) => [
140 type,
141 new Blob([data], { type }),
142 ]),
143 ),
144 }),
145 ]);
146 return true;
147 } catch {
148 // Safari/native bridges may accept HTML but reject Chromium's custom web flavor.
149 const html = extraFlavors["text/html"];
150 if (html) {
151 try {
152 await navigator.clipboard.write([
153 new ClipboardItem({
154 "text/plain": new Blob([value], { type: "text/plain" }),
155 "text/html": new Blob([html], { type: "text/html" }),
156 }),
157 ]);
158 return true;
159 } catch {}
160 }
161 }
162 }
163 await navigator.clipboard.writeText(value);
164 return true;
165 } catch (cause) {
166 throw new ClipboardWriteError({
167 target,
168 cause,
169 });
170 }
172​
173export async function readTextFromClipboard(target = "text"): Promise<string> {
174 if (
175 typeof window === "undefined" ||
176 typeof navigator === "undefined" ||
177 !navigator.clipboard?.readText
178 ) {
179 throw new ClipboardReadUnavailableError({
180 target,
181 });
182 }
183​
184 try {
185 return await navigator.clipboard.readText();
186 } catch (cause) {
187 throw new ClipboardReadError({
188 target,
189 cause,
190 });
191 }
193​
194export function useCopyToClipboard<TContext = void>({
195 timeout = 2000,
196 target = "text",
197 onCopy,
198 onError,
199 extraFlavors,
200}: {
201 timeout?: number;
202 target?: string;
203 onCopy?: (ctx: TContext) => void;
204 onError?: (error: Error, ctx: TContext) => void;
205 extraFlavors?: Readonly<Record<string, string>>;
206} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
207 const [isCopied, setIsCopied] = React.useState(false);
208 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
209 const onCopyRef = React.useRef(onCopy);
210 const onErrorRef = React.useRef(onError);
211 const targetRef = React.useRef(target);
212 const timeoutRef = React.useRef(timeout);
213​
214 onCopyRef.current = onCopy;
215 onErrorRef.current = onError;
216 const extraFlavorsRef = React.useRef(extraFlavors);
217 targetRef.current = target;
218 timeoutRef.current = timeout;
219 extraFlavorsRef.current = extraFlavors;
220​
221 const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
222 void writeTextToClipboard(value, targetRef.current, extraFlavorsRef.current).then(
223 (didCopy) => {
224 if (!didCopy) return;
225 if (timeoutIdRef.current) {
226 clearTimeout(timeoutIdRef.current);
227 }
228 setIsCopied(true);
229​
230 onCopyRef.current?.(ctx);
231​
232 if (timeoutRef.current !== 0) {
233 timeoutIdRef.current = setTimeout(() => {
234 setIsCopied(false);
235 timeoutIdRef.current = null;
236 }, timeoutRef.current);
237 }
238 },
239 (error) => {
240 console.error(error);
241 onErrorRef.current?.(error, ctx);
242 },
243 );
244 }, []);
245​
246 React.useEffect(() => {
247 return (): void => {
248 if (timeoutIdRef.current) {
249 clearTimeout(timeoutIdRef.current);
250 }
251 };
252 }, []);
253​
254 return { copyToClipboard, isCopied };