aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/components/ui/copy-button.tsx
blob: 8d8699f822a7e71e1eef608347fbf975ba3e8847 (plain) (blame)
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
import React, { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
import { Check, Copy } from "lucide-react";

import { Button } from "./button";
import { toast } from "./use-toast";

export default function CopyBtn({
  className,
  getStringToCopy,
}: {
  className?: string;
  getStringToCopy: () => string;
}) {
  const [copyOk, setCopyOk] = React.useState(false);
  const [disabled, setDisabled] = React.useState(false);
  useEffect(() => {
    if (!navigator || !navigator.clipboard) {
      setDisabled(true);
    }
  });

  const handleClick = async () => {
    await navigator.clipboard.writeText(getStringToCopy());
    setCopyOk(true);
    setTimeout(() => {
      setCopyOk(false);
    }, 2000);
  };

  return (
    <button
      className={className}
      onClick={handleClick}
      disabled={disabled}
      title={disabled ? "Copying is only available over https" : undefined}
    >
      {copyOk ? <Check /> : <Copy />}
    </button>
  );
}

export function CopyBtnV2({
  className,
  getStringToCopy,
}: {
  className?: string;
  getStringToCopy: () => string;
}) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async (url: string) => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      toast({
        description:
          "Failed to copy link. Browsers only support copying to the clipboard from https pages.",
        variant: "destructive",
      });
    }
  };

  return (
    <Button
      size="sm"
      variant="outline"
      onClick={() => handleCopy(getStringToCopy())}
      className={cn("shrink-0", className)}
    >
      {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
    </Button>
  );
}