Open History to see the last commit
1import * as React from "react";
2import * as Schema from "effect/Schema";
3
4export class ClipboardApiUnavailableError extends Schema.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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.TaggedErrorClass<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
50export async function writeTextToClipboard(value: string, target = "text") {
51 if (
52 typeof window === "undefined" ||
53 typeof navigator === "undefined" ||
54 !navigator.clipboard?.writeText
55 ) {
56 throw new ClipboardApiUnavailableError({
57 target,
58 });
59 }
60
61 if (!value) return false;
62
63 try {
64 await navigator.clipboard.writeText(value);
65 return true;
66 } catch (cause) {
67 throw new ClipboardWriteError({
68 target,
69 cause,
70 });
71 }
72}
73
74export async function readTextFromClipboard(target = "text"): Promise<string> {
75 if (
76 typeof window === "undefined" ||
77 typeof navigator === "undefined" ||
78 !navigator.clipboard?.readText
79 ) {
80 throw new ClipboardReadUnavailableError({
81 target,
82 });
83 }
84
85 try {
86 return await navigator.clipboard.readText();
87 } catch (cause) {
88 throw new ClipboardReadError({
89 target,
90 cause,
91 });
92 }
93}
94
95export function useCopyToClipboard<TContext = void>({
96 timeout = 2000,
97 target = "text",
98 onCopy,
99 onError,
100}: {
101 timeout?: number;
102 target?: string;
103 onCopy?: (ctx: TContext) => void;
104 onError?: (error: Error, ctx: TContext) => void;
105} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
106 const [isCopied, setIsCopied] = React.useState(false);
107 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
108 const onCopyRef = React.useRef(onCopy);
109 const onErrorRef = React.useRef(onError);
110 const targetRef = React.useRef(target);
111 const timeoutRef = React.useRef(timeout);
112
113 onCopyRef.current = onCopy;
114 onErrorRef.current = onError;
115 targetRef.current = target;
116 timeoutRef.current = timeout;
117
118 const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
119 void writeTextToClipboard(value, targetRef.current).then(
120 (didCopy) => {
121 if (!didCopy) return;
122 if (timeoutIdRef.current) {
123 clearTimeout(timeoutIdRef.current);
124 }
125 setIsCopied(true);
126
127 onCopyRef.current?.(ctx);
128
129 if (timeoutRef.current !== 0) {
130 timeoutIdRef.current = setTimeout(() => {
131 setIsCopied(false);
132 timeoutIdRef.current = null;
133 }, timeoutRef.current);
134 }
135 },
136 (error) => {
137 console.error(error);
138 onErrorRef.current?.(error, ctx);
139 },
140 );
141 }, []);
142
143 // Cleanup timeout on unmount
144 React.useEffect(() => {
145 return (): void => {
146 if (timeoutIdRef.current) {
147 clearTimeout(timeoutIdRef.current);
148 }
149 };
150 }, []);
151
152 return { copyToClipboard, isCopied };
153}