All files / src/features/collections CopyInviteLinkButton.tsx

100% Statements 17/17
100% Branches 8/8
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 502x                   8x 8x       8x 7x 2x 2x       3x 3x 3x 2x 2x       1x       8x                              
"use client";
 
import { useEffect, useState } from "react";
import { Button } from "@/components/ui";
 
interface CopyInviteLinkButtonProps {
  token: string;
}
 
export function CopyInviteLinkButton({ token }: CopyInviteLinkButtonProps) {
  const [copied, setCopied] = useState(false);
  const [copyFailed, setCopyFailed] = useState(false);
 
  // Auto-reset the "Copied" label after ~2s, cleaning the timer up on unmount so we
  // never call setCopied on an unmounted component (mirrors InviteForm's success reset).
  useEffect(() => {
    if (!copied) return;
    const t = setTimeout(() => setCopied(false), 2000);
    return () => clearTimeout(t);
  }, [copied]);
 
  async function handleClick() {
    const url = `${window.location.origin}/invitations/${token}`;
    try {
      await navigator.clipboard.writeText(url);
      setCopyFailed(false);
      setCopied(true);
    } catch {
      // Clipboard access can be denied (permissions, insecure context, etc.).
      // Never claim success — leave the label as "Copy link" and say so gently.
      setCopyFailed(true);
    }
  }
 
  return (
    <div className="flex flex-col items-end gap-1">
      <Button type="button" size="sm" variant="secondary" onClick={handleClick}>
        {copied ? "Copied" : "Copy link"}
      </Button>
      {/* Mounted for the component's whole life, not gated on `copied`: a live region
          must already exist when its text changes, or AT never observes the mutation
          (the InviteForm precedent — a region born with its text is frequently skipped). */}
      <div role="status" aria-live="polite" className="sr-only">
        {copied && "Invite link copied"}
        {copyFailed && "Couldn't copy — try again."}
      </div>
    </div>
  );
}