Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessageCopyButton.tsx

82 lines2.2 KB

1import { memo, useRef } from "react";
2import { CopyIcon, CheckIcon } from "lucide-react";
3import { Button } from "../ui/button";
4import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
5import { cn } from "~/lib/utils";
6import { anchoredToastManager } from "../ui/toast";
7import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
8​
9const ANCHORED_TOAST_TIMEOUT_MS = 1000;
10const onCopy = (ref: React.RefObject<HTMLButtonElement | null>) => {
11 if (ref.current) {
12 anchoredToastManager.add({
13 data: {
14 tooltipStyle: true,
15 },
16 positionerProps: {
17 anchor: ref.current,
18 },
19 timeout: ANCHORED_TOAST_TIMEOUT_MS,
20 title: "Copied!",
21 });
22 }
23};
24​
25const onCopyError = (ref: React.RefObject<HTMLButtonElement | null>, error: Error) => {
26 if (ref.current) {
27 anchoredToastManager.add({
28 data: {
29 tooltipStyle: true,
30 },
31 positionerProps: {
32 anchor: ref.current,
33 },
34 timeout: ANCHORED_TOAST_TIMEOUT_MS,
35 title: "Failed to copy",
36 description: error.message,
37 });
38 }
39};
40​
41export const MessageCopyButton = memo(function MessageCopyButton({
42 text,
43 size = "xs",
44 variant = "outline",
45 className,
46}: {
47 text: string;
48 size?: "xs" | "icon-xs";
49 variant?: "outline" | "ghost";
50 className?: string;
51}) {
52 const ref = useRef<HTMLButtonElement>(null);
53 const { copyToClipboard, isCopied } = useCopyToClipboard<void>({
54 onCopy: () => onCopy(ref),
55 onError: (error: Error) => onCopyError(ref, error),
56 timeout: ANCHORED_TOAST_TIMEOUT_MS,
57 });
58​
59 return (
60 <Tooltip>
61 <TooltipTrigger
62 render={
63 <Button
64 aria-label="Copy link"
65 disabled={isCopied}
66 onClick={() => copyToClipboard(text)}
67 ref={ref}
68 type="button"
69 size={size}
70 variant={variant}
71 className={cn("text-muted-foreground hover:text-foreground", className)}
72 />
73 }
74 >
75 {isCopied ? <CheckIcon className="size-3 text-primary" /> : <CopyIcon className="size-3" />}
76 </TooltipTrigger>
77 <TooltipPopup>
78 <p>Copy to clipboard</p>
79 </TooltipPopup>
80 </Tooltip>
81 );
82});