🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
feat(settings): hold to confirm deleting a site, account or organization, and confirm unguarded actions (#1260)
Goldflagd11238bfbbb1
diff --git a/client/src/app/[site]/experiments/components/ExperimentRow.tsx b/client/src/app/[site]/experiments/components/ExperimentRow.tsxindex 1d43c63dd..ee435f6b3 100644--- a/client/src/app/[site]/experiments/components/ExperimentRow.tsx+++ b/client/src/app/[site]/experiments/components/ExperimentRow.tsx@@ -2,6 +2,15 @@import type { Experiment, ExperimentStatus } from "@/api/analytics/endpoints";import { useDeleteExperiment, useUpdateExperiment } from "@/api/analytics/hooks/experiments/useExperiments";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -35,6 +44,8 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experimconst deleteMutation = useDeleteExperiment();const updateMutation = useUpdateExperiment();const [editOpen, setEditOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);+ const [completeOpen, setCompleteOpen] = useState(false);const primaryGoalName =experiment.primaryGoal?.name || (experiment.primaryGoalId ? t("Untitled goal") : t("No goal"));@@ -51,11 +62,10 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experim: null;const handleDelete = async () => {- if (!window.confirm(t("Delete this experiment?"))) return;-try {await deleteMutation.mutateAsync(experiment.experimentId);toast.success(t("Experiment deleted"));+ setDeleteOpen(false);} catch (error) {toast.error(error instanceof Error ? error.message : t("Failed to delete experiment"));}@@ -65,11 +75,17 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experimtry {await updateMutation.mutateAsync({ experimentId: experiment.experimentId, payload: { status } });toast.success(t("Experiment updated"));+ return true;} catch (error) {toast.error(error instanceof Error ? error.message : t("Failed to update experiment"));+ return false;}};+ const handleComplete = async () => {+ if (await setStatus("completed")) setCompleteOpen(false);+ };+const isRunning = experiment.status === "running";return (@@ -127,7 +143,7 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experim<Buttonsize="sm"variant="secondary"- onClick={() => setStatus("completed")}+ onClick={() => setCompleteOpen(true)}disabled={updateMutation.isPending}><Square className="h-3.5 w-3.5" />@@ -148,7 +164,7 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experim<DropdownMenuSeparator /><DropdownMenuItemdisabled={deleteMutation.isPending}- onSelect={handleDelete}+ onSelect={() => setDeleteOpen(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" />@@ -164,6 +180,62 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experim</div><ExperimentDialog experiment={experiment} experiments={experiments} open={editOpen} onOpenChange={setEditOpen} />++ <AlertDialog+ open={deleteOpen}+ onOpenChange={open => {+ if (!deleteMutation.isPending) setDeleteOpen(open);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Delete this experiment?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t('This permanently deletes "{name}". Its feature flag and goal are not deleted.', {+ name: experiment.name,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={deleteMutation.isPending}>{t("Cancel")}</AlertDialogCancel>+ {/* Plain Buttons, not AlertDialogAction, so these dialogs stay open until the request settles (the+ handlers close them on success). `loading` keeps their width while pending. */}+ <Button+ variant="destructive"+ loading={deleteMutation.isPending}+ loadingLabel={t("Deleting...")}+ onClick={handleDelete}+ >+ {t("Delete")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <AlertDialog+ open={completeOpen}+ onOpenChange={open => {+ if (!updateMutation.isPending) setCompleteOpen(open);+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Complete this experiment?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(+ 'This permanently ends "{name}": a completed experiment can\'t be restarted. Its feature flag keeps serving variants until you change it.',+ { name: experiment.name }+ )}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={updateMutation.isPending}>{t("Cancel")}</AlertDialogCancel>+ <Button loading={updateMutation.isPending} loadingLabel={t("Completing...")} onClick={handleComplete}>+ {t("Complete experiment")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}diff --git a/client/src/app/settings/account/components/DeleteAccount.tsx b/client/src/app/settings/account/components/DeleteAccount.tsxindex 416264fe2..b1274ff36 100644--- a/client/src/app/settings/account/components/DeleteAccount.tsx+++ b/client/src/app/settings/account/components/DeleteAccount.tsx@@ -4,10 +4,10 @@ import { useQueryClient } from "@tanstack/react-query";import { AlertTriangle } from "lucide-react";import { useExtracted } from "next-intl";import { useState } from "react";+import { HoldToConfirm } from "@/components/interior/hold-to-confirm";import { toast } from "@/components/ui/sonner";import {AlertDialog,- AlertDialogAction,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,@@ -28,34 +28,43 @@ export function DeleteAccount() {const t = useExtracted();const handleAccountDeletion = async () => {+ setIsDeleting(true);try {- setIsDeleting(true);const response = await authClient.deleteUser();if (response.error) {toast.error(t("Failed to delete account: {error}", { error: response.error.message || t("Unknown error") }));+ setIsDeleting(false);return;}- queryClient.clear();- toast.success(t("Account successfully deleted"));- setIsOpen(false);- window.location.reload();} catch (error) {toast.error(t("Failed to delete account: {error}", { error: String(error) }));- } finally {setIsDeleting(false);+ return;}+ // Stays pending through the reload, so the button doesn't re-arm on the way out.+ queryClient.clear();+ toast.success(t("Account successfully deleted"));+ setIsOpen(false);+ window.location.reload();};const handleClose = () => {setIsOpen(false);};- const accountNotDeletable =- isDeleting || subscription?.planName.startsWith("standard") || subscription?.planName.startsWith("pro");+ // Paid plans must be cancelled first. (isDeleting used to be part of this, which flipped the dialog to+ // "Cannot delete account" for as long as the deletion was running.)+ const hasActiveSubscription =+ subscription?.planName.startsWith("standard") || subscription?.planName.startsWith("pro");return (- <AlertDialog open={isOpen} onOpenChange={setIsOpen}>+ <AlertDialog+ open={isOpen}+ onOpenChange={open => {+ if (!isDeleting) setIsOpen(open);+ }}+ ><AlertDialogTrigger asChild><Button variant="destructive" className="w-full" onClick={() => setIsOpen(true)}>{t("Delete Account")}@@ -65,12 +74,14 @@ export function DeleteAccount() {<AlertDialogHeader><AlertDialogTitle className="flex items-center gap-2"><AlertTriangle className="h-5 w-5" color="hsl(var(--red-500))" />- {accountNotDeletable ? t("Cannot delete account") : t("Delete your account?")}+ {hasActiveSubscription ? t("Cannot delete account") : t("Delete your account?")}</AlertDialogTitle><AlertDialogDescription>- {accountNotDeletable+ {hasActiveSubscription? t("You have an active subscription. Please cancel your subscription before deleting your account.")- : t("This action cannot be undone. This will permanently delete your account and remove all your data from our servers.")}+ : t(+ "This action cannot be undone. This will permanently delete your account and remove all your data from our servers."+ )}</AlertDialogDescription></AlertDialogHeader>@@ -78,17 +89,10 @@ export function DeleteAccount() {<AlertDialogCancel onClick={handleClose} disabled={isDeleting}>{t("Cancel")}</AlertDialogCancel>- {!accountNotDeletable && (- <AlertDialogAction- onClick={e => {- e.preventDefault();- handleAccountDeletion();- }}- variant="destructive"- disabled={isDeleting}- >- {isDeleting ? t("Deleting...") : t("Delete Account")}- </AlertDialogAction>+ {!hasActiveSubscription && (+ <HoldToConfirm onConfirm={handleAccountDeletion} pending={isDeleting} pendingLabel={t("Deleting...")}>+ {t("Hold to delete account")}+ </HoldToConfirm>)}</AlertDialogFooter></AlertDialogContent>diff --git a/client/src/app/settings/organization/components/DeleteOrganizationDialog.tsx b/client/src/app/settings/organization/components/DeleteOrganizationDialog.tsxindex b6a5fa3b3..6d17d60fe 100644--- a/client/src/app/settings/organization/components/DeleteOrganizationDialog.tsx+++ b/client/src/app/settings/organization/components/DeleteOrganizationDialog.tsx@@ -3,11 +3,11 @@import { useQueryClient } from "@tanstack/react-query";import { AlertTriangle } from "lucide-react";import { useExtracted } from "next-intl";-import { useState } from "react";+import { useId, useState } from "react";+import { HoldToConfirm } from "@/components/interior/hold-to-confirm";import { toast } from "@/components/ui/sonner";import {AlertDialog,- AlertDialogAction,AlertDialogCancel,AlertDialogContent,AlertDialogDescription,@@ -35,6 +35,7 @@ export function DeleteOrganizationDialog({ organization, onSuccess }: DeleteOrgaconst [isOpen, setIsOpen] = useState(false);const [confirmText, setConfirmText] = useState("");const queryClient = useQueryClient();+ const confirmPromptId = useId();const hasActiveSubscription =subscription?.planName.startsWith("standard") || subscription?.planName.startsWith("pro");@@ -47,35 +48,42 @@ export function DeleteOrganizationDialog({ organization, onSuccess }: DeleteOrgasetIsDeleting(true);try {- await authClient.organization.delete({+ // better-auth reports failures in the result rather than throwing.+ const { error } = await authClient.organization.delete({organizationId: organization.id,});-- toast.success(t("Organization deleted successfully"));- queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });- authClient.organization.setActive({- organizationId: null,- });- setIsOpen(false);- onSuccess();- } catch (error: any) {- toast.error(error.message || t("Failed to delete organization"));- } finally {+ if (error) {+ throw new Error(error.message || t("Failed to delete organization"));+ }+ } catch (error) {+ toast.error(error instanceof Error && error.message ? error.message : t("Failed to delete organization"));setIsDeleting(false);+ return;}- };- const handleClose = () => {+ // Stays pending on success: the page leaves this organization (it's keyed by organization id), so the+ // button must not re-arm while the dialog closes.+ toast.success(t("Organization deleted successfully"));+ queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });+ authClient.organization.setActive({+ organizationId: null,+ });setIsOpen(false);- setConfirmText("");+ onSuccess();};- const canDelete = !hasActiveSubscription && confirmText === organization.name && !isDeleting;+ const handleOpenChange = (open: boolean) => {+ // A running deletion can't be dismissed.+ if (isDeleting && !open) return;+ // Every attempt starts from an empty confirmation field.+ if (open) setConfirmText("");+ setIsOpen(open);+ };return (- <AlertDialog open={isOpen} onOpenChange={setIsOpen}>+ <AlertDialog open={isOpen} onOpenChange={handleOpenChange}><AlertDialogTrigger asChild>- <Button variant="destructive" className="w-full" onClick={() => setIsOpen(true)}>+ <Button variant="destructive" className="w-full">{t("Delete Organization")}</Button></AlertDialogTrigger>@@ -88,38 +96,39 @@ export function DeleteOrganizationDialog({ organization, onSuccess }: DeleteOrga<AlertDialogDescription>{hasActiveSubscription? t("You have an active subscription. Please cancel your subscription before deleting your organization.")- : t("This action cannot be undone. This will permanently delete the organization and remove all associated data.")}+ : t(+ "This action cannot be undone. This will permanently delete the organization and remove all associated data."+ )}</AlertDialogDescription></AlertDialogHeader>{!hasActiveSubscription && (<div className="py-4">- <p className="text-sm mb-2">+ <p id={confirmPromptId} className="text-sm mb-2">{t("Please type {name} to confirm.", { name: organization.name })}</p><Inputvalue={confirmText}- onChange={(e) => setConfirmText(e.target.value)}+ onChange={e => setConfirmText(e.target.value)}placeholder={organization.name}+ aria-labelledby={confirmPromptId}+ autoComplete="off"+ disabled={isDeleting}/></div>)}<AlertDialogFooter>- <AlertDialogCancel onClick={handleClose} disabled={isDeleting}>- {t("Cancel")}- </AlertDialogCancel>+ <AlertDialogCancel disabled={isDeleting}>{t("Cancel")}</AlertDialogCancel>{!hasActiveSubscription && (- <AlertDialogAction- onClick={(e) => {- e.preventDefault();- handleDelete();- }}- variant="destructive"- disabled={!canDelete}+ <HoldToConfirm+ onConfirm={handleDelete}+ pending={isDeleting}+ pendingLabel={t("Deleting...")}+ disabled={confirmText !== organization.name}>- {isDeleting ? t("Deleting...") : t("Delete Organization")}- </AlertDialogAction>+ {t("Hold to delete organization")}+ </HoldToConfirm>)}</AlertDialogFooter></AlertDialogContent>diff --git a/client/src/app/settings/organization/components/EditMemberDialog.tsx b/client/src/app/settings/organization/components/EditMemberDialog.tsxindex 6a19f2700..6809c2315 100644--- a/client/src/app/settings/organization/components/EditMemberDialog.tsx+++ b/client/src/app/settings/organization/components/EditMemberDialog.tsx@@ -6,6 +6,16 @@ import { useEffect, useState } from "react";import { toast } from "@/components/ui/sonner";import { GetOrganizationMembersResponse, updateMemberSiteAccess } from "@/api/admin/endpoints/auth";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Input } from "@/components/ui/input";@@ -33,13 +43,7 @@ interface EditMemberDialogProps {isOwner: boolean;}-export function EditMemberDialog({- member,- open,- onClose,- onSuccess,- isOwner,-}: EditMemberDialogProps) {+export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }: EditMemberDialogProps) {const { data: activeOrganization } = authClient.useActiveOrganization();const queryClient = useQueryClient();const t = useExtracted();@@ -50,6 +54,7 @@ export function EditMemberDialog({const [selectedSiteIds, setSelectedSiteIds] = useState<number[]>([]);const [isSaving, setIsSaving] = useState(false);const [isRemoving, setIsRemoving] = useState(false);+ const [confirmRemoveOpen, setConfirmRemoveOpen] = useState(false);useEffect(() => {if (open && member) {@@ -57,6 +62,7 @@ export function EditMemberDialog({setRole(member.role);setRestrictSiteAccess(member.siteAccess?.hasRestrictedSiteAccess ?? false);setSelectedSiteIds(member.siteAccess?.siteIds ?? []);+ setConfirmRemoveOpen(false);}}, [open, member]);@@ -120,16 +126,21 @@ export function EditMemberDialog({setIsRemoving(true);try {- await authClient.organization.removeMember({+ // better-auth reports failures in the result rather than throwing.+ const { error } = await authClient.organization.removeMember({memberIdOrEmail: member.id,organizationId: activeOrganization.id,});+ if (error) {+ throw new Error(error.message || t("Failed to remove member"));+ }toast.success(t("Member removed successfully"));+ setConfirmRemoveOpen(false);onSuccess();onClose();- } catch (error: any) {- toast.error(error.message || t("Failed to remove member"));+ } catch (error) {+ toast.error(error instanceof Error && error.message ? error.message : t("Failed to remove member"));} finally {setIsRemoving(false);}@@ -222,8 +233,7 @@ export function EditMemberDialog({</>) : (<p className="text-sm text-neutral-500 dark:text-neutral-300">- {role === "owner" ? t("Organization owners") : t("Admins")}{" "}- {t("automatically have access to all sites.")}+ {role === "owner" ? t("Organization owners") : t("Admins")} {t("automatically have access to all sites.")}</p>)}@@ -232,17 +242,49 @@ export function EditMemberDialog({<p className="text-xs text-neutral-500 dark:text-neutral-300 mt-1">{t("Remove this member from the organization.")}</p>- <Button variant="destructive" size="sm" className="mt-2" onClick={handleRemove} disabled={isRemoving}>- {isRemoving ? t("Removing...") : t("Remove Member")}- </Button>+ <AlertDialog+ open={confirmRemoveOpen}+ onOpenChange={next => {+ if (!isRemoving) setConfirmRemoveOpen(next);+ }}+ >+ <AlertDialogTrigger asChild>+ <Button variant="destructive" size="sm" className="mt-2">+ {t("Remove Member")}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Remove this member?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("{name} will immediately lose access to this organization's sites and data.", {+ name: member.user.name || member.user.email,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isRemoving}>{t("Cancel")}</AlertDialogCancel>+ {/* A plain Button, not AlertDialogAction, so the dialog stays open until the request settles+ (handleRemove closes it on success). `loading` keeps its width while pending. */}+ <Button+ variant="destructive"+ loading={isRemoving}+ loadingLabel={t("Removing...")}+ onClick={handleRemove}+ >+ {t("Remove member")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div></div><DialogFooter><Button variant="outline" onClick={onClose}>{t("Cancel")}</Button>- <Button onClick={handleSave} disabled={isSaving} variant="success">- {isSaving ? t("Saving...") : t("Save Changes")}+ <Button onClick={handleSave} loading={isSaving} loadingLabel={t("Saving...")} variant="success">+ {t("Save Changes")}</Button></DialogFooter></DialogContent>diff --git a/client/src/app/settings/organization/components/Invitations.test.tsx b/client/src/app/settings/organization/components/Invitations.test.tsxnew file mode 100644index 000000000..1a99beda0--- /dev/null+++ b/client/src/app/settings/organization/components/Invitations.test.tsx@@ -0,0 +1,117 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { Invitations } from "./Invitations";++const mocks = vi.hoisted(() => ({+ cancelInvitation: vi.fn(),+ refetch: vi.fn(),+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, unknown>) =>+ values ? message.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key])) : message,+}));++vi.mock("../../../../api/admin/hooks/useOrganizations", () => ({+ useOrganizationInvitations: () => ({+ data: [+ {+ id: "inv-1",+ email: "[email protected]",+ role: "member",+ status: "pending",+ expiresAt: "2026-10-05T00:00:00.000Z",+ },+ ],+ refetch: mocks.refetch,+ isLoading: false,+ }),+}));++vi.mock("../../../../lib/auth", () => ({+ authClient: { organization: { cancelInvitation: mocks.cancelInvitation } },+}));++vi.mock("@/components/ui/sonner", () => ({+ toast: { success: mocks.toastSuccess, error: mocks.toastError },+}));++function openConfirmation() {+ render(<Invitations organizationId="org-1" isOwner />);+ fireEvent.click(screen.getByRole("button", { name: "Cancel invitation for [email protected]" }));+ return screen.getByRole("alertdialog");+}++beforeEach(() => {+ mocks.cancelInvitation.mockResolvedValue({ data: {}, error: null });+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("Invitations", () => {+ it("asks before cancelling, and keeping the invitation does nothing", () => {+ const dialog = openConfirmation();+ expect(dialog.textContent).toContain("The invitation sent to [email protected] will stop working.");++ fireEvent.click(screen.getByRole("button", { name: "Keep invitation" }));++ expect(screen.queryByRole("alertdialog")).toBeNull();+ expect(mocks.cancelInvitation).not.toHaveBeenCalled();+ });++ it("cancels once confirmed, then refetches and closes", async () => {+ openConfirmation();+ fireEvent.click(screen.getByRole("button", { name: "Cancel invitation" }));++ await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());+ expect(mocks.cancelInvitation).toHaveBeenCalledWith({ invitationId: "inv-1" });+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Invitation cancelled");+ expect(mocks.refetch).toHaveBeenCalledTimes(1);+ });++ it("keeps the confirm button's label, width and focus while the request is pending", async () => {+ let settle: (value: unknown) => void = () => {};+ mocks.cancelInvitation.mockReturnValue(new Promise(resolve => (settle = resolve)));+ openConfirmation();+ const confirm = screen.getByRole("button", { name: "Cancel invitation" });+ confirm.focus();+ fireEvent.click(confirm);++ // Busy rather than disabled: it keeps focus, announces "Cancelling...", and the label stays in layout+ // (invisible under the spinner) so the button doesn't change width.+ const pending = await screen.findByRole("button", { name: "Cancelling..." });+ expect(pending).toBe(confirm);+ expect(confirm.getAttribute("aria-busy")).toBe("true");+ expect(confirm.getAttribute("aria-disabled")).toBe("true");+ expect(confirm.hasAttribute("disabled")).toBe(false);+ expect(confirm.textContent).toBe("Cancel invitation");+ expect(document.activeElement).toBe(confirm);+ expect(screen.getByRole("button", { name: "Keep invitation" }).hasAttribute("disabled")).toBe(true);++ // A second click while pending doesn't send a second request.+ fireEvent.click(confirm);+ expect(mocks.cancelInvitation).toHaveBeenCalledTimes(1);++ settle({ data: {}, error: null });+ await waitFor(() => expect(screen.queryByRole("alertdialog")).toBeNull());+ });++ it("reports an error returned by better-auth instead of claiming success", async () => {+ mocks.cancelInvitation.mockResolvedValue({ data: null, error: { message: "Not allowed" } });+ openConfirmation();+ fireEvent.click(screen.getByRole("button", { name: "Cancel invitation" }));++ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Not allowed"));+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ expect(mocks.refetch).not.toHaveBeenCalled();+ // The dialog stays open so the owner can retry or back out.+ expect(screen.getByRole("alertdialog")).toBeTruthy();+ expect(screen.getByRole("button", { name: "Cancel invitation" }).hasAttribute("disabled")).toBe(false);+ });+});diff --git a/client/src/app/settings/organization/components/Invitations.tsx b/client/src/app/settings/organization/components/Invitations.tsxindex f3c4c7122..4121a3cc2 100644--- a/client/src/app/settings/organization/components/Invitations.tsx+++ b/client/src/app/settings/organization/components/Invitations.tsx@@ -4,6 +4,16 @@ import { useExtracted } from "next-intl";import { useState } from "react";import { toast } from "@/components/ui/sonner";import { useOrganizationInvitations } from "../../../../api/admin/hooks/useOrganizations";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "../../../../components/ui/alert-dialog";import { Badge } from "../../../../components/ui/badge";import { Button } from "../../../../components/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";@@ -15,9 +25,77 @@ interface InvitationsProps {isOwner: boolean;}+function CancelInvitationButton({+ invitation,+ onCancelled,+}: {+ invitation: { id: string; email: string };+ onCancelled: () => void;+}) {+ const t = useExtracted();+ const [open, setOpen] = useState(false);+ const [isCancelling, setIsCancelling] = useState(false);++ const handleCancel = async () => {+ setIsCancelling(true);+ try {+ // better-auth reports failures in the result rather than throwing.+ const { error } = await authClient.organization.cancelInvitation({+ invitationId: invitation.id,+ });+ if (error) {+ throw new Error(error.message || t("Failed to cancel invitation"));+ }+ toast.success(t("Invitation cancelled"));+ setOpen(false);+ onCancelled();+ } catch (error) {+ toast.error(error instanceof Error && error.message ? error.message : t("Failed to cancel invitation"));+ } finally {+ setIsCancelling(false);+ }+ };++ return (+ <AlertDialog+ open={open}+ onOpenChange={next => {+ if (!isCancelling) setOpen(next);+ }}+ >+ <AlertDialogTrigger asChild>+ <Button+ variant="default"+ size="sm"+ aria-label={t("Cancel invitation for {email}", { email: invitation.email })}+ >+ {t("Cancel")}+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t("Cancel this invitation?")}</AlertDialogTitle>+ <AlertDialogDescription>+ {t("The invitation sent to {email} will stop working. You can invite them again later.", {+ email: invitation.email,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel disabled={isCancelling}>{t("Keep invitation")}</AlertDialogCancel>+ {/* A plain Button, not AlertDialogAction, so the dialog stays open until the request settles+ (handleCancel closes it on success). `loading` keeps its width while pending. */}+ <Button variant="destructive" loading={isCancelling} loadingLabel={t("Cancelling...")} onClick={handleCancel}>+ {t("Cancel invitation")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}+export function Invitations({ organizationId, isOwner }: InvitationsProps) {const t = useExtracted();- const [loadingInvitationId, setLoadingInvitationId] = useState<string | null>(null);const {data: invitations,@@ -26,21 +104,6 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {} = useOrganizationInvitations(organizationId);const pendingInvitations = invitations?.filter(invitation => invitation.status === "pending") ?? [];- const handleCancelInvitation = async (invitationId: string) => {- try {- setLoadingInvitationId(invitationId);- await authClient.organization.cancelInvitation({- invitationId,- });- toast.success(t("Invitation cancelled"));- refetchInvitations();- } catch (error: any) {- toast.error(error.message || t("Failed to cancel invitation"));- } finally {- setLoadingInvitationId(null);- }- };-return (<Card className="w-full"><CardHeader className="pb-2">@@ -88,7 +151,11 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {<TableRow key={invitation.id}><TableCell>{invitation.email}</TableCell><TableCell className="capitalize">- {invitation.role === "admin" ? t("Admin") : invitation.role === "owner" ? t("Owner") : t("Member")}+ {invitation.role === "admin"+ ? t("Admin")+ : invitation.role === "owner"+ ? t("Owner")+ : t("Member")}</TableCell><TableCell><Badge variant="secondary">{t("Pending")}</Badge>@@ -99,14 +166,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {{isOwner && (<TableCell className="text-right">{invitation.status === "pending" && (- <Button- variant="default"- size="sm"- disabled={loadingInvitationId === invitation.id}- onClick={() => handleCancelInvitation(invitation.id)}- >- {loadingInvitationId === invitation.id ? t("Processing...") : t("Cancel")}- </Button>+ <CancelInvitationButton invitation={invitation} onCancelled={refetchInvitations} />)}</TableCell>)}diff --git a/client/src/components/SiteSettings/GeneralTab.tsx b/client/src/components/SiteSettings/GeneralTab.tsxindex 16f6374c9..9b714938b 100644--- a/client/src/components/SiteSettings/GeneralTab.tsx+++ b/client/src/components/SiteSettings/GeneralTab.tsx@@ -7,6 +7,7 @@ import { useRouter } from "next/navigation";import { useState, useCallback, ReactNode } from "react";import { toast } from "@/components/ui/sonner";+import { HoldToConfirm } from "@/components/interior/hold-to-confirm";import {AlertDialog,AlertDialogAction,@@ -173,19 +174,20 @@ export function GeneralTab({};const handleDelete = async () => {+ setIsDeleting(true);try {- setIsDeleting(true);await deleteSite(siteMetadata.siteId);- toast.success(t("Site deleted successfully"));- router.push("/");- onClose?.();- refreshSiteLists();} catch (error) {console.error("Error deleting site:", error);toast.error(t("Failed to delete site"));- } finally {setIsDeleting(false);+ return;}+ // Stays pending on success: the dialog closes and we navigate away, so the button must not re-arm meanwhile.+ toast.success(t("Site deleted successfully"));+ router.push("/");+ onClose?.();+ refreshSiteLists();};const handleMove = async () => {@@ -279,9 +281,11 @@ export function GeneralTab({<Buttonvariant="outline"onClick={handleNameChange}- disabled={isChangingName || newName === siteMetadata.name || disabled}+ loading={isChangingName}+ loadingLabel={t("Updating...")}+ disabled={newName === siteMetadata.name || disabled}>- {isChangingName ? t("Updating...") : t("Update")}+ {t("Update")}</Button></div></div>@@ -310,9 +314,11 @@ export function GeneralTab({<Buttonvariant="outline"onClick={handleDomainChange}- disabled={isChangingDomain || newDomain === siteMetadata.domain || disabled}+ loading={isChangingDomain}+ loadingLabel={t("Updating...")}+ disabled={newDomain === siteMetadata.domain || disabled}>- {isChangingDomain ? t("Updating...") : t("Update")}+ {t("Update")}</Button></div></div>@@ -375,8 +381,8 @@ export function GeneralTab({</div><AlertDialog><AlertDialogTrigger asChild>- <Button variant="outline" disabled={!targetOrgId || isMoving}>- {isMoving ? t("Moving...") : t("Move")}+ <Button variant="outline" loading={isMoving} loadingLabel={t("Moving...")} disabled={!targetOrgId}>+ {t("Move")}</Button></AlertDialogTrigger><AlertDialogContent>@@ -394,8 +400,9 @@ export function GeneralTab({</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>+ {/* Closes on click; the Move button shows the request as it runs. */}<AlertDialogAction onClick={handleMove} disabled={isMoving}>- {isMoving ? t("Moving...") : t("Yes, move site")}+ {t("Yes, move site")}</AlertDialogAction></AlertDialogFooter></AlertDialogContent>@@ -419,7 +426,11 @@ export function GeneralTab({{t("Delete Site")}</Button></AlertDialogTrigger>- <AlertDialogContent>+ <AlertDialogContent+ onEscapeKeyDown={event => {+ if (isDeleting) event.preventDefault();+ }}+ ><AlertDialogHeader><AlertDialogTitle>{t("Are you absolutely sure?")}</AlertDialogTitle><AlertDialogDescription>@@ -430,10 +441,10 @@ export function GeneralTab({</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancel>{t("Cancel")}</AlertDialogCancel>- <AlertDialogAction onClick={handleDelete} disabled={isDeleting} variant="destructive">- {isDeleting ? t("Deleting...") : t("Yes, delete site")}- </AlertDialogAction>+ <AlertDialogCancel disabled={isDeleting}>{t("Cancel")}</AlertDialogCancel>+ <HoldToConfirm onConfirm={handleDelete} pending={isDeleting} pendingLabel={t("Deleting...")}>+ {t("Hold to delete site")}+ </HoldToConfirm></AlertDialogFooter></AlertDialogContent></AlertDialog>diff --git a/client/src/components/interior/hold-to-confirm.test.tsx b/client/src/components/interior/hold-to-confirm.test.tsxnew file mode 100644index 000000000..65175ccf6--- /dev/null+++ b/client/src/components/interior/hold-to-confirm.test.tsx@@ -0,0 +1,447 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";++import { HoldToConfirm, useHoldToConfirm, type UseHoldToConfirmOptions } from "./hold-to-confirm";++vi.mock("next-intl", () => ({+ useExtracted: () => (message: string, values?: Record<string, unknown>) =>+ values ? message.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key])) : message,+}));++const DURATION = 1000;+// Fake rAF fires every 16 ms, and the clock's first frame only starts it, so a hold lands within+// a couple of frames of its duration. Assertions allow that much slack.+const FRAME = 16;++const onConfirm = vi.fn();+const onAbort = vi.fn();++let hold: ReturnType<typeof useHoldToConfirm>;++function Harness(options: Partial<UseHoldToConfirmOptions>) {+ hold = useHoldToConfirm({ onConfirm, onAbort, duration: DURATION, ...options });+ return (+ <button type="button" data-phase={hold.phase} {...hold.bind}>+ Hold+ </button>+ );+}++function advance(ms: number) {+ act(() => {+ vi.advanceTimersByTime(ms);+ });+}++function press(button: HTMLElement, point = { clientX: 20, clientY: 20 }) {+ fireEvent.pointerDown(button, { pointerId: 1, pointerType: "mouse", button: 0, ...point });+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "setTimeout", "clearTimeout"] });+});++afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.clearAllMocks();+});++describe("useHoldToConfirm", () => {+ it("fills linearly with held time and confirms once the duration is reached", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ press(button);+ expect(hold.phase).toBe("holding");++ advance(250 + FRAME);+ expect(hold.progress.get()).toBeCloseTo(0.25, 1);+ advance(250);+ expect(hold.progress.get()).toBeCloseTo(0.5, 1);+ advance(DURATION / 2 - 3 * FRAME);+ expect(hold.phase).toBe("holding");+ expect(onConfirm).not.toHaveBeenCalled();++ advance(4 * FRAME);+ expect(hold.phase).toBe("committed");+ expect(hold.progress.get()).toBe(1);+ expect(onConfirm).toHaveBeenCalledTimes(1);++ // Letting go after the commit changes nothing.+ fireEvent.pointerUp(button, { pointerId: 1 });+ advance(DURATION);+ expect(hold.phase).toBe("committed");+ expect(onConfirm).toHaveBeenCalledTimes(1);+ expect(onAbort).not.toHaveBeenCalled();+ });++ it("drains 2.5x faster after an early release and never confirms", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ press(button);+ advance(800 + FRAME);+ fireEvent.pointerUp(button, { pointerId: 1 });+ expect(hold.phase).toBe("releasing");+ expect(onAbort).toHaveBeenCalledTimes(1);++ // 160 ms of draining removes 400 ms of held time.+ advance(160);+ expect(hold.progress.get()).toBeCloseTo(0.4, 1);++ advance(200);+ expect(hold.phase).toBe("idle");+ expect(hold.progress.get()).toBe(0);+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("resumes from the current fill when pressed again mid-drain", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ press(button);+ advance(800 + FRAME);+ fireEvent.pointerUp(button, { pointerId: 1 });+ advance(160); // ~400 ms of held time left++ press(button);+ expect(hold.phase).toBe("holding");+ const resumedAt = hold.progress.get();+ expect(resumedAt).toBeGreaterThan(0.3);++ // A fresh hold would need the whole duration; this one only needs the remainder.+ advance((1 - resumedAt) * DURATION - 3 * FRAME);+ expect(hold.phase).toBe("holding");+ advance(4 * FRAME);+ expect(hold.phase).toBe("committed");+ expect(onConfirm).toHaveBeenCalledTimes(1);+ });++ it("holds with Space or Enter, ignoring key repeat", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ fireEvent.keyDown(button, { key: "Enter" });+ expect(hold.phase).toBe("holding");+ advance(300);+ fireEvent.keyUp(button, { key: "Enter" });+ expect(hold.phase).toBe("releasing");++ // Auto-repeat from a key that is still down must not restart the hold.+ fireEvent.keyDown(button, { key: "Enter", repeat: true });+ expect(hold.phase).toBe("releasing");+ advance(DURATION);+ expect(hold.phase).toBe("idle");++ fireEvent.keyDown(button, { key: " " });+ expect(hold.phase).toBe("holding");+ advance(DURATION + 2 * FRAME);+ expect(onConfirm).toHaveBeenCalledTimes(1);+ });++ it("swallows the confirming keys so they never click", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ expect(fireEvent.keyDown(button, { key: "Enter" })).toBe(false);+ expect(fireEvent.keyDown(button, { key: " ", repeat: true })).toBe(false);+ expect(fireEvent.keyDown(button, { key: "a" })).toBe(true);+ });++ it("cancels at once on Escape, wherever focus is", () => {+ render(<Harness />);+ press(screen.getByRole("button"));+ advance(600);++ fireEvent.keyDown(document.body, { key: "Escape" });+ expect(hold.phase).toBe("idle");+ expect(hold.progress.get()).toBe(0);+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("lets go when the window loses focus, the tab is hidden or the button blurs", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ press(button);+ advance(300);+ fireEvent.blur(window);+ expect(hold.phase).toBe("releasing");+ advance(DURATION);++ press(button);+ advance(300);+ Object.defineProperty(document, "hidden", { configurable: true, get: () => true });+ try {+ fireEvent(document, new Event("visibilitychange"));+ } finally {+ delete (document as { hidden?: boolean }).hidden;+ }+ expect(hold.phase).toBe("releasing");+ advance(DURATION);++ press(button);+ advance(300);+ fireEvent.blur(button);+ expect(hold.phase).toBe("releasing");+ advance(DURATION);++ expect(hold.phase).toBe("idle");+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("lets go when the pointer wanders more than 10 px", () => {+ render(<Harness />);+ const button = screen.getByRole("button");++ press(button, { clientX: 10, clientY: 10 });+ fireEvent.pointerMove(button, { pointerId: 1, clientX: 16, clientY: 16 }); // ~8.5 px+ expect(hold.phase).toBe("holding");++ fireEvent.pointerMove(button, { pointerId: 1, clientX: 21, clientY: 10 }); // 11 px+ expect(hold.phase).toBe("releasing");+ });++ it("ignores secondary mouse buttons", () => {+ render(<Harness />);+ fireEvent.pointerDown(screen.getByRole("button"), { pointerId: 1, pointerType: "mouse", button: 2 });+ expect(hold.phase).toBe("idle");+ });++ it("does nothing while disabled, and drops a hold that becomes disabled", () => {+ const { rerender } = render(<Harness disabled />);+ const button = screen.getByRole("button");++ press(button);+ fireEvent.keyDown(button, { key: "Enter" });+ advance(DURATION * 2);+ expect(hold.phase).toBe("idle");++ rerender(<Harness />);+ press(button);+ advance(600);+ expect(hold.phase).toBe("holding");++ rerender(<Harness disabled />);+ expect(hold.phase).toBe("idle");+ expect(hold.progress.get()).toBe(0);+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it("stops its clock on unmount", () => {+ const { unmount } = render(<Harness />);+ press(screen.getByRole("button"));+ advance(600);++ unmount();+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ });+});++describe("HoldToConfirm", () => {+ function renderButton(props: { pending?: boolean; disabled?: boolean } = {}) {+ return render(+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={DURATION} {...props}>+ Hold to delete site+ </HoldToConfirm>+ );+ }++ it("swaps to the pending label sequentially on commit, never showing both labels at once", async () => {+ // Real time: framer drives the label opacity from its own frame loop.+ vi.useRealTimers();+ const { container } = render(+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={40}>+ Hold to delete site+ </HoldToConfirm>+ );+ const button = screen.getByRole("button", { name: "Hold to delete site" });+ // One pair per layer: the resting faces and the inverted faces inside the fill.+ const labels = Array.from(container.querySelectorAll<HTMLElement>('[data-face="label"]'));+ const pendings = Array.from(container.querySelectorAll<HTMLElement>('[data-face="pending"]'));+ expect(labels).toHaveLength(2);+ expect(pendings).toHaveLength(2);+ const opacity = (face: HTMLElement) => Number(face.style.opacity || "1");++ fireEvent.keyDown(button, { key: "Enter" });+ await waitFor(() => expect(button.getAttribute("data-phase")).toBe("committed"));++ let sawOutgoingFading = false;+ for (let elapsed = 0; elapsed < 600; elapsed += 8) {+ labels.forEach((label, layer) => {+ const out = opacity(label);+ const incoming = opacity(pendings[layer]);+ if (out > 0 && out < 1) sawOutgoingFading = true;+ expect(Math.min(out, incoming), `both labels visible at ${elapsed} ms`).toBeLessThan(0.02);+ });+ await new Promise(resolve => setTimeout(resolve, 8));+ }++ expect(sawOutgoingFading).toBe(true);+ for (const layer of [0, 1]) {+ expect(opacity(labels[layer])).toBe(0);+ expect(opacity(pendings[layer])).toBe(1);+ }+ });++ it("is named by its visible label and described by the hold hint", () => {+ renderButton();+ const button = screen.getByRole("button", { name: "Hold to delete site" });++ const hint = document.getElementById(button.getAttribute("aria-describedby") ?? "");+ expect(hint?.textContent).toBe("Press and hold to confirm. Releasing early cancels.");+ expect(button.getAttribute("type")).toBe("button");+ expect(button.getAttribute("aria-disabled")).toBeNull();+ });++ it("announces the pending label on commit and stays inert while pending", () => {+ const { rerender } = renderButton();+ const button = screen.getByRole("button", { name: "Hold to delete site" });+ expect(screen.getByRole("status").textContent).toBe("");++ fireEvent.keyDown(button, { key: "Enter" });+ advance(DURATION + 2 * FRAME);+ expect(onConfirm).toHaveBeenCalledTimes(1);++ rerender(+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={DURATION} pending>+ Hold to delete site+ </HoldToConfirm>+ );+ expect(screen.getByRole("status").textContent).toBe("Deleting...");+ expect(button.getAttribute("aria-disabled")).toBe("true");+ expect(screen.getByRole("button", { name: "Deleting..." })).toBe(button);++ fireEvent.keyUp(button, { key: "Enter" });+ fireEvent.keyDown(button, { key: "Enter" });+ advance(DURATION * 2);+ expect(onConfirm).toHaveBeenCalledTimes(1);+ expect(button.getAttribute("data-phase")).toBe("committed");+ });++ it("re-arms when the pending action ends without unmounting it (it failed)", () => {+ const { rerender } = renderButton();+ const button = screen.getByRole("button");++ fireEvent.keyDown(button, { key: "Enter" });+ advance(DURATION + 2 * FRAME);+ rerender(+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={DURATION} pending>+ Hold to delete site+ </HoldToConfirm>+ );+ rerender(+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={DURATION} pending={false}>+ Hold to delete site+ </HoldToConfirm>+ );++ expect(button.getAttribute("data-phase")).toBe("idle");+ expect(button.getAttribute("aria-disabled")).toBeNull();+ expect(screen.getByRole("status").textContent).toBe("");+ });++ it("re-arms after a beat when the caller never goes pending", () => {+ renderButton();+ const button = screen.getByRole("button");++ fireEvent.keyDown(button, { key: " " });+ advance(DURATION + 2 * FRAME);+ expect(button.getAttribute("data-phase")).toBe("committed");++ advance(1500);+ expect(button.getAttribute("data-phase")).toBe("idle");+ });++ it("stays inert while disabled", () => {+ renderButton({ disabled: true });+ const button = screen.getByRole("button", { name: "Hold to delete site" });+ expect(button.getAttribute("aria-disabled")).toBe("true");++ press(button);+ fireEvent.keyDown(button, { key: "Enter" });+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ expect(button.getAttribute("data-phase")).toBe("idle");+ });+});++describe("HoldToConfirm inside an AlertDialog", () => {+ const onOpenChange = vi.fn();++ function renderDialog() {+ return render(+ <AlertDialog open onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogTitle>Delete this site?</AlertDialogTitle>+ <AlertDialogDescription>This cannot be undone.</AlertDialogDescription>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <HoldToConfirm onConfirm={onConfirm} pendingLabel="Deleting..." duration={DURATION}>+ Hold to delete site+ </HoldToConfirm>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+ }++ it("neither closes nor confirms on a click or an early release", () => {+ renderDialog();+ const button = screen.getByRole("button", { name: "Hold to delete site" });++ press(button);+ fireEvent.pointerUp(button, { pointerId: 1 });+ fireEvent.click(button);+ press(button);+ advance(DURATION / 2);+ fireEvent.pointerUp(button, { pointerId: 1 });+ advance(DURATION * 2);++ expect(onConfirm).not.toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(screen.getByRole("alertdialog")).toBeTruthy();+ });++ it("confirms after a full hold and leaves closing to the caller", () => {+ renderDialog();+ const button = screen.getByRole("button", { name: "Hold to delete site" });++ press(button);+ advance(DURATION + 2 * FRAME);+ fireEvent.pointerUp(button, { pointerId: 1 });+ fireEvent.click(button);++ expect(onConfirm).toHaveBeenCalledTimes(1);+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it("cancels the hold when Escape dismisses the dialog", () => {+ renderDialog();+ const button = screen.getByRole("button", { name: "Hold to delete site" });++ button.focus();+ fireEvent.keyDown(button, { key: " " });+ advance(DURATION * 0.9);+ fireEvent.keyDown(button, { key: "Escape" });++ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(button.getAttribute("data-phase")).toBe("idle");+ advance(DURATION * 2);+ expect(onConfirm).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/interior/hold-to-confirm.tsx b/client/src/components/interior/hold-to-confirm.tsxnew file mode 100644index 000000000..d1b71b34e--- /dev/null+++ b/client/src/components/interior/hold-to-confirm.tsx@@ -0,0 +1,358 @@+// Adapted from interior.dev "Hold to Confirm" (MIT). See ./THIRD_PARTY_LICENSES.md+"use client";++import { motion, useMotionValue, useTransform, type Transition } from "framer-motion";+import { useExtracted } from "next-intl";+import {+ useCallback,+ useEffect,+ useId,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent as ReactMouseEvent,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+} from "react";++import { FADE_IN, FADE_OUT } from "@/lib/motion";+import { cn } from "@/lib/utils";++export type HoldPhase = "idle" | "holding" | "releasing" | "committed";++// Long enough to be deliberate, short enough not to feel like a punishment.+export const HOLD_TO_CONFIRM_DURATION = 1600;+// Letting go drains the fill this many times faster than holding fills it.+const RELEASE_RATE = 2.5;+// A pointer that wanders further than this (px) from where it pressed is not holding any more.+const MOVE_TOLERANCE = 10;+// The most a single frame may add, so a janky or throttled frame can't jump the fill.+const MAX_FRAME_MS = 64;+// A commit the caller never marks as pending re-arms the button after this long.+const RESET_AFTER_MS = 1500;+// Label swaps are sequential: the incoming label only starts once the outgoing one has fully faded, so the two+// never show on top of each other in their shared cell.+const LABEL_OUT: Transition = FADE_OUT;+const LABEL_IN: Transition = { ...FADE_IN, delay: FADE_OUT.duration };++export type UseHoldToConfirmOptions = {+ onConfirm: () => void;+ onAbort?: () => void;+ duration?: number;+ releaseRate?: number;+ moveTolerance?: number;+ haptic?: boolean;+ disabled?: boolean;+};++/**+ * The hold clock. `progress` (0–1) is written from a rAF loop that accumulates held time and drains+ * `releaseRate`× faster after release; pressing again mid-drain resumes from the current fill. The fill is+ * the clock itself, so it stays linear and time-driven under reduced motion too (upstream jumped straight+ * to 100% on press, which hid the progress).+ */+export function useHoldToConfirm({+ onConfirm,+ onAbort,+ duration = HOLD_TO_CONFIRM_DURATION,+ releaseRate = RELEASE_RATE,+ moveTolerance = MOVE_TOLERANCE,+ haptic = true,+ disabled = false,+}: UseHoldToConfirmOptions) {+ const [phase, setPhase] = useState<HoldPhase>("idle");+ const progress = useMotionValue(0);++ const phaseRef = useRef<HoldPhase>("idle");+ const down = useRef(false);+ const elapsed = useRef(0);+ const last = useRef<number | null>(null);+ const raf = useRef(0);+ const origin = useRef<{ x: number; y: number } | null>(null);++ const confirmRef = useRef(onConfirm);+ const abortRef = useRef(onAbort);+ useEffect(() => {+ confirmRef.current = onConfirm;+ abortRef.current = onAbort;+ });++ const goTo = useCallback((next: HoldPhase) => {+ phaseRef.current = next;+ setPhase(next);+ }, []);++ const stop = useCallback(() => {+ if (raf.current) cancelAnimationFrame(raf.current);+ raf.current = 0;+ last.current = null;+ }, []);++ const reset = useCallback(() => {+ stop();+ down.current = false;+ elapsed.current = 0;+ origin.current = null;+ progress.set(0);+ goTo("idle");+ }, [goTo, progress, stop]);++ const begin = useCallback(+ (point?: { x: number; y: number }) => {+ if (disabled || phaseRef.current === "holding" || phaseRef.current === "committed") return;+ origin.current = point ?? null;+ down.current = true;+ goTo("holding");+ // Pressed again mid-drain: the clock is still running and picks the hold back up.+ if (raf.current) return;++ const loop = (now: number) => {+ // Only rAF timestamps are compared, so the first frame just starts the clock.+ const dt = last.current === null ? 0 : Math.min(MAX_FRAME_MS, Math.max(0, now - last.current));+ last.current = now;+ elapsed.current += down.current ? dt : -dt * releaseRate;++ if (elapsed.current >= duration) {+ stop();+ elapsed.current = duration;+ down.current = false;+ origin.current = null;+ progress.set(1);+ goTo("committed");+ if (haptic) navigator.vibrate?.(14);+ confirmRef.current();+ return;+ }++ if (!down.current && elapsed.current <= 0) {+ stop();+ elapsed.current = 0;+ origin.current = null;+ progress.set(0);+ goTo("idle");+ return;+ }++ progress.set(elapsed.current / duration);+ raf.current = requestAnimationFrame(loop);+ };++ raf.current = requestAnimationFrame(loop);+ },+ [disabled, duration, releaseRate, haptic, goTo, progress, stop]+ );++ const release = useCallback(() => {+ if (phaseRef.current !== "holding") return;+ down.current = false;+ origin.current = null;+ goTo("releasing");+ abortRef.current?.();+ }, [goTo]);++ // Leaving the window or tab lets go. Escape cancels outright, wherever focus is (Safari doesn't focus a+ // clicked button, so a mouse hold never sees the key on the button itself).+ useEffect(() => {+ const onWindowBlur = () => release();+ const onVisibilityChange = () => {+ if (document.hidden) release();+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ if (phaseRef.current === "holding" || phaseRef.current === "releasing") reset();+ };+ window.addEventListener("blur", onWindowBlur);+ document.addEventListener("visibilitychange", onVisibilityChange);+ document.addEventListener("keydown", onKeyDown, true);+ return () => {+ window.removeEventListener("blur", onWindowBlur);+ document.removeEventListener("visibilitychange", onVisibilityChange);+ document.removeEventListener("keydown", onKeyDown, true);+ };+ }, [release, reset]);++ // Disabled mid-hold (e.g. the typed confirmation stopped matching): drop the hold.+ useEffect(() => {+ if (disabled && (phaseRef.current === "holding" || phaseRef.current === "releasing")) reset();+ }, [disabled, reset]);++ // Never leave a clock running after unmount (e.g. the dialog closed mid-hold).+ useEffect(() => stop, [stop]);++ const bind = {+ onPointerDown: (event: ReactPointerEvent<HTMLElement>) => {+ if (disabled || (event.pointerType === "mouse" && event.button !== 0)) return;+ event.currentTarget.setPointerCapture?.(event.pointerId);+ begin({ x: event.clientX, y: event.clientY });+ },+ onPointerMove: (event: ReactPointerEvent<HTMLElement>) => {+ const from = origin.current;+ if (phaseRef.current !== "holding" || !from) return;+ if (Math.hypot(event.clientX - from.x, event.clientY - from.y) > moveTolerance) release();+ },+ onPointerUp: release,+ onPointerCancel: release,+ onPointerLeave: release,+ onLostPointerCapture: release,+ onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {+ if (event.key !== " " && event.key !== "Enter") return;+ // Swallow the key so it never becomes a click. A held key auto-repeats; only a fresh press starts a hold.+ event.preventDefault();+ if (!event.repeat) begin();+ },+ onKeyUp: (event: ReactKeyboardEvent<HTMLElement>) => {+ if (event.key === " " || event.key === "Enter") release();+ },+ onBlur: release,+ // Holding is the only way to confirm; a click does nothing (and never reaches a parent once committed).+ onClick: (event: ReactMouseEvent<HTMLElement>) => {+ event.preventDefault();+ if (phaseRef.current === "committed") event.stopPropagation();+ },+ onContextMenu: (event: ReactMouseEvent<HTMLElement>) => event.preventDefault(),+ };++ return { bind, phase, progress, reset };+}++export type HoldToConfirmProps = {+ /** Runs once, when a hold completes. Handle errors inside it and reflect the work in `pending`. */+ onConfirm: () => void;+ /** The visible label, e.g. "Hold to delete site". */+ children: ReactNode;+ /** The confirmed action is running: the button stays full and inert. When it turns false again while the+ * button is still mounted (the action failed), the button re-arms. */+ pending?: boolean;+ /** Replaces the label, and is announced, once the hold commits, e.g. "Deleting...". */+ pendingLabel?: string;+ duration?: number;+ disabled?: boolean;+ className?: string;+};++/**+ * A destructive button that confirms by being pressed and held (pointer, or Space/Enter). Render it as a plain+ * child of an AlertDialog footer, not as an AlertDialogAction, so the dialog stays open until the hold commits.+ */+export function HoldToConfirm({+ onConfirm,+ children,+ pending = false,+ pendingLabel,+ duration = HOLD_TO_CONFIRM_DURATION,+ disabled = false,+ className,+}: HoldToConfirmProps) {+ const t = useExtracted();+ const hintId = useId();+ const { bind, phase, progress, reset } = useHoldToConfirm({ onConfirm, duration, disabled: disabled || pending });+ const clipPath = useTransform(progress, value => `inset(0 ${(1 - value) * 100}% 0 0)`);++ const committed = phase === "committed";+ const busy = committed || pending;++ // After a commit the caller's `pending` takes over. If it falls again while we're still mounted, the action+ // failed (or finished without navigating away), so re-arm. If it never rises, re-arm after a beat.+ const sawPending = useRef(false);+ useEffect(() => {+ if (pending) {+ sawPending.current = true;+ return;+ }+ if (!committed) {+ sawPending.current = false;+ return;+ }+ if (sawPending.current) {+ sawPending.current = false;+ reset();+ return;+ }+ const timer = setTimeout(reset, RESET_AFTER_MS);+ return () => clearTimeout(timer);+ }, [committed, pending, reset]);++ return (+ <>+ {/* Outside the button so they stay out of its accessible name. */}+ <span id={hintId} className="sr-only">+ {t("Press and hold to confirm. Releasing early cancels.")}+ </span>+ <span role="status" aria-live="polite" className="sr-only">+ {committed ? (pendingLabel ?? t("Confirmed")) : ""}+ </span>+ <button+ type="button"+ aria-describedby={hintId}+ aria-disabled={disabled || busy || undefined}+ data-phase={phase}+ {...bind}+ style={{ touchAction: "manipulation", WebkitTouchCallout: "none" }}+ className={cn(+ "relative isolate inline-grid h-9 select-none place-items-center overflow-hidden whitespace-nowrap rounded-lg border bg-transparent px-3 text-sm font-medium text-red-600 transition-colors dark:text-red-400",+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:focus-visible:ring-neutral-300",+ // The edge darkens to the fill color once armed, so the unfilled part reads as "in progress".+ phase !== "idle" || pending+ ? "border-red-600"+ : cn(+ "border-red-300 dark:border-red-500/40",+ !disabled && "hover:border-red-400 dark:hover:border-red-500/60"+ ),+ disabled+ ? "cursor-not-allowed opacity-50"+ : busy+ ? "cursor-default"+ : "cursor-pointer hover:bg-red-50 dark:hover:bg-red-500/10",+ className+ )}+ >+ <Faces busy={busy} pendingLabel={pendingLabel}>+ {children}+ </Faces>+ {/* The fill: the same faces in inverted colors, revealed left to right as the hold progresses. */}+ <motion.span+ aria-hidden+ style={{ clipPath }}+ className="absolute inset-0 grid place-items-center bg-red-600 px-3 text-white dark:bg-red-700 dark:text-neutral-50"+ >+ <Faces busy={busy} pendingLabel={pendingLabel}>+ {children}+ </Faces>+ </motion.span>+ </button>+ </>+ );+}++function Faces({ busy, pendingLabel, children }: { busy: boolean; pendingLabel?: string; children: ReactNode }) {+ const swapped = busy && pendingLabel !== undefined;++ // Both faces share one grid cell, so the button is as wide as the longer label and never jumps. Whichever face+ // is leaving fades out first; the arriving one waits for it (LABEL_IN's delay), so they never overlap.+ return (+ <span className="col-start-1 row-start-1 grid">+ <motion.span+ initial={false}+ animate={{ opacity: swapped ? 0 : 1 }}+ transition={swapped ? LABEL_OUT : LABEL_IN}+ aria-hidden={swapped || undefined}+ data-face="label"+ className="col-start-1 row-start-1 flex items-center justify-center gap-2 [&_svg]:size-4 [&_svg]:shrink-0"+ >+ {children}+ </motion.span>+ {pendingLabel !== undefined && (+ <motion.span+ initial={false}+ animate={{ opacity: swapped ? 1 : 0 }}+ transition={swapped ? LABEL_IN : LABEL_OUT}+ aria-hidden={!swapped || undefined}+ data-face="pending"+ className="col-start-1 row-start-1 flex items-center justify-center"+ >+ {pendingLabel}+ </motion.span>+ )}+ </span>+ );+}