aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/components/ui/copy-button.tsx
blob: a51ce90280683a373c52a7551b1bda0f9732c4d4 (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
import React, { useEffect } from "react";
import { Check, Copy } from "lucide-react";

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>
  );
}