πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(ui): one copy-to-clipboard interaction everywhere (#1254)
Goldflage3e84843f91e
diff --git a/client/src/app/[site]/components/SubHeader/ShareExportButton.test.tsx b/client/src/app/[site]/components/SubHeader/ShareExportButton.test.tsxnew file mode 100644index 000000000..52ec45b2b--- /dev/null+++ b/client/src/app/[site]/components/SubHeader/ShareExportButton.test.tsx@@ -0,0 +1,143 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { TooltipProvider } from "@/components/ui/tooltip";++import { ShareExportButton } from "./ShareExportButton";++const mocks = vi.hoisted(() => ({+ revoke: vi.fn<(siteId: number) => Promise<unknown>>(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+ writeText: vi.fn<(text: string) => Promise<void>>(),+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string) => message,+}));++vi.mock("next/navigation", () => ({+ useParams: () => ({ site: "7" }),+}));++vi.mock("../../../../api/admin/hooks/usePrivateLink", () => ({+ useGetPrivateLinkConfig: () => ({ data: { privateLinkKey: "k3y" }, isLoading: false }),+ useGeneratePrivateLinkKey: () => ({ mutate: vi.fn(), isPending: false }),+ useRevokePrivateLinkKey: () => ({ mutateAsync: mocks.revoke, isPending: false }),+}));++vi.mock("../../../../lib/auth", () => ({+ authClient: { useSession: () => ({ data: { user: { id: "u1" } } }) },+}));++vi.mock("../../../../lib/store", () => ({+ useStore: () => ({ site: "7", time: { mode: "day" }, filters: [] }),+ getTimezone: () => "UTC",+}));++vi.mock("../../../../lib/subscription/useStripeSubscription", () => ({+ useStripeSubscription: () => ({ data: { planName: "pro" } }),+}));++vi.mock("./Export", () => ({ exportCsv: vi.fn(), exportPdf: vi.fn() }));++vi.mock("@/components/ui/sonner", () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}));++const LINK = `${window.location.protocol}//${window.location.host}/7/k3y`;++function openShareMenu() {+ render(+ <TooltipProvider>+ <ShareExportButton />+ </TooltipProvider>+ );+ const trigger = document.querySelector<HTMLButtonElement>('[aria-haspopup="menu"]')!;+ fireEvent.keyDown(trigger, { key: "Enter" });+}++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Object.defineProperty(navigator, "clipboard", { value: { writeText: mocks.writeText }, configurable: true });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ Reflect.deleteProperty(navigator, "clipboard");+});++describe("ShareExportButton private link", () => {+ it("copies the link without a toast when the copy succeeds", async () => {+ mocks.writeText.mockResolvedValue(undefined);+ openShareMenu();++ fireEvent.click(screen.getByRole("button", { name: "Copy link" }));++ await waitFor(() => expect(screen.getByRole("status").textContent).toBe("Copied"));+ expect(mocks.writeText).toHaveBeenCalledWith(LINK);+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(mocks.toastError).not.toHaveBeenCalled();+ });++ it("reports a failed copy instead of claiming success", async () => {+ mocks.writeText.mockRejectedValue(new DOMException("Write permission denied.", "NotAllowedError"));+ openShareMenu();++ // jsdom has no document.execCommand, so the fallback fails too.+ fireEvent.click(screen.getByRole("button", { name: "Copy link" }));++ await waitFor(() =>+ expect(mocks.toastError).toHaveBeenCalledWith("Couldn't copy the link. Select it and copy it manually.")+ );+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ });++ it("confirms before revoking and reports success only once the revoke lands", async () => {+ let finishRevoke!: () => void;+ mocks.revoke.mockImplementation(+ () =>+ new Promise(resolve => {+ finishRevoke = () => resolve({ privateLinkKey: null });+ })+ );+ openShareMenu();++ fireEvent.click(screen.getByRole("button", { name: "Revoke this link" }));+ expect(mocks.revoke).not.toHaveBeenCalled();++ const dialog = await screen.findByRole("alertdialog", { name: "Revoke this private link?" });+ fireEvent.click(screen.getByRole("button", { name: "Revoke link" }));++ expect(mocks.revoke).toHaveBeenCalledWith(7);+ expect(mocks.toastSuccess).not.toHaveBeenCalled();++ finishRevoke();++ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Private link revoked"));+ await waitFor(() => expect(dialog.isConnected).toBe(false));+ expect(mocks.toastError).not.toHaveBeenCalled();+ });++ it("keeps the confirmation open and reports the error when the revoke fails", async () => {+ mocks.revoke.mockRejectedValue(new Error("Site not found"));+ openShareMenu();++ fireEvent.click(screen.getByRole("button", { name: "Revoke this link" }));+ await screen.findByRole("alertdialog", { name: "Revoke this private link?" });+ fireEvent.click(screen.getByRole("button", { name: "Revoke link" }));++ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Site not found"));+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(screen.getByRole("alertdialog", { name: "Revoke this private link?" })).toBeTruthy();+ });+});diff --git a/client/src/app/[site]/components/SubHeader/ShareExportButton.tsx b/client/src/app/[site]/components/SubHeader/ShareExportButton.tsxindex e23be5a84..c4f7e8ce2 100644--- a/client/src/app/[site]/components/SubHeader/ShareExportButton.tsx+++ b/client/src/app/[site]/components/SubHeader/ShareExportButton.tsx@@ -1,15 +1,26 @@"use client";-import { Copy, Download, FileArchive, FileText, Loader2, Share } from "lucide-react";+import { Download, FileArchive, FileText, Loader2, Share } from "lucide-react";import { useExtracted } from "next-intl";import { useParams } from "next/navigation";-import { useState } from "react";+import { useRef, useState } from "react";+import { CopyButton } from "@/components/interior/copy-button";import { toast } from "@/components/ui/sonner";import {useGeneratePrivateLinkKey,useGetPrivateLinkConfig,useRevokePrivateLinkKey,} from "../../../../api/admin/hooks/usePrivateLink";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "../../../../components/ui/alert-dialog";import { Button } from "../../../../components/ui/button";import {DropdownMenu,@@ -34,12 +45,29 @@ export function ShareExportButton() {const [isExportingCsv, setIsExportingCsv] = useState(false);const [isExportingPdf, setIsExportingPdf] = useState(false);+ const [confirmRevoke, setConfirmRevoke] = useState(false);+ const shareTriggerRef = useRef<HTMLButtonElement>(null);const { site, time, filters } = useStore();const { data: subscription } = useStripeSubscription();const { data: privateLink, isLoading: isLoadingPrivateLink } = useGetPrivateLinkConfig(canShare ? siteId : 0);const { mutate: generatePrivateLinkKey, isPending: isGeneratingPrivateLink } = useGeneratePrivateLinkKey();- const { mutate: revokePrivateLinkKey } = useRevokePrivateLinkKey();+ const { mutateAsync: revokePrivateLinkKey, isPending: isRevokingPrivateLink } = useRevokePrivateLinkKey();++ const privateLinkUrl = privateLink?.privateLinkKey+ ? `${globalThis.location.protocol}//${globalThis.location.host}/${siteId}/${privateLink.privateLinkKey}`+ : "";++ const handleRevokePrivateLink = async () => {+ try {+ await revokePrivateLinkKey(siteId);+ toast.success(t("Private link revoked"));+ setConfirmRevoke(false);+ } catch (error) {+ console.error("Failed to revoke private link:", error);+ toast.error(error instanceof Error ? error.message : t("Failed to revoke the private link"));+ }+ };const handleExportPdf = async () => {if (!site) {@@ -89,7 +117,7 @@ export function ShareExportButton() {<Tooltip><TooltipTrigger asChild><DropdownMenuTrigger asChild>- <Button variant="secondary" size="icon" className="h-8 w-8">+ <Button ref={shareTriggerRef} variant="secondary" size="icon" className="h-8 w-8">{isExporting ? (<Loader2 className="h-4 w-4 animate-spin" />) : canShare ? (@@ -112,35 +140,28 @@ export function ShareExportButton() {{isGeneratingPrivateLink ? t("Generating...") : t("Generate Private Link")}</Button>)}- {privateLink?.privateLinkKey && (+ {privateLinkUrl && (<><div className="flex items-center">- <Input- value={`${globalThis.location.protocol}//${globalThis.location.host}/${siteId}/${privateLink?.privateLinkKey}`}- readOnly- className="rounded-r-none bg-white dark:bg-neutral-900"- />- <Button- size="icon"- onClick={() => {- const fullUrl = `${globalThis.location.protocol}//${globalThis.location.host}/${siteId}/${privateLink?.privateLinkKey}`;- navigator.clipboard.writeText(fullUrl);- toast.success(t("Copied to clipboard"));- }}+ <Input value={privateLinkUrl} readOnly className="rounded-r-none bg-white dark:bg-neutral-900" />+ <CopyButton+ iconOnly+ variant="default"+ value={privateLinkUrl}+ label={t("Copy link")}className="w-10 rounded-l-none"- >- <Copy />- </Button>+ onError={() => toast.error(t("Couldn't copy the link. Select it and copy it manually."))}+ /></div>- <div- className="text-xs text-neutral-500 dark:text-neutral-500 mt-1 cursor-pointer hover:text-neutral-600 dark:hover:text-neutral-400"- onClick={() => {- revokePrivateLinkKey(siteId);- toast.success(t("Private link revoked"));- }}+ {/* Opens the confirmation outside the menu, which closes as focus moves to it. */}+ <Button+ variant="link"+ size="xs"+ className="mt-1 h-auto self-start px-0 font-normal text-neutral-500 hover:text-neutral-600 dark:text-neutral-500 dark:hover:text-neutral-400"+ onClick={() => setConfirmRevoke(true)}>{t("Revoke this link")}- </div>+ </Button></>)}<span className="text-xs text-neutral-600 dark:text-neutral-300 mt-2">@@ -162,6 +183,38 @@ export function ShareExportButton() {</DropdownMenuItem></DropdownMenuContent></DropdownMenu>++ <AlertDialog open={confirmRevoke} onOpenChange={setConfirmRevoke}>+ <AlertDialogContent+ onCloseAutoFocus={event => {+ // The menu that held "Revoke this link" is gone; return focus to the share button.+ event.preventDefault();+ shareTriggerRef.current?.focus();+ }}+ >+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Revoke this private link?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ "Anyone with the link loses access to this dashboard right away. You can generate a new link afterwards."+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isRevokingPrivateLink}>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={isRevokingPrivateLink}+ onClick={event => {+ event.preventDefault();+ void handleRevokePrivateLink();+ }}+ >+ {isRevokingPrivateLink ? t("Revoking...") : t("Revoke link")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsxindex 8f8342d38..0a9a79ccf 100644--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx@@ -3,6 +3,7 @@import { useExtracted } from "next-intl";import { ErrorEvent } from "@/api/analytics/endpoints";import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetErrorEvents";+import { CopyButton } from "@/components/interior/copy-button";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";@@ -113,16 +114,11 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {</Link></div><div className="flex items-center gap-2">--{errorEvent.user_id && (<Tooltip><TooltipTrigger asChild><Link href={`/${site}/user/${encodeURIComponent(errorEvent.user_id)}`}>- <Avatar- size={24}- id={errorEvent.user_id}- />+ <Avatar size={24} id={errorEvent.user_id} /></Link></TooltipTrigger><TooltipContent>User ID: {errorEvent.user_id}</TooltipContent>@@ -172,9 +168,19 @@ function ErrorEventItem({ errorEvent }: { errorEvent: ErrorEvent }) {</div></div>)}- <pre className="text-xs text-neutral-900 dark:text-neutral-100 bg-neutral-200 dark:bg-neutral-800 p-2 rounded overflow-x-auto whitespace-pre-wrap wrap-break-word">- {errorEvent.stack}- </pre>+ <div className="relative">+ <pre className="text-xs text-neutral-900 dark:text-neutral-100 bg-neutral-200 dark:bg-neutral-800 p-2 pr-9 rounded overflow-x-auto whitespace-pre-wrap wrap-break-word">+ {errorEvent.stack}+ </pre>+ <CopyButton+ iconOnly+ size="xs"+ tooltip+ value={errorEvent.stack}+ label={t("Copy stack trace")}+ className="absolute right-1 top-1"+ />+ </div></div></div></div>@@ -311,7 +317,10 @@ export function ErrorDetails({ errorMessage }: ErrorDetailsProps) {{totalCount > 0 && (<div className="text-center text-xs text-neutral-500 dark:text-neutral-500 mt-2">- {t("Showing {shown} of {total} error events", { shown: String(allErrorEvents.length), total: String(totalCount) })}+ {t("Showing {shown} of {total} error events", {+ shown: String(allErrorEvents.length),+ total: String(totalCount),+ })}</div>)}</div>diff --git a/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsxindex 32d59bccf..287712167 100644--- a/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx+++ b/client/src/app/[site]/events/components/EventLog/EventDetailsSheet.tsx@@ -7,6 +7,7 @@ import Link from "next/link";import { Event } from "../../../../../api/analytics/endpoints";import { fetchSessions } from "../../../../../api/analytics/endpoints/sessions";import { EventTypeIcon } from "../../../../../components/EventIcons";+import { CopyButton } from "../../../../../components/interior/copy-button";import { SessionCard, SessionCardSkeleton } from "../../../../../components/Sessions/SessionCard";import { Sheet, SheetContent, SheetHeader, SheetTitle } from "../../../../../components/ui/sheet";import { hour12, userLocale } from "../../../../../lib/dateTimeUtils";@@ -29,6 +30,8 @@ interface EventDetailsSheetProps {export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDetailsSheetProps) {const t = useExtracted();const selectedEventProperties = event ? parseEventProperties(event) : {};+ const propertiesJson =+ Object.keys(selectedEventProperties).length > 0 ? JSON.stringify(selectedEventProperties, null, 2) : "";const sessionQuery = useQuery({queryKey: ["event-session", site, event?.session_id],@@ -47,7 +50,7 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDetaconst timestamp = DateTime.fromSQL(event?.timestamp || "", { zone: "utc" }).setLocale(userLocale)- .setZone(getTimezone())+ .setZone(getTimezone());return (<Sheet@@ -75,9 +78,7 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta<div className="grid grid-cols-1 gap-1 text-sm"><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Timestamp")}</span>- <span>- {timestamp.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")}- </span>+ <span>{timestamp.toFormat(hour12 ? "MMM d, h:mm:ss a" : "dd MMM, HH:mm:ss")}</span></div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("User")}</span>@@ -120,14 +121,16 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta<span className="text-neutral-500 dark:text-neutral-400">{t("Browser")}</span><span className="flex items-center gap-1"><Browser browser={event.browser || "Unknown"} />- {event.browser || t("Unknown")}{event.browser_version ? ` ${event.browser_version}` : ""}+ {event.browser || t("Unknown")}+ {event.browser_version ? ` ${event.browser_version}` : ""}</span></div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Operating System")}</span><span className="flex items-center gap-1"><OperatingSystem os={event.operating_system || ""} />- {event.operating_system || t("Unknown")}{event.operating_system_version ? ` ${event.operating_system_version}` : ""}+ {event.operating_system || t("Unknown")}+ {event.operating_system_version ? ` ${event.operating_system_version}` : ""}</span></div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5">@@ -139,7 +142,11 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta</div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Screen")}</span>- <span>{event.screen_width && event.screen_height ? `${event.screen_width} Γ ${event.screen_height}` : "-"}</span>+ <span>+ {event.screen_width && event.screen_height+ ? `${event.screen_width} Γ ${event.screen_height}`+ : "-"}+ </span></div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Language")}</span>@@ -147,33 +154,54 @@ export function EventDetailsSheet({ open, onOpenChange, event, site }: EventDeta</div><div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Location")}</span>- <span className="flex items-center gap-1">{event.country && <CountryFlag country={event.country} />}{[event.city, getRegionName(event.region), getCountryName(event.country)].filter(Boolean).join(", ") || "-"}</span>+ <span className="flex items-center gap-1">+ {event.country && <CountryFlag country={event.country} />}+ {[event.city, getRegionName(event.region), getCountryName(event.country)]+ .filter(Boolean)+ .join(", ") || "-"}+ </span></div>- {(isFinite(event.lat) && isFinite(event.lon)) && (+ {isFinite(event.lat) && isFinite(event.lon) && (<div className="flex items-center justify-between border-b border-neutral-50 dark:border-neutral-850 pb-1.5"><span className="text-neutral-500 dark:text-neutral-400">{t("Coordinates")}</span>- <span>{event.lat.toFixed(4)}, {event.lon.toFixed(4)}</span>+ <span>+ {event.lat.toFixed(4)}, {event.lon.toFixed(4)}+ </span></div>)}</div></div></div>- {Object.keys(selectedEventProperties).length > 0 &&+ {propertiesJson && (<div><div className="text-sm font-medium mb-2">{t("Properties")}</div>- <pre className="text-xs bg-neutral-50 dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-md p-3 overflow-auto max-h-64">- {JSON.stringify(selectedEventProperties, null, 2)}- </pre>+ <div className="relative">+ <pre className="text-xs bg-neutral-50 dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-md p-3 pr-10 overflow-auto max-h-64">+ {propertiesJson}+ </pre>+ <CopyButton+ iconOnly+ size="xs"+ tooltip+ value={propertiesJson}+ label={t("Copy properties as JSON")}+ className="absolute right-2 top-2"+ />+ </div></div>- }+ )}<div><div className="text-sm font-medium mb-2">{t("Session")}</div>{sessionQuery.isLoading ? (<SessionCardSkeleton count={1} />) : sessionQuery.data ? (- <SessionCard session={sessionQuery.data} expandedByDefault highlightedEventTimestamp={timestamp.toMillis()} />+ <SessionCard+ session={sessionQuery.data}+ expandedByDefault+ highlightedEventTimestamp={timestamp.toMillis()}+ />) : (<div className="text-xs text-neutral-500 dark:text-neutral-400">{t("No session data")}</div>)}diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsxnew file mode 100644index 000000000..92d0d4809--- /dev/null+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx@@ -0,0 +1,141 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { FeatureFlag } from "@/api/analytics/endpoints";+import { TooltipProvider } from "@/components/ui/tooltip";++import { FeatureFlagTable } from "./FeatureFlagTable";++const mocks = vi.hoisted(() => ({+ deleteFlag: vi.fn<(flagId: number) => Promise<unknown>>(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+ writeText: vi.fn<(text: string) => Promise<void>>(),+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>+ values ? message.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? `{${key}}`)) : message,+ useLocale: () => "en",+}));++vi.mock("@/api/analytics/hooks/featureFlags/useFeatureFlags", () => ({+ useDeleteFeatureFlag: () => ({ mutateAsync: mocks.deleteFlag, isPending: false }),+ useUpdateFeatureFlag: () => ({ mutate: vi.fn(), isPending: false }),+}));++vi.mock("./FeatureFlagDialog", () => ({ FeatureFlagDialog: () => null }));++vi.mock("@/lib/store", () => ({ getTimezone: () => "UTC" }));++vi.mock("@/components/ui/sonner", () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}));++const flag: FeatureFlag = {+ flagId: 42,+ siteId: 1,+ key: "new-checkout",+ description: null,+ enabled: true,+ runtime: "client",+ flagType: "boolean",+ payload: null,+ variants: [],+ rolloutPercentage: 50,+ rules: [],+ conditionSets: [{ rules: [], rolloutPercentage: 50 }],+ version: 3,+ createdAt: "2026-09-01 10:00:00",+ updatedAt: "2026-09-20 10:00:00",+ stats: [],+};++function renderTable() {+ render(+ <TooltipProvider>+ <FeatureFlagTable flags={[flag]} />+ </TooltipProvider>+ );+}++function chooseDelete() {+ fireEvent.keyDown(screen.getByRole("button", { name: "Actions" }), { key: "Enter" });+ fireEvent.click(screen.getByRole("menuitem", { name: "Delete" }));+}++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Object.defineProperty(navigator, "clipboard", { value: { writeText: mocks.writeText }, configurable: true });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ Reflect.deleteProperty(navigator, "clipboard");+});++describe("FeatureFlagTable", () => {+ it("copies a flag's key from its row", async () => {+ mocks.writeText.mockResolvedValue(undefined);+ renderTable();++ fireEvent.click(screen.getByRole("button", { name: "Copy flag key" }));++ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith("new-checkout"));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Copy flag key" }).getAttribute("data-status")).toBe("copied")+ );+ });++ it("asks in a dialog, not window.confirm, and deletes only once confirmed", async () => {+ const confirmSpy = vi.spyOn(window, "confirm");+ mocks.deleteFlag.mockResolvedValue(undefined);+ renderTable();++ chooseDelete();++ const dialog = await screen.findByRole("alertdialog", { name: "Delete this feature flag?" });+ expect(within(dialog).getByText('"new-checkout" will be permanently deleted. This cannot be undone.')).toBeTruthy();+ expect(mocks.deleteFlag).not.toHaveBeenCalled();+ expect(confirmSpy).not.toHaveBeenCalled();++ fireEvent.click(within(dialog).getByRole("button", { name: "Delete flag" }));++ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Feature flag deleted"));+ expect(mocks.deleteFlag).toHaveBeenCalledWith(42);+ await waitFor(() => expect(dialog.isConnected).toBe(false));+ });++ it("deletes nothing when the dialog is cancelled", async () => {+ renderTable();++ chooseDelete();+ const dialog = await screen.findByRole("alertdialog", { name: "Delete this feature flag?" });+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));++ await waitFor(() => expect(dialog.isConnected).toBe(false));+ expect(mocks.deleteFlag).not.toHaveBeenCalled();+ });++ it("keeps the dialog open and reports the error when the delete fails", async () => {+ mocks.deleteFlag.mockRejectedValue(new Error("Flag is in use by an experiment"));+ renderTable();++ chooseDelete();+ const dialog = await screen.findByRole("alertdialog", { name: "Delete this feature flag?" });+ fireEvent.click(within(dialog).getByRole("button", { name: "Delete flag" }));++ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Flag is in use by an experiment"));+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(dialog.isConnected).toBe(true);+ });+});diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsxindex 936a69aff..68d577ec1 100644--- a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx@@ -2,6 +2,17 @@import { useDeleteFeatureFlag, useUpdateFeatureFlag } from "@/api/analytics/hooks/featureFlags/useFeatureFlags";import type { FeatureFlag } from "@/api/analytics/endpoints";+import { CopyButton } from "@/components/interior/copy-button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import {@@ -17,6 +28,7 @@ import { toast } from "@/components/ui/sonner";import { cn } from "@/lib/utils";import { getTimezone } from "@/lib/store";import {+ type CellContext,createColumnHelper,flexRender,getCoreRowModel,@@ -27,7 +39,7 @@ import {import { Edit2, MoreHorizontal, Trash2 } from "lucide-react";import { DateTime } from "luxon";import { useExtracted } from "next-intl";-import { useState } from "react";+import { useRef, useState } from "react";import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";import { formatFlagValue, getConditionSetPayload } from "../lib/form";import { useFlagTypeLabel, useRuntimeLabel } from "../lib/labels";@@ -162,12 +174,14 @@ function RowActions({ flag }: { flag: FeatureFlag }) {const t = useExtracted();const deleteMutation = useDeleteFeatureFlag();const [editOpen, setEditOpen] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const actionsTriggerRef = useRef<HTMLButtonElement>(null);const handleDelete = async () => {- if (!window.confirm(t("Delete this feature flag?"))) return;try {await deleteMutation.mutateAsync(flag.flagId);toast.success(t("Feature flag deleted"));+ setConfirmDelete(false);} catch (error) {toast.error(error instanceof Error ? error.message : t("Failed to delete feature flag"));}@@ -177,7 +191,7 @@ function RowActions({ flag }: { flag: FeatureFlag }) {<><DropdownMenu><DropdownMenuTrigger asChild>- <Button size="smIcon" variant="ghost" aria-label={t("Actions")}>+ <Button ref={actionsTriggerRef} size="smIcon" variant="ghost" aria-label={t("Actions")}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>@@ -189,7 +203,7 @@ function RowActions({ flag }: { flag: FeatureFlag }) {<DropdownMenuSeparator /><DropdownMenuItemdisabled={deleteMutation.isPending}- onSelect={handleDelete}+ onSelect={() => setConfirmDelete(true)}className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"><Trash2 className="mr-2 h-4 w-4" />@@ -198,10 +212,71 @@ function RowActions({ flag }: { flag: FeatureFlag }) {</DropdownMenuContent></DropdownMenu><FeatureFlagDialog flag={flag} open={editOpen} onOpenChange={setEditOpen} />+ <AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>+ <AlertDialogContent+ onCloseAutoFocus={event => {+ // Back to the row's actions button, as window.confirm did.+ event.preventDefault();+ actionsTriggerRef.current?.focus();+ }}+ >+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Delete this feature flag?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('"{key}" will be permanently deleted. This cannot be undone.', { key: flag.key })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleteMutation.isPending}>{t("Cancel")}</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ disabled={deleteMutation.isPending}+ onClick={event => {+ event.preventDefault();+ void handleDelete();+ }}+ >+ {deleteMutation.isPending ? t("Deleting...") : t("Delete flag")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></>);}+// Cells with state are module-level components: flexRender mounts a cell function+// as a component, and the inline ones below are recreated on every table render,+// which would reset a copy check or close an open dialog.+function FlagKeyCell({ row }: CellContext<FeatureFlag, string>) {+ const t = useExtracted();+ const flag = row.original;++ return (+ <div className="flex items-center gap-2">+ <span className="font-mono text-sm font-medium">{flag.key}</span>+ <Badge variant="secondary">v{flag.version}</Badge>+ {/* Shown on row hover or focus where hover exists; always shown on touch screens. */}+ <CopyButton+ iconOnly+ size="xs"+ tooltip+ value={flag.key}+ label={t("Copy flag key")}+ className="-ml-1 [@media(hover:hover)]:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[status=copied]:opacity-100 data-[status=error]:opacity-100"+ />+ </div>+ );+}++function RowActionsCell({ row }: CellContext<FeatureFlag, unknown>) {+ return (+ <div className="flex justify-end">+ <RowActions flag={row.original} />+ </div>+ );+}+export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {const t = useExtracted();const getRuntimeLabel = useRuntimeLabel();@@ -238,12 +313,7 @@ export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {columnHelper.accessor("key", {id: "key",header: ({ column }) => <SortHeader column={column}>{t("Flag")}</SortHeader>,- cell: info => (- <div className="flex items-center gap-2">- <span className="font-mono text-sm font-medium">{info.getValue()}</span>- <Badge variant="secondary">v{info.row.original.version}</Badge>- </div>- ),+ cell: FlagKeyCell,}),columnHelper.accessor("enabled", {id: "enabled",@@ -304,11 +374,7 @@ export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {columnHelper.display({id: "actions",header: () => <span className="sr-only">{t("Actions")}</span>,- cell: info => (- <div className="flex justify-end">- <RowActions flag={info.row.original} />- </div>- ),+ cell: RowActionsCell,}),];diff --git a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx b/client/src/app/[site]/user/[userId]/components/UserHeader.tsxindex c9c4176e0..f21b77360 100644--- a/client/src/app/[site]/user/[userId]/components/UserHeader.tsx+++ b/client/src/app/[site]/user/[userId]/components/UserHeader.tsx@@ -1,12 +1,13 @@"use client";-import { Check, Clock, Copy } from "lucide-react";+import { Clock } from "lucide-react";import { DateTime } from "luxon";import { useExtracted, useLocale } from "next-intl";-import { useRef, useState } from "react";import { UserInfo } from "../../../../../api/analytics/endpoints";import { Avatar } from "../../../../../components/Avatar";import { IdentifiedBadge } from "../../../../../components/IdentifiedBadge";+import { CopyAnnouncement, CopyStatusIcon } from "../../../../../components/interior/copy-button";+import { useCopyToClipboard } from "../../../../../components/interior/use-copy-to-clipboard";import { Skeleton } from "../../../../../components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";import { useDateTimeFormat } from "../../../../../hooks/useDateTimeFormat";@@ -20,38 +21,36 @@ const ONLINE_WINDOW_SECONDS = 300;function CopyUserId({ value }: { value: string }) {const t = useExtracted();- const [copied, setCopied] = useState(false);- const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);-- const handleCopy = async () => {- try {- await navigator.clipboard.writeText(value);- setCopied(true);- if (resetTimer.current) clearTimeout(resetTimer.current);- resetTimer.current = setTimeout(() => setCopied(false), 1500);- } catch {- // Clipboard unavailable (permissions/insecure context); leave the id selectable- }- };+ const { copy, status } = useCopyToClipboard();return (- <Tooltip>- <TooltipTrigger asChild>- <button- type="button"- onClick={handleCopy}- className="inline-flex min-w-0 items-center gap-1 rounded-sm font-mono text-neutral-500 transition-colors hover:text-neutral-800 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-200"- >- <span className="max-w-[160px] truncate sm:max-w-[260px]">{value}</span>- {copied ? (- <Check className="h-3 w-3 shrink-0 text-emerald-500" />- ) : (- <Copy className="h-3 w-3 shrink-0 text-neutral-400 dark:text-neutral-500" />- )}- </button>- </TooltipTrigger>- <TooltipContent>{copied ? t("Copied!") : t("Copy user ID")}</TooltipContent>- </Tooltip>+ <>+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onClick={() => void copy(value)}+ aria-label={t("Copy user ID {id}", { id: value })}+ className="inline-flex min-w-0 items-center gap-1 rounded-sm font-mono text-neutral-500 transition-colors hover:text-neutral-800 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-400 dark:text-neutral-400 dark:hover:text-neutral-200"+ >+ <span className="max-w-[160px] truncate sm:max-w-[260px]">{value}</span>+ <CopyStatusIcon+ status={status}+ className="[&_svg]:size-3"+ idleClassName="text-neutral-400 dark:text-neutral-500"+ />+ </button>+ </TooltipTrigger>+ <TooltipContent>+ {status === "copied"+ ? t("Copied!")+ : status === "error"+ ? t("Couldn't copy to clipboard")+ : t("Copy user ID")}+ </TooltipContent>+ </Tooltip>+ <CopyAnnouncement status={status} />+ </>);}diff --git a/client/src/app/admin/components/organizations/Organizations.tsx b/client/src/app/admin/components/organizations/Organizations.tsxindex edbd3bd11..40533d0e8 100644--- a/client/src/app/admin/components/organizations/Organizations.tsx+++ b/client/src/app/admin/components/organizations/Organizations.tsx@@ -2,12 +2,11 @@import { useState, useMemo } from "react";import { useAdminOrganizations } from "@/api/admin/hooks/useAdminOrganizations";-import { Button } from "@/components/ui/button";+import { CopyButton } from "@/components/interior/copy-button";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { toast } from "@/components/ui/sonner";import { cn, formatter } from "@/lib/utils";import { DateTime } from "luxon";-import { Copy } from "lucide-react";import { useExtracted } from "next-intl";import { ErrorAlert } from "../shared/ErrorAlert";import { GrowthChart } from "../shared/GrowthChart";@@ -83,20 +82,17 @@ export function Organizations() {return { total: orgs.length, active, events24h, events30d };}, [filteredOrganizations]);- if (isError) {- return <ErrorAlert message={t("Failed to load organizations data. Please try again later.")} />;- }-- const copyOwnerEmails = () => {- if (!filteredOrganizations?.length) return;- const emails = [...filteredOrganizations]+ const ownerEmails = useMemo(() => {+ const emails = [...(filteredOrganizations ?? [])].sort((a, b) => a.name.localeCompare(b.name)).flatMap(org => org.members.filter(m => m.role === "owner").map(m => m.email)).filter(Boolean);- const unique = [...new Set(emails)];- navigator.clipboard.writeText(unique.join("\n"));- toast.success(t("Copied {count} owner emails", { count: String(unique.length) }));- };+ return [...new Set(emails)];+ }, [filteredOrganizations]);++ if (isError) {+ return <ErrorAlert message={t("Failed to load organizations data. Please try again later.")} />;+ }return (<div className="space-y-6">@@ -176,15 +172,15 @@ export function Organizations() {selectedTiers={selectedTiers}setSelectedTiers={setSelectedTiers}actions={- <Button+ <CopyButtonvariant="outline"size="sm"- onClick={copyOwnerEmails}- disabled={isLoading || !filteredOrganizations?.length}- >- <Copy className="h-3.5 w-3.5" />- {t("Copy owner emails")}- </Button>+ value={ownerEmails.join("\n")}+ label={t("Copy owner emails")}+ disabled={isLoading || ownerEmails.length === 0}+ onCopy={() => toast.success(t("Copied {count} owner emails", { count: String(ownerEmails.length) }))}+ onError={() => toast.error(t("Couldn't copy to clipboard"))}+ />}/><OrganizationsTable organizations={filteredOrganizations} isLoading={isLoading} searchQuery={searchQuery} />diff --git a/client/src/app/settings/account/components/ApiKeyManager.test.tsx b/client/src/app/settings/account/components/ApiKeyManager.test.tsxnew file mode 100644index 000000000..f73a4dc8a--- /dev/null+++ b/client/src/app/settings/account/components/ApiKeyManager.test.tsx@@ -0,0 +1,140 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { ApiKeyManager } from "./ApiKeyManager";++const SECRET = "rb_live_7f3a9c2e";++const mocks = vi.hoisted(() => {+ const createKey = vi.fn();+ return {+ createKey,+ toastError: vi.fn(),+ writeText: vi.fn<(text: string) => Promise<void>>(),+ keyHooks: () => ({ mutateAsync: createKey, isPending: false }),+ listHook: () => ({ data: { apiKeys: [] }, isLoading: false, isError: false, error: null, refetch: vi.fn() }),+ };+});++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, string | number>) =>+ values ? message.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? `{${key}}`)) : message,+}));++vi.mock("next/link", () => ({+ default: ({ href, children, ...props }: { href: string; children: ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+}));++vi.mock("../../../../api/admin/hooks/useUserApiKeys", () => ({+ useCreateApiKey: mocks.keyHooks,+ useDeleteApiKey: mocks.keyHooks,+ useListApiKeys: mocks.listHook,+}));++vi.mock("../../../../api/admin/hooks/useOrgApiKeys", () => ({+ useCreateOrgApiKey: mocks.keyHooks,+ useDeleteOrgApiKey: mocks.keyHooks,+ useListOrgApiKeys: mocks.listHook,+}));++vi.mock("../../../../lib/subscription/useStripeSubscription", () => ({+ useStripeSubscription: () => ({ data: { planName: "pro" } }),+}));++vi.mock("../../../../lib/const", async importOriginal => ({+ ...(await importOriginal<typeof import("../../../../lib/const")>()),+ IS_CLOUD: false,+}));++vi.mock("./ApiKeyScopePicker", () => ({ ApiKeyScopePicker: () => null, getScopeLabel: (scope: string) => scope }));++vi.mock("@/components/ui/sonner", () => ({ toast: { success: vi.fn(), error: mocks.toastError } }));++async function createKey() {+ render(<ApiKeyManager />);+ fireEvent.change(screen.getByLabelText("API Key Name"), { target: { value: "Deploy script" } });+ fireEvent.click(screen.getByRole("button", { name: "Create" }));+ return screen.findByRole("dialog", { name: "API Key Created" });+}++beforeEach(() => {+ mocks.createKey.mockResolvedValue({ key: SECRET });+ Object.defineProperty(navigator, "clipboard", { value: { writeText: mocks.writeText }, configurable: true });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ Reflect.deleteProperty(navigator, "clipboard");+});++describe("ApiKeyManager reveal dialog", () => {+ it("asks for a second step before closing when the key hasn't been copied", async () => {+ const dialog = await createKey();+ expect(within(dialog).getByText(SECRET)).toBeTruthy();++ fireEvent.click(within(dialog).getByRole("button", { name: "Done" }));++ expect(dialog.isConnected).toBe(true);+ expect(within(dialog).getByRole("alert").textContent).toContain("You haven't copied this key yet.");++ fireEvent.click(within(dialog).getByRole("button", { name: "Close anyway" }));++ await waitFor(() => expect(dialog.isConnected).toBe(false));+ });++ it("guards Escape the same way", async () => {+ const dialog = await createKey();++ fireEvent.keyDown(dialog, { key: "Escape" });++ expect(dialog.isConnected).toBe(true);+ expect(within(dialog).getByRole("alert")).toBeTruthy();+ });++ it("closes straight away once the key was copied with the button", async () => {+ mocks.writeText.mockResolvedValue(undefined);+ const dialog = await createKey();++ fireEvent.click(within(dialog).getByRole("button", { name: "Copy key" }));+ await waitFor(() => expect(within(dialog).getByRole("button", { name: "Copy key" }).dataset.status).toBe("copied"));+ expect(mocks.writeText).toHaveBeenCalledWith(SECRET);++ fireEvent.click(within(dialog).getByRole("button", { name: "Done" }));++ await waitFor(() => expect(dialog.isConnected).toBe(false));+ });++ it("counts selecting the key and copying it by hand", async () => {+ const dialog = await createKey();+ const code = within(dialog).getByText(SECRET);+ const range = document.createRange();+ range.selectNodeContents(code);+ document.getSelection()!.removeAllRanges();+ document.getSelection()!.addRange(range);++ fireEvent.copy(code);+ fireEvent.click(within(dialog).getByRole("button", { name: "Done" }));++ await waitFor(() => expect(dialog.isConnected).toBe(false));+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("keeps the manual-copy advice when the copy button fails", async () => {+ mocks.writeText.mockRejectedValue(new DOMException("Write permission denied.", "NotAllowedError"));+ const dialog = await createKey();++ fireEvent.click(within(dialog).getByRole("button", { name: "Copy key" }));++ await waitFor(() =>+ expect(mocks.toastError).toHaveBeenCalledWith("Couldn't copy to clipboard. Select the key and copy it manually.")+ );+ fireEvent.click(within(dialog).getByRole("button", { name: "Done" }));+ expect(within(dialog).getByRole("alert")).toBeTruthy();+ });+});diff --git a/client/src/app/settings/account/components/ApiKeyManager.tsx b/client/src/app/settings/account/components/ApiKeyManager.tsxindex 3f3841987..c9c6f9492 100644--- a/client/src/app/settings/account/components/ApiKeyManager.tsx+++ b/client/src/app/settings/account/components/ApiKeyManager.tsx@@ -1,10 +1,11 @@"use client";-import { AlertTriangle, Check, Copy, KeyRound, Trash2 } from "lucide-react";+import { AlertTriangle, KeyRound, Trash2 } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";import { useExtracted } from "next-intl";import { useState } from "react";+import { CopyButton } from "@/components/interior/copy-button";import { toast } from "@/components/ui/sonner";import { useCreateOrgApiKey, useDeleteOrgApiKey, useListOrgApiKeys } from "../../../../api/admin/hooks/useOrgApiKeys";import { useCreateApiKey, useDeleteApiKey, useListApiKeys } from "../../../../api/admin/hooks/useUserApiKeys";@@ -70,7 +71,10 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {const [apiKeyName, setApiKeyName] = useState("");const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);const [createdApiKey, setCreatedApiKey] = useState<string | null>(null);- const [copied, setCopied] = useState(false);+ // The key is shown once. Closing the reveal dialog before it has been copied+ // takes a second, deliberate step.+ const [keyCopied, setKeyCopied] = useState(false);+ const [confirmClose, setConfirmClose] = useState(false);const [restrictScopes, setRestrictScopes] = useState(false);const [scopes, setScopes] = useState<ScopeSelection>({});const [pendingDelete, setPendingDelete] = useState<{ id: string; name: string | null } | null>(null);@@ -115,7 +119,8 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {try {const result = await createApiKey.mutateAsync({ name: apiKeyName, permissions });setCreatedApiKey(result.key);- setCopied(false);+ setKeyCopied(false);+ setConfirmClose(false);setShowApiKeyDialog(true);setApiKeyName("");setRestrictScopes(false);@@ -139,16 +144,23 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {}};- const handleCopy = async () => {- if (!createdApiKey) return;- try {- await navigator.clipboard.writeText(createdApiKey);- setCopied(true);- } catch {- toast.error(t("Couldn't copy to clipboard. Select the key and copy it manually."));+ const handleApiKeyDialogOpenChange = (open: boolean) => {+ if (!open && !keyCopied && !confirmClose) {+ setConfirmClose(true);+ return;+ }+ setShowApiKeyDialog(open);+ };++ // Selecting the key and pressing Cmd/Ctrl+C counts as copying it too.+ const handleManualKeyCopy = () => {+ if (createdApiKey && document.getSelection()?.toString().includes(createdApiKey)) {+ setKeyCopied(true);}};+ const showCloseWarning = confirmClose && !keyCopied;+return (<><Card className="p-2">@@ -293,9 +305,7 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {{DateTime.fromJSDate(new Date(key.createdAt)).toLocaleString(DateTime.DATE_MED)}</TableCell><TableCell className="text-neutral-600 dark:text-neutral-400">- {key.lastRequest- ? DateTime.fromJSDate(new Date(key.lastRequest)).toRelative()- : t("Never")}+ {key.lastRequest ? DateTime.fromJSDate(new Date(key.lastRequest)).toRelative() : t("Never")}</TableCell><TableCell className="text-right"><Button@@ -326,7 +336,7 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {</CardContent></Card>- <Dialog open={showApiKeyDialog} onOpenChange={setShowApiKeyDialog}>+ <Dialog open={showApiKeyDialog} onOpenChange={handleApiKeyDialogOpenChange}><DialogContent className="max-w-md"><DialogHeader><DialogTitle>{t("API Key Created")}</DialogTitle>@@ -335,16 +345,29 @@ export function ApiKeyManager({ organizationId }: { organizationId?: string }) {</DialogDescription></DialogHeader><div className="space-y-3">- <code className="block select-all break-all rounded-lg border border-neutral-100 bg-neutral-50 p-3 font-mono text-xs leading-relaxed dark:border-neutral-800 dark:bg-neutral-900">+ <code+ onCopy={handleManualKeyCopy}+ className="block select-all break-all rounded-lg border border-neutral-100 bg-neutral-50 p-3 font-mono text-xs leading-relaxed dark:border-neutral-800 dark:bg-neutral-900"+ >{createdApiKey}</code>+ {showCloseWarning && (+ <p role="alert" className="flex items-start gap-2 text-xs text-amber-700 dark:text-amber-400">+ <AlertTriangle className="mt-px h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ {t("You haven't copied this key yet. Once you close this dialog, it can't be shown again.")}+ </p>+ )}<div className="flex gap-2">- <Button variant="success" className="flex-1" onClick={handleCopy}>- {copied ? <Check /> : <Copy />}- {copied ? t("Copied") : t("Copy key")}- </Button>- <Button variant="outline" onClick={() => setShowApiKeyDialog(false)}>- {t("Done")}+ <CopyButton+ variant="success"+ className="flex-1"+ value={createdApiKey ?? ""}+ label={t("Copy key")}+ onCopy={() => setKeyCopied(true)}+ onError={() => toast.error(t("Couldn't copy to clipboard. Select the key and copy it manually."))}+ />+ <Button variant="outline" onClick={() => handleApiKeyDialogOpenChange(false)}>+ {showCloseWarning ? t("Close anyway") : t("Done")}</Button></div></div>diff --git a/client/src/components/CodeSnippet.tsx b/client/src/components/CodeSnippet.tsxindex ab9709340..9dd0c046c 100644--- a/client/src/components/CodeSnippet.tsx+++ b/client/src/components/CodeSnippet.tsx@@ -1,6 +1,5 @@"use client";-import { Check, Copy } from "lucide-react";import { useExtracted } from "next-intl";import * as React from "react";import { Light as SyntaxHighlighter } from "react-syntax-highlighter";@@ -17,7 +16,7 @@ import json from "react-syntax-highlighter/dist/esm/languages/hljs/json";import { vs2015, vs } from "react-syntax-highlighter/dist/esm/styles/hljs";import { useTheme } from "next-themes";-import { Button } from "@/components/ui/button";+import { CopyButton } from "@/components/interior/copy-button";import { cn } from "@/lib/utils";// Register only the languages we need@@ -44,17 +43,10 @@ export const CodeSnippet = React.memo(function CodeSnippet({showLanguageLabel = false,className,}: CodeSnippetProps) {- const [hasCopied, setHasCopied] = React.useState(false);const t = useExtracted();const { resolvedTheme } = useTheme();const isDark = resolvedTheme === "dark";- const copyToClipboard = React.useCallback(async () => {- await navigator.clipboard.writeText(code);- setHasCopied(true);- setTimeout(() => setHasCopied(false), 2000);- }, [code]);-return (<div className={cn("relative border border-neutral-150 dark:border-neutral-800 rounded-md", className)}>{showLanguageLabel && language && (@@ -73,15 +65,7 @@ export const CodeSnippet = React.memo(function CodeSnippet({>{code}</SyntaxHighlighter>- <Button- size="icon"- variant="ghost"- className="absolute right-2 top-2 h-6 w-6 text-neutral-400 hover:text-neutral-100 hover:bg-neutral-700"- onClick={copyToClipboard}- >- {hasCopied ? <Check className="size-3" /> : <Copy className="size-3" />}- <span className="sr-only">{t("Copy code")}</span>- </Button>+ <CopyButton iconOnly size="xs" value={code} label={t("Copy code")} className="absolute right-2 top-2" /></div>);});diff --git a/client/src/components/CopyText.tsx b/client/src/components/CopyText.tsxindex a8e56bb2f..86c15c07c 100644--- a/client/src/components/CopyText.tsx+++ b/client/src/components/CopyText.tsx@@ -1,7 +1,10 @@-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+"use client";++import { useExtracted } from "next-intl";+import { ReactNode } from "react";++import { CopyButton } from "@/components/interior/copy-button";import { cn } from "@/lib/utils";-import { Check, Copy } from "lucide-react";-import { ReactNode, useEffect, useState } from "react";interface CopyTextProps {text: string;@@ -23,56 +26,25 @@ export function CopyText({className,copyButtonClassName,showCopyButton = true,- tooltipText = "Copy to clipboard",+ tooltipText,children,}: CopyTextProps) {- const [copied, setCopied] = useState(false);- const [displayText, setDisplayText] = useState("");-- useEffect(() => {- if (maxLength && text.length > maxLength) {- setDisplayText(`${text.substring(0, maxLength)}...`);- } else {- setDisplayText(text);- }- }, [text, maxLength]);-- const handleCopy = async () => {- try {- await navigator.clipboard.writeText(text);- setCopied(true);-- // Reset the copied state after 2 seconds- setTimeout(() => {- setCopied(false);- }, 2000);- } catch (err) {- console.error("Failed to copy text: ", err);- }- };+ const t = useExtracted();+ const displayText = maxLength && text.length > maxLength ? `${text.substring(0, maxLength)}...` : text;return (<div className={cn("flex items-center gap-1.5 group", className)}><span className="font-mono text-sm truncate">{children || displayText}</span>{showCopyButton && (- <Tooltip>- <TooltipTrigger asChild>- <button- onClick={handleCopy}- className={cn(- "p-1 rounded-md transition-colors text-neutral-400 hover:text-neutral-200 hover:bg-neutral-800 focus:outline-none",- copyButtonClassName- )}- aria-label="Copy to clipboard"- >- {copied ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}- </button>- </TooltipTrigger>- <TooltipContent>- <p>{copied ? "Copied!" : tooltipText}</p>- </TooltipContent>- </Tooltip>+ <CopyButton+ iconOnly+ size="xs"+ tooltip+ value={text}+ label={tooltipText ?? t("Copy to clipboard")}+ className={cn("size-5.5 [&_svg]:size-3.5", copyButtonClassName)}+ />)}</div>);diff --git a/client/src/components/interior/copy-button.test.tsx b/client/src/components/interior/copy-button.test.tsxnew file mode 100644index 000000000..978a90afe--- /dev/null+++ b/client/src/components/interior/copy-button.test.tsx@@ -0,0 +1,214 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { TooltipProvider } from "@/components/ui/tooltip";++import { CopyButton } from "./copy-button";++const mocks = vi.hoisted(() => ({+ writeText: vi.fn<(text: string) => Promise<void>>(),+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string) => message,+}));++function installClipboardApi() {+ Object.defineProperty(navigator, "clipboard", { value: { writeText: mocks.writeText }, configurable: true });+}++afterEach(() => {+ cleanup();+ Reflect.deleteProperty(navigator, "clipboard");+ mocks.writeText.mockReset();+});++describe("CopyButton", () => {+ it("keeps every state's label in the button so its width never changes", () => {+ render(<CopyButton value="sk_live_123" label="Copy key" />);++ const button = screen.getByRole("button", { name: "Copy key" });+ expect(button.textContent).toContain("Copy key");+ expect(button.textContent).toContain("Copied");+ expect(button.textContent).toContain("Failed");+ expect(button.getAttribute("data-status")).toBe("idle");+ expect(button.getAttribute("type")).toBe("button");+ });++ it("uses the label as the accessible name of an icon-only button", () => {+ render(<CopyButton iconOnly value="npm i @rybbit/js" label="Copy code" />);++ const button = screen.getByRole("button", { name: "Copy code" });+ expect(button.textContent).toBe("");+ });++ it("announces a copy politely, from outside the button", async () => {+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const onCopy = vi.fn();+ render(<CopyButton value="sk_live_123" label="Copy key" onCopy={onCopy} />);++ const button = screen.getByRole("button", { name: "Copy key" });+ const status = screen.getByRole("status");+ expect(status.textContent).toBe("");+ // WebKit drops a button's descendants from the accessibility tree.+ expect(button.contains(status)).toBe(false);++ fireEvent.click(button);++ await waitFor(() => expect(status.textContent).toBe("Copied"));+ expect(button.getAttribute("data-status")).toBe("copied");+ expect(mocks.writeText).toHaveBeenCalledWith("sk_live_123");+ expect(onCopy).toHaveBeenCalledWith("sk_live_123");+ });++ it("announces a failure and hands the reason to onError", async () => {+ installClipboardApi();+ const denied = new DOMException("Write permission denied.", "NotAllowedError");+ mocks.writeText.mockRejectedValue(denied);+ const onError = vi.fn();+ // jsdom has no document.execCommand, so the fallback fails too.+ render(<CopyButton value="sk_live_123" label="Copy key" onError={onError} />);++ fireEvent.click(screen.getByRole("button", { name: "Copy key" }));++ await waitFor(() => expect(screen.getByRole("status").textContent).toBe("Couldn't copy to clipboard"));+ expect(screen.getByRole("button", { name: "Copy key" }).getAttribute("data-status")).toBe("error");+ expect(onError).toHaveBeenCalledWith(denied);+ });++ it("lets a caller's onClick cancel the copy", () => {+ installClipboardApi();+ render(<CopyButton value="sk_live_123" label="Copy key" onClick={event => event.preventDefault()} />);++ fireEvent.click(screen.getByRole("button", { name: "Copy key" }));++ expect(mocks.writeText).not.toHaveBeenCalled();+ });+});++describe("CopyButton with a tooltip", () => {+ beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ Reflect.deleteProperty(document, "execCommand");+ });++ function renderCopySql() {+ render(+ <TooltipProvider>+ <CopyButton iconOnly size="sm" tooltip value="SELECT 1" label="Copy SQL" timeout={150} />+ </TooltipProvider>+ );+ return screen.getByRole("button", { name: "Copy SQL" });+ }++ async function hover(button: HTMLElement) {+ fireEvent.pointerMove(button);+ const tooltip = await screen.findByRole("tooltip");+ // Let Radix finish mounting the content's dismiss listeners (set up on a timeout).+ await act(() => new Promise(resolve => setTimeout(resolve, 0)));+ return tooltip;+ }++ // A mouse click: Radix closes an open tooltip on pointerdown, on the content's+ // outside-press check, and again on click.+ function click(button: HTMLElement) {+ fireEvent.pointerDown(button, { button: 0 });+ fireEvent.pointerUp(button, { button: 0 });+ fireEvent.click(button);+ }++ const tooltipText = () => screen.getByRole("tooltip").textContent;++ it("stays open through the click and shows the outcome until the button is back at rest", async () => {+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const button = renderCopySql();+ expect((await hover(button)).textContent).toBe("Copy SQL");++ click(button);++ expect(screen.queryByRole("tooltip")).not.toBeNull();+ await waitFor(() => expect(tooltipText()).toBe("Copied"));+ expect(mocks.writeText).toHaveBeenCalledWith("SELECT 1");+ // Back at rest while still hovered, it offers the action again.+ await waitFor(() => expect(tooltipText()).toBe("Copy SQL"));+ });++ it("still closes when the pointer leaves", async () => {+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const button = renderCopySql();+ await hover(button);+ click(button);+ await waitFor(() => expect(tooltipText()).toBe("Copied"));++ fireEvent.pointerLeave(button);+ fireEvent.pointerMove(document.body, { clientX: 400, clientY: 400 });++ await waitFor(() => expect(screen.queryByRole("tooltip")).toBeNull());+ });++ it("closes when a press is released away from the button, without copying", async () => {+ installClipboardApi();+ const button = renderCopySql();+ await hover(button);++ fireEvent.pointerDown(button, { button: 0 });+ expect(screen.queryByRole("tooltip")).not.toBeNull();+ fireEvent.pointerUp(document.body, { button: 0 });++ await waitFor(() => expect(screen.queryByRole("tooltip")).toBeNull());+ expect(mocks.writeText).not.toHaveBeenCalled();+ });++ it("shows a failure in the tooltip", async () => {+ installClipboardApi();+ mocks.writeText.mockRejectedValue(new DOMException("Write permission denied.", "NotAllowedError"));+ const button = renderCopySql();+ await hover(button);++ // jsdom has no document.execCommand, so the fallback fails too.+ click(button);++ await waitFor(() => expect(tooltipText()).toBe("Couldn't copy to clipboard"));+ });++ it("stays open from the keyboard through the fallback's focus hop", async () => {+ Object.defineProperty(document, "execCommand", { value: () => true, configurable: true });+ const button = renderCopySql();+ act(() => button.focus());+ expect(tooltipText()).toBe("Copy SQL");++ // No Clipboard API: the fallback focuses a textarea, which blurs the button.+ fireEvent.click(button);++ expect(screen.queryByRole("tooltip")).not.toBeNull();+ await waitFor(() => expect(tooltipText()).toBe("Copied"));+ expect(document.activeElement).toBe(button);+ });++ it("still closes on Escape while showing the outcome", async () => {+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const button = renderCopySql();+ await hover(button);+ click(button);+ await waitFor(() => expect(tooltipText()).toBe("Copied"));++ fireEvent.keyDown(document, { key: "Escape" });++ await waitFor(() => expect(screen.queryByRole("tooltip")).toBeNull());+ });+});diff --git a/client/src/components/interior/copy-button.tsx b/client/src/components/interior/copy-button.tsxnew file mode 100644index 000000000..2f8f85a04--- /dev/null+++ b/client/src/components/interior/copy-button.tsx@@ -0,0 +1,280 @@+// Adapted from interior.dev "Copy Button" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import { motion, useReducedMotion } from "framer-motion";+import { Copy, X } from "lucide-react";+import { useExtracted } from "next-intl";+import * as React from "react";++import { Button, type ButtonProps } from "@/components/ui/button";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { INSTANT, SPRING_CELL, SPRING_CROSSFADE } from "@/lib/motion";+import { cn } from "@/lib/utils";++import { type CopyStatus, useCopyToClipboard } from "./use-copy-to-clipboard";++const STATES: CopyStatus[] = ["idle", "copied", "error"];++const ICON_SHOWN = { opacity: 1, scale: 1 };+const ICON_HIDDEN = { opacity: 0, scale: 0.92 };+const LABEL_SHOWN = { opacity: 1, y: 0, filter: "blur(0px)" };+const LABEL_HIDDEN = { opacity: 0, y: 3, filter: "blur(3px)" };++type CopyStatusIconProps = {+ status: CopyStatus;+ // "color" paints the check emerald and the cross red, for neutral surfaces.+ // "current" keeps the text color, for filled (accent/success) buttons.+ tone?: "color" | "current";+ className?: string;+ // Extra classes for the resting copy icon only, e.g. to mute it next to text.+ idleClassName?: string;+};++// The copy icon, a check that draws itself in, and a cross, stacked in one cell and+// crossfaded by status. Sized like any icon: by a Button's [&_svg]:size-* or by+// passing one in className.+export function CopyStatusIcon({ status, tone = "color", className, idleClassName }: CopyStatusIconProps) {+ const reduced = useReducedMotion();+ const fade = reduced ? INSTANT : SPRING_CROSSFADE;+ const draw = reduced ? INSTANT : SPRING_CELL;++ return (+ <span aria-hidden="true" className={cn("inline-grid shrink-0 place-items-center", className)}>+ <motion.span+ initial={false}+ animate={status === "idle" ? ICON_SHOWN : ICON_HIDDEN}+ transition={fade}+ className={cn("col-start-1 row-start-1 flex", idleClassName)}+ >+ <Copy className="size-4" />+ </motion.span>+ <motion.span+ initial={false}+ animate={status === "copied" ? ICON_SHOWN : ICON_HIDDEN}+ transition={fade}+ className={cn("col-start-1 row-start-1 flex", tone === "color" && "text-accent-600 dark:text-accent-400")}+ >+ {/* Lucide's check, drawn from its short arm so it reads as a tick being made. */}+ <svg+ viewBox="0 0 24 24"+ width="24"+ height="24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ className="size-4"+ >+ <motion.path+ d="M4 12l5 5L20 6"+ initial={false}+ animate={{ pathLength: status === "copied" ? 1 : 0 }}+ transition={draw}+ />+ </svg>+ </motion.span>+ <motion.span+ initial={false}+ animate={status === "error" ? ICON_SHOWN : ICON_HIDDEN}+ transition={fade}+ className={cn("col-start-1 row-start-1 flex", tone === "color" && "text-red-500 dark:text-red-400")}+ >+ <X className="size-4" />+ </motion.span>+ </span>+ );+}++// Polite announcement of the outcome. Render it as a sibling of the button, not+// inside it: WebKit drops a button's descendants from the accessibility tree, so a+// live region inside one is never announced by VoiceOver.+export function CopyAnnouncement({ status, copiedLabel }: { status: CopyStatus; copiedLabel?: string }) {+ const t = useExtracted();++ return (+ <span role="status" aria-live="polite" className="sr-only">+ {status === "copied" ? (copiedLabel ?? t("Copied")) : status === "error" ? t("Couldn't copy to clipboard") : ""}+ </span>+ );+}++function CopyStatusLabel({ status, labels }: { status: CopyStatus; labels: Record<CopyStatus, string> }) {+ const reduced = useReducedMotion();+ const fade = reduced ? INSTANT : SPRING_CROSSFADE;++ return (+ // Every label shares one grid cell, so the button keeps the width of the longest.+ <span aria-hidden="true" className="grid justify-items-start">+ {STATES.map(state => (+ <motion.span+ key={state}+ initial={false}+ animate={state === status ? LABEL_SHOWN : LABEL_HIDDEN}+ transition={fade}+ className="col-start-1 row-start-1 whitespace-nowrap"+ >+ {labels[state]}+ </motion.span>+ ))}+ </span>+ );+}++type CopyButtonSize = "xs" | "sm" | "default" | "lg";++// Maps onto Button's sizes: labeled buttons use xs/sm/default/lg, icon-only ones+// the matching square (xs β 24px, sm β smIcon 28px, default β icon 36px, lg β 40px).+const SIZES: Record<+ CopyButtonSize,+ { labeled: ButtonProps["size"]; labeledClass: string; square: ButtonProps["size"]; squareClass: string }+> = {+ xs: { labeled: "xs", labeledClass: "gap-1.5 [&_svg]:size-3", square: "xs", squareClass: "w-6 px-0 [&_svg]:size-3" },+ sm: { labeled: "sm", labeledClass: "gap-1.5 [&_svg]:size-3.5", square: "smIcon", squareClass: "[&_svg]:size-3.5" },+ default: { labeled: "default", labeledClass: "", square: "icon", squareClass: "" },+ lg: { labeled: "lg", labeledClass: "", square: "lg", squareClass: "w-10 px-0" },+};++const FILLED_VARIANTS = new Set<ButtonProps["variant"]>(["accent", "success", "destructive", "warning"]);++// Icon-only ghost buttons usually sit on content (code blocks, table cells), so+// they rest muted and lift on hover.+const QUIET_ICON =+ "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-750 dark:hover:text-neutral-100";++export interface CopyButtonProps extends Omit<+ ButtonProps,+ "value" | "onCopy" | "onError" | "children" | "size" | "asChild" | "loading" | "loadingLabel"+> {+ // The text that ends up on the clipboard.+ value: string;+ // The action. Visible text, or the accessible name and tooltip when iconOnly. Defaults to "Copy".+ label?: string;+ copiedLabel?: string;+ errorLabel?: string;+ iconOnly?: boolean;+ size?: CopyButtonSize;+ // Show the action (then the outcome) in a tooltip. Use this rather than wrapping+ // the button in a TooltipTrigger: CopyButton renders two elements.+ tooltip?: boolean;+ // How long the outcome shows before the button returns to rest, in ms.+ timeout?: number;+ onCopy?: (value: string) => void;+ onError?: (reason: unknown) => void;+}++/**+ * Copies `value` and swaps Copy β β Copied (or β Failed) in place without changing+ * width, then returns to rest. Plays the success/error interface sound and+ * announces the outcome politely. Renders the button plus a sibling live region.+ */+export const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(function CopyButton(+ {+ value,+ label,+ copiedLabel,+ errorLabel,+ iconOnly = false,+ size = "default",+ variant,+ tooltip = false,+ timeout,+ onCopy,+ onError,+ onClick,+ onPointerDown,+ className,+ ...props+ },+ ref+) {+ const t = useExtracted();+ const { copy, status } = useCopyToClipboard({ timeout, onCopy, onError });++ // Radix closes a tooltip when its trigger is pressed (pointerdown, the content's+ // outside-press check, click), which hid "Copied" after ~100 ms. So the tooltip+ // is controlled, and closes are skipped while the pointer is down on the button+ // and while its copy runs (the execCommand fallback briefly blurs the button).+ // Leaving the button, blurring away, Escape, scrolling and pressing elsewhere+ // still close it.+ const [tooltipOpen, setTooltipOpen] = React.useState(false);+ const pointerDown = React.useRef(false);+ const copiesInFlight = React.useRef(0);++ const labels: Record<CopyStatus, string> = {+ idle: label ?? t("Copy"),+ copied: copiedLabel ?? t("Copied"),+ error: errorLabel ?? t("Failed"),+ };+ const resolvedVariant = variant ?? (iconOnly ? "ghost" : "default");+ const sizing = SIZES[size];++ const button = (+ <Button+ ref={ref}+ type="button"+ variant={resolvedVariant}+ size={iconOnly ? sizing.square : sizing.labeled}+ aria-label={labels.idle}+ data-status={status}+ {...props}+ className={cn(+ "touch-manipulation",+ iconOnly ? sizing.squareClass : sizing.labeledClass,+ iconOnly && resolvedVariant === "ghost" && QUIET_ICON,+ className+ )}+ // Both run before Radix's trigger handlers, so the hold is in place when+ // Radix asks the tooltip to close.+ onPointerDown={event => {+ onPointerDown?.(event);+ if (!tooltip || event.button !== 0) return;+ pointerDown.current = true;+ const trigger = event.currentTarget;+ const release = (up: PointerEvent) => {+ document.removeEventListener("pointerup", release, true);+ document.removeEventListener("pointercancel", release, true);+ pointerDown.current = false;+ // Released away from the button: no click or copy follows, so apply the+ // close the press held back.+ if (up.type === "pointercancel" || !(up.target instanceof Node && trigger.contains(up.target))) {+ setTooltipOpen(false);+ }+ };+ document.addEventListener("pointerup", release, true);+ document.addEventListener("pointercancel", release, true);+ }}+ onClick={event => {+ onClick?.(event);+ if (event.defaultPrevented) return;+ // Counted before copy() starts: the fallback blurs the button synchronously.+ copiesInFlight.current += 1;+ void copy(value).finally(() => {+ copiesInFlight.current -= 1;+ });+ }}+ >+ <CopyStatusIcon status={status} tone={FILLED_VARIANTS.has(resolvedVariant) ? "current" : "color"} />+ {!iconOnly && <CopyStatusLabel status={status} labels={labels} />}+ </Button>+ );++ return (+ <>+ {tooltip ? (+ <Tooltip+ open={tooltipOpen}+ onOpenChange={open => {+ if (open || (!pointerDown.current && copiesInFlight.current === 0)) setTooltipOpen(open);+ }}+ >+ <TooltipTrigger asChild>{button}</TooltipTrigger>+ <TooltipContent>{status === "error" ? t("Couldn't copy to clipboard") : labels[status]}</TooltipContent>+ </Tooltip>+ ) : (+ button+ )}+ <CopyAnnouncement status={status} copiedLabel={labels.copied} />+ </>+ );+});diff --git a/client/src/components/interior/use-copy-to-clipboard.test.tsx b/client/src/components/interior/use-copy-to-clipboard.test.tsxnew file mode 100644index 000000000..f9fcf9593--- /dev/null+++ b/client/src/components/interior/use-copy-to-clipboard.test.tsx@@ -0,0 +1,285 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useCopyToClipboard, writeFallback } from "./use-copy-to-clipboard";++const mocks = vi.hoisted(() => ({+ writeText: vi.fn<(text: string) => Promise<void>>(),+ execCommand: vi.fn<(command: string) => boolean>(),+}));++// jsdom implements neither the async Clipboard API nor document.execCommand.+function installClipboardApi() {+ Object.defineProperty(navigator, "clipboard", { value: { writeText: mocks.writeText }, configurable: true });+}++beforeEach(() => {+ Object.defineProperty(document, "execCommand", { value: mocks.execCommand, configurable: true });+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+ Reflect.deleteProperty(navigator, "clipboard");+ Reflect.deleteProperty(document, "execCommand");+ mocks.writeText.mockReset();+ mocks.execCommand.mockReset();+ document.body.innerHTML = "";+});++describe("useCopyToClipboard", () => {+ it("copies with the Clipboard API, reports success, then returns to idle", async () => {+ vi.useFakeTimers();+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const onCopy = vi.fn();+ const onError = vi.fn();+ const { result } = renderHook(() => useCopyToClipboard({ onCopy, onError }));++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("sk_live_123");+ });++ expect(ok).toBe(true);+ expect(mocks.writeText).toHaveBeenCalledWith("sk_live_123");+ expect(mocks.execCommand).not.toHaveBeenCalled();+ expect(result.current.status).toBe("copied");+ expect(result.current.copied).toBe(true);+ expect(onCopy).toHaveBeenCalledWith("sk_live_123");+ expect(onError).not.toHaveBeenCalled();++ act(() => {+ vi.advanceTimersByTime(1999);+ });+ expect(result.current.status).toBe("copied");+ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(result.current.status).toBe("idle");+ });++ it("falls back to execCommand without the Clipboard API, restoring focus and selection", async () => {+ document.body.innerHTML = '<p id="note">keep me selected</p><button id="trigger" type="button">Copy</button>';+ const trigger = document.getElementById("trigger") as HTMLButtonElement;+ // Focus first: jsdom, like some engines, collapses the selection when focus moves.+ trigger.focus();+ const range = document.createRange();+ range.selectNodeContents(document.getElementById("note")!);+ document.getSelection()!.removeAllRanges();+ document.getSelection()!.addRange(range);++ let copiedFrom: Element | null = null;+ mocks.execCommand.mockImplementation(() => {+ copiedFrom = document.activeElement;+ return true;+ });+ const { result } = renderHook(() => useCopyToClipboard());++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("line one\nline two");+ });++ expect(ok).toBe(true);+ expect(mocks.execCommand).toHaveBeenCalledWith("copy");+ // The copy ran from a focused, fully selected textarea holding the exact text...+ expect(copiedFrom).toBeInstanceOf(HTMLTextAreaElement);+ const area = copiedFrom as unknown as HTMLTextAreaElement;+ expect(area.value).toBe("line one\nline two");+ expect([area.selectionStart, area.selectionEnd]).toEqual([0, "line one\nline two".length]);+ // ...which is gone again, with the user's focus and selection put back.+ expect(document.querySelector("textarea")).toBeNull();+ expect(document.activeElement).toBe(trigger);+ expect(document.getSelection()!.toString()).toBe("keep me selected");+ expect(result.current.status).toBe("copied");+ });++ it("falls back to execCommand when the Clipboard API rejects", async () => {+ installClipboardApi();+ mocks.writeText.mockRejectedValue(new DOMException("Document is not focused.", "NotAllowedError"));+ mocks.execCommand.mockReturnValue(true);+ const onCopy = vi.fn();+ const onError = vi.fn();+ const { result } = renderHook(() => useCopyToClipboard({ onCopy, onError }));++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("https://app.rybbit.io/1/abc");+ });++ expect(ok).toBe(true);+ expect(mocks.execCommand).toHaveBeenCalledWith("copy");+ expect(result.current.status).toBe("copied");+ expect(onCopy).toHaveBeenCalledWith("https://app.rybbit.io/1/abc");+ expect(onError).not.toHaveBeenCalled();+ });++ it("mounts the fallback textarea inside the dialog that holds focus", () => {+ // Radix focus traps pull focus back out of anything mounted outside them.+ document.body.innerHTML = '<div role="dialog" id="dialog"><button id="inside" type="button">Copy</button></div>';+ const inside = document.getElementById("inside") as HTMLButtonElement;+ inside.focus();++ let host: Element | null = null;+ mocks.execCommand.mockImplementation(() => {+ host = document.querySelector("textarea")?.parentElement ?? null;+ return true;+ });++ expect(writeFallback("secret")).toBe(true);+ expect(host).toBe(document.getElementById("dialog"));+ expect(document.activeElement).toBe(inside);+ });++ it("reports failure when both the Clipboard API and the fallback fail", async () => {+ vi.useFakeTimers();+ installClipboardApi();+ const denied = new DOMException("Write permission denied.", "NotAllowedError");+ mocks.writeText.mockRejectedValue(denied);+ mocks.execCommand.mockReturnValue(false);+ const onCopy = vi.fn();+ const onError = vi.fn();+ const { result } = renderHook(() => useCopyToClipboard({ onCopy, onError }));++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("sk_live_123");+ });++ expect(ok).toBe(false);+ expect(result.current.status).toBe("error");+ expect(result.current.copied).toBe(false);+ expect(onError).toHaveBeenCalledWith(denied);+ expect(onCopy).not.toHaveBeenCalled();+ expect(document.querySelector("textarea")).toBeNull();++ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(result.current.status).toBe("idle");+ });++ it("reports failure when execCommand itself is unavailable", async () => {+ Reflect.deleteProperty(document, "execCommand");+ const onError = vi.fn();+ const { result } = renderHook(() => useCopyToClipboard({ onError }));++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("sk_live_123");+ });++ expect(ok).toBe(false);+ expect(result.current.status).toBe("error");+ expect(onError).toHaveBeenCalledOnce();+ expect(document.querySelector("textarea")).toBeNull();+ });++ it("restarts the reset timer on every copy", async () => {+ vi.useFakeTimers();+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const { result } = renderHook(() => useCopyToClipboard({ timeout: 2000 }));++ await act(async () => {+ await result.current.copy("first");+ });+ act(() => {+ vi.advanceTimersByTime(1500);+ });+ expect(result.current.status).toBe("copied");++ await act(async () => {+ await result.current.copy("second");+ });+ // 3000 ms after the first copy, but only 1500 after the second.+ act(() => {+ vi.advanceTimersByTime(1500);+ });+ expect(result.current.status).toBe("copied");++ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(result.current.status).toBe("idle");+ });++ it("restarts the timer when a failure follows a success", async () => {+ vi.useFakeTimers();+ installClipboardApi();+ mocks.writeText.mockResolvedValueOnce(undefined).mockRejectedValueOnce(new Error("denied"));+ mocks.execCommand.mockReturnValue(false);+ const { result } = renderHook(() => useCopyToClipboard({ timeout: 1000 }));++ await act(async () => {+ await result.current.copy("first");+ });+ act(() => {+ vi.advanceTimersByTime(800);+ });+ await act(async () => {+ await result.current.copy("second");+ });+ expect(result.current.status).toBe("error");++ act(() => {+ vi.advanceTimersByTime(800);+ });+ expect(result.current.status).toBe("error");+ act(() => {+ vi.advanceTimersByTime(200);+ });+ expect(result.current.status).toBe("idle");+ });++ it("does nothing for empty text", async () => {+ installClipboardApi();+ const { result } = renderHook(() => useCopyToClipboard());++ let ok: boolean | undefined;+ await act(async () => {+ ok = await result.current.copy("");+ });++ expect(ok).toBe(false);+ expect(result.current.status).toBe("idle");+ expect(mocks.writeText).not.toHaveBeenCalled();+ });++ it("returns to idle immediately on reset", async () => {+ installClipboardApi();+ mocks.writeText.mockResolvedValue(undefined);+ const { result } = renderHook(() => useCopyToClipboard());++ await act(async () => {+ await result.current.copy("value");+ });+ expect(result.current.status).toBe("copied");++ act(() => {+ result.current.reset();+ });+ expect(result.current.status).toBe("idle");+ });++ it("skips state updates and callbacks once unmounted", async () => {+ installClipboardApi();+ let finishWrite!: () => void;+ mocks.writeText.mockImplementation(+ () =>+ new Promise<void>(resolve => {+ finishWrite = resolve;+ })+ );+ const onCopy = vi.fn();+ const { result, unmount } = renderHook(() => useCopyToClipboard({ onCopy }));++ const pending = result.current.copy("value");+ unmount();+ finishWrite();++ await expect(pending).resolves.toBe(true);+ expect(onCopy).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/interior/use-copy-to-clipboard.ts b/client/src/components/interior/use-copy-to-clipboard.tsnew file mode 100644index 000000000..1aa57d085--- /dev/null+++ b/client/src/components/interior/use-copy-to-clipboard.ts@@ -0,0 +1,132 @@+// Adapted from interior.dev "Copy Button" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++export type CopyStatus = "idle" | "copied" | "error";++export type UseCopyToClipboardOptions = {+ // How long "copied" or "error" shows before returning to idle, in ms. Restarts on every copy.+ timeout?: number;+ onCopy?: (value: string) => void;+ onError?: (reason: unknown) => void;+};++// Radix dialogs, sheets and menus trap focus: a textarea mounted outside them has+// focus pulled straight back before the copy runs. Mount it inside the overlay+// that holds focus instead.+function fallbackHost(): HTMLElement {+ const active = document.activeElement;+ const overlay =+ active instanceof HTMLElement+ ? active.closest<HTMLElement>('[role="dialog"], [role="alertdialog"], [role="menu"]')+ : null;+ return overlay ?? document.body;+}++// document.execCommand("copy") through an invisible textarea, for contexts without+// the async Clipboard API (self-hosts served over plain HTTP) or where it rejects+// (iframes without clipboard-write). Puts the user's selection and focus back.+export function writeFallback(text: string): boolean {+ const selection = document.getSelection();+ // A copy, since engines may collapse the live range in place when focus moves.+ const previousRange = selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;+ const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;++ const area = document.createElement("textarea");+ area.value = text;+ area.setAttribute("readonly", "");+ area.tabIndex = -1;+ area.style.position = "fixed";+ area.style.top = "0";+ area.style.left = "0";+ area.style.opacity = "0";+ area.style.pointerEvents = "none";+ fallbackHost().appendChild(area);++ let ok = false;+ try {+ area.focus({ preventScroll: true });+ area.select();+ area.setSelectionRange(0, text.length);+ ok = document.execCommand("copy");+ } catch {+ ok = false;+ } finally {+ area.remove();+ // Focus first: focusing can move the selection, so it is restored last.+ if (previousFocus && previousFocus !== document.body && previousFocus.isConnected) {+ previousFocus.focus({ preventScroll: true });+ }+ if (selection && previousRange) {+ selection.removeAllRanges();+ selection.addRange(previousRange);+ }+ }+ return ok;+}++export function useCopyToClipboard({ timeout = 2000, onCopy, onError }: UseCopyToClipboardOptions = {}) {+ const [status, setStatus] = useState<CopyStatus>("idle");+ // Bumped on every copy so the reset timer restarts even when the status doesn't change.+ const [ticket, setTicket] = useState(0);++ const mounted = useRef(true);+ const handlers = useRef({ onCopy, onError });+ useEffect(() => {+ handlers.current = { onCopy, onError };+ });++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);++ const reset = useCallback(() => {+ setStatus("idle");+ setTicket(0);+ }, []);++ const copy = useCallback(async (text: string) => {+ if (!text) return false;++ let ok = false;+ let reason: unknown = null;++ try {+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ ok = true;+ } else {+ ok = writeFallback(text);+ }+ } catch (error) {+ reason = error;+ try {+ ok = writeFallback(text);+ } catch {+ ok = false;+ }+ }++ if (!mounted.current) return ok;++ setStatus(ok ? "copied" : "error");+ setTicket(n => n + 1);++ if (ok) handlers.current.onCopy?.(text);+ else handlers.current.onError?.(reason);++ return ok;+ }, []);++ useEffect(() => {+ if (ticket === 0 || status === "idle") return;+ const id = setTimeout(() => setStatus("idle"), timeout);+ return () => clearTimeout(id);+ }, [ticket, status, timeout]);++ return { copy, reset, status, copied: status === "copied" };+}