Open History to see the last commit
1import * as React from "react";
2import * as Schema from "effect/Schema";
3
4export class ClipboardApiUnavailableError extends Schema.TaggedError<ClipboardApiUnavailableError>()(
5 "ClipboardApiUnavailableError",
6 {
7 target: Schema.String,
8 },
9) {
10 override get message(): string {
11 return `Clipboard API is unavailable while copying ${this.target}.`;
12 }
13}
14
15export class ClipboardWriteError extends Schema.TaggedError<ClipboardWriteError>()(
16 "ClipboardWriteError",
17 {
18 target: Schema.String,
19 cause: Schema.Defect(),
20 },
21) {
22 override get message(): string {
23 return `Failed to copy ${this.target} to the clipboard.`;
24 }
25}
26
27export class ClipboardReadUnavailableError extends Schema.TaggedError<ClipboardReadUnavailableError>()(
28 "ClipboardReadUnavailableError",
29 {
30 target: Schema.String,
31 },
32) {
33 override get message(): string {
34 return `Clipboard API is unavailable while reading ${this.target}.`;
35 }
36}
37
38export class ClipboardReadError extends Schema.TaggedError<ClipboardReadError>()(
39 "ClipboardReadError",
40 {
41 target: Schema.String,
42 cause: Schema.Defect(),
43 },
44) {
45 override get message(): string {
46 return `Failed to read ${this.target} from the clipboard.`;
47 }
48}
49
50/** Copy fallback for remote web pages served over plain HTTP. */
51function writeTextWithExecCommand(value: string): boolean {
52 if (typeof document === "undefined" || typeof document.execCommand !== "function") return false;
53
54 const textarea = document.createElement("textarea");
55 textarea.value = value;
56 textarea.setAttribute("readonly", "");
57 textarea.setAttribute("aria-hidden", "true");
58 textarea.style.position = "fixed";
59 textarea.style.top = "0";
60 textarea.style.left = "0";
61 textarea.style.opacity = "0";
62 textarea.style.fontSize = "16px";
63
64 const previouslyFocused = document.activeElement;
65 document.body.appendChild(textarea);
66 try {
67 textarea.focus({ preventScroll: true });
68 textarea.select();
69 textarea.setSelectionRange(0, value.length);
70 return document.execCommand("copy");
71 } catch {
72 return false;
73 } finally {
74 textarea.remove();
75 const restoreFocus = (previouslyFocused as { focus?: unknown } | null)?.focus;
76 if (typeof restoreFocus === "function") {
77 restoreFocus.call(previouslyFocused);
78 }
79 }
80}
81
82export async function writeTextToClipboard(value: string, target = "text") {
83 if (typeof window === "undefined") {
84 throw new ClipboardApiUnavailableError({
85 target,
86 });
87 }
88
89 if (!value) return false;
90
91 if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
92 if (writeTextWithExecCommand(value)) return true;
93 throw new ClipboardApiUnavailableError({
94 target,
95 });
96 }
97
98 try {
99 await navigator.clipboard.writeText(value);
100 return true;
101 } catch (cause) {
102 throw new ClipboardWriteError({
103 target,
104 cause,
105 });
106 }
107}
108
109export async function readTextFromClipboard(target = "text"): Promise<string> {
110 if (
111 typeof window === "undefined" ||
112 typeof navigator === "undefined" ||
113 !navigator.clipboard?.readText
114 ) {
115 throw new ClipboardReadUnavailableError({
116 target,
117 });
118 }
119
120 try {
121 return await navigator.clipboard.readText();
122 } catch (cause) {
123 throw new ClipboardReadError({
124 target,
125 cause,
126 });
127 }
128}
129
130export function useCopyToClipboard<TContext = void>({
131 timeout = 2000,
132 target = "text",
133 onCopy,
134 onError,
135}: {
136 timeout?: number;
137 target?: string;
138 onCopy?: (ctx: TContext) => void;
139 onError?: (error: Error, ctx: TContext) => void;
140} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
141 const [isCopied, setIsCopied] = React.useState(false);
142 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
143 const onCopyRef = React.useRef(onCopy);
144 const onErrorRef = React.useRef(onError);
145 const targetRef = React.useRef(target);
146 const timeoutRef = React.useRef(timeout);
147
148 onCopyRef.current = onCopy;
149 onErrorRef.current = onError;
150 targetRef.current = target;
151 timeoutRef.current = timeout;
152
153 const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
154 void writeTextToClipboard(value, targetRef.current).then(
155 (didCopy) => {
156 if (!didCopy) return;
157 if (timeoutIdRef.current) {
158 clearTimeout(timeoutIdRef.current);
159 }
160 setIsCopied(true);
161
162 onCopyRef.current?.(ctx);
163
164 if (timeoutRef.current !== 0) {
165 timeoutIdRef.current = setTimeout(() => {
166 setIsCopied(false);
167 timeoutIdRef.current = null;
168 }, timeoutRef.current);
169 }
170 },
171 (error) => {
172 console.error(error);
173 onErrorRef.current?.(error, ctx);
174 },
175 );
176 }, []);
177
178 // Cleanup timeout on unmount
179 React.useEffect(() => {
180 return (): void => {
181 if (timeoutIdRef.current) {
182 clearTimeout(timeoutIdRef.current);
183 }
184 };
185 }, []);
186
187 return { copyToClipboard, isCopied };
188}