fix: handle clipboard errors and cleanup timeout in CopyButton
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import { Check, Copy } from "lucide-react";
|
import { Check, Copy } from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
@@ -11,17 +11,30 @@ interface CopyButtonProps {
|
|||||||
|
|
||||||
export function CopyButton({ text, className }: CopyButtonProps) {
|
export function CopyButton({ text, className }: CopyButtonProps) {
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
|
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (timeoutRef.current) clearTimeout(timeoutRef.current);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleCopy = async () => {
|
const handleCopy = async () => {
|
||||||
await navigator.clipboard.writeText(text);
|
if (copied) return;
|
||||||
setCopied(true);
|
try {
|
||||||
setTimeout(() => setCopied(false), 1500);
|
await navigator.clipboard.writeText(text);
|
||||||
|
setCopied(true);
|
||||||
|
timeoutRef.current = setTimeout(() => setCopied(false), 1500);
|
||||||
|
} catch {
|
||||||
|
// clipboard unavailable — silently no-op
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={handleCopy}
|
onClick={handleCopy}
|
||||||
title="Copy to clipboard"
|
title="Copy to clipboard"
|
||||||
|
aria-label="Copy to clipboard"
|
||||||
className={cn(
|
className={cn(
|
||||||
"inline-flex items-center justify-center rounded p-0.5 text-muted-foreground/60 transition-colors hover:text-muted-foreground",
|
"inline-flex items-center justify-center rounded p-0.5 text-muted-foreground/60 transition-colors hover:text-muted-foreground",
|
||||||
className
|
className
|
||||||
|
|||||||
Reference in New Issue
Block a user