|
4 | 4 | COMPOSER_CONTEXT_CLIPBOARD_MIME, |
5 | 5 | encodeComposerContextClipboardHtml, |
6 | 6 | } from "@t3tools/shared/composerContextClipboard"; |
| 7 | +import { useStableCallback } from "./useStableCallback"; |
7 | 8 |
|
8 | 9 | export class ClipboardApiUnavailableError extends Schema.TaggedError<ClipboardApiUnavailableError>()( |
9 | 10 | "ClipboardApiUnavailableError", |
@@ -206,42 +207,31 @@ export function useCopyToClipboard<TContext = void>({ |
206 | 207 | } = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } { |
207 | 208 | const [isCopied, setIsCopied] = React.useState(false); |
208 | 209 | 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( |
| 210 | + // Callers pass inline onCopy/onError but key callbacks and effects on this function. |
| 211 | + const copyToClipboard = useStableCallback((value: string, ctx: TContext): void => { |
| 212 | + void writeTextToClipboard(value, target, extraFlavors).then( |
223 | 213 | (didCopy) => { |
224 | 214 | if (!didCopy) return; |
225 | 215 | if (timeoutIdRef.current) { |
226 | 216 | clearTimeout(timeoutIdRef.current); |
227 | 217 | } |
228 | 218 | setIsCopied(true); |
229 | 219 |
|
230 | | - onCopyRef.current?.(ctx); |
| 220 | + onCopy?.(ctx); |
231 | 221 |
|
232 | | - if (timeoutRef.current !== 0) { |
| 222 | + if (timeout !== 0) { |
233 | 223 | timeoutIdRef.current = setTimeout(() => { |
234 | 224 | setIsCopied(false); |
235 | 225 | timeoutIdRef.current = null; |
236 | | - }, timeoutRef.current); |
| 226 | + }, timeout); |
237 | 227 | } |
238 | 228 | }, |
239 | 229 | (error) => { |
240 | 230 | console.error(error); |
241 | | - onErrorRef.current?.(error, ctx); |
| 231 | + onError?.(error, ctx); |
242 | 232 | }, |
243 | 233 | ); |
244 | | - }, []); |
| 234 | + }); |
245 | 235 |
|
246 | 236 | React.useEffect(() => { |
247 | 237 | return (): void => { |
|
0 commit comments