forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCopyToClipboard.ts
More file actions
181 lines (161 loc) · 4.53 KB
/
Copy pathuseCopyToClipboard.ts
File metadata and controls
181 lines (161 loc) · 4.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import * as React from "react";
import * as Schema from "effect/Schema";
export class ClipboardApiUnavailableError extends Schema.TaggedErrorClass<ClipboardApiUnavailableError>()(
"ClipboardApiUnavailableError",
{
target: Schema.String,
},
) {
override get message(): string {
return `Clipboard API is unavailable while copying ${this.target}.`;
}
}
export class ClipboardWriteError extends Schema.TaggedErrorClass<ClipboardWriteError>()(
"ClipboardWriteError",
{
target: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to copy ${this.target} to the clipboard.`;
}
}
export class ClipboardReadUnavailableError extends Schema.TaggedErrorClass<ClipboardReadUnavailableError>()(
"ClipboardReadUnavailableError",
{
target: Schema.String,
},
) {
override get message(): string {
return `Clipboard API is unavailable while reading ${this.target}.`;
}
}
export class ClipboardReadError extends Schema.TaggedErrorClass<ClipboardReadError>()(
"ClipboardReadError",
{
target: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.target} from the clipboard.`;
}
}
// Monotonic count of clipboard writes observable from inside the app: every
// successful write through this module, plus any DOM copy (Cmd+C on a
// selection, copy-on-selection handlers) once tracking is installed. An
// asynchronous copy captures the epoch when it starts and drops its result if
// the epoch moved, so a slow fetch can never stomp something copied later.
let clipboardWriteCount = 0;
export function clipboardWriteEpoch(): number {
return clipboardWriteCount;
}
let copyEventTracked = false;
export function ensureClipboardEpochTracking(): void {
if (copyEventTracked || typeof document === "undefined") {
return;
}
copyEventTracked = true;
document.addEventListener(
"copy",
() => {
clipboardWriteCount += 1;
},
true,
);
}
export async function writeTextToClipboard(value: string, target = "text") {
if (
typeof window === "undefined" ||
typeof navigator === "undefined" ||
!navigator.clipboard?.writeText
) {
throw new ClipboardApiUnavailableError({
target,
});
}
if (!value) return false;
try {
await navigator.clipboard.writeText(value);
clipboardWriteCount += 1;
return true;
} catch (cause) {
throw new ClipboardWriteError({
target,
cause,
});
}
}
export async function readTextFromClipboard(target = "text"): Promise<string> {
if (
typeof window === "undefined" ||
typeof navigator === "undefined" ||
!navigator.clipboard?.readText
) {
throw new ClipboardReadUnavailableError({
target,
});
}
try {
return await navigator.clipboard.readText();
} catch (cause) {
throw new ClipboardReadError({
target,
cause,
});
}
}
export function useCopyToClipboard<TContext = void>({
timeout = 2000,
target = "text",
onCopy,
onError,
}: {
timeout?: number;
target?: string;
onCopy?: (ctx: TContext) => void;
onError?: (error: Error, ctx: TContext) => void;
} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
const [isCopied, setIsCopied] = React.useState(false);
const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
const onCopyRef = React.useRef(onCopy);
const onErrorRef = React.useRef(onError);
const targetRef = React.useRef(target);
const timeoutRef = React.useRef(timeout);
onCopyRef.current = onCopy;
onErrorRef.current = onError;
targetRef.current = target;
timeoutRef.current = timeout;
const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
void writeTextToClipboard(value, targetRef.current).then(
(didCopy) => {
if (!didCopy) return;
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current);
}
setIsCopied(true);
onCopyRef.current?.(ctx);
if (timeoutRef.current !== 0) {
timeoutIdRef.current = setTimeout(() => {
setIsCopied(false);
timeoutIdRef.current = null;
}, timeoutRef.current);
}
},
(error) => {
console.error(error);
onErrorRef.current?.(error, ctx);
},
);
}, []);
// Cleanup timeout on unmount
React.useEffect(() => {
return (): void => {
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current);
}
};
}, []);
return { copyToClipboard, isCopied };
}