Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

feat(ui): add a width-stable loading state to Button, and make Enter submit Add Site and signup (#1253)

Goldflagf1900d48a58f
diff --git a/client/src/app/[site]/EnableFeatureButtons.test.tsx b/client/src/app/[site]/EnableFeatureButtons.test.tsx
new file mode 100644
index 000000000..0a1b189ea
--- /dev/null
+++ b/client/src/app/[site]/EnableFeatureButtons.test.tsx
@@ -0,0 +1,102 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { EnableErrorTracking } from "./errors/components/EnableErrorTracking";
+import { EnableWebVitals } from "./performance/components/EnableWebVitals";
+import { EnableSessionReplay } from "./replay/components/EnableSessionReplay";
+
+const mocks = vi.hoisted(() => ({
+ updateSiteConfig: vi.fn(),
+ refetch: vi.fn(),
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+ site: {} as Record<string, boolean>,
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, string>) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => values?.[key] ?? ""),
+}));
+vi.mock("next/navigation", () => ({ useParams: () => ({ site: "7" }) }));
+vi.mock("@/api/admin/endpoints", () => ({ updateSiteConfig: mocks.updateSiteConfig }));
+vi.mock("@/api/admin/hooks/useSites", () => ({
+ useGetSite: () => ({ data: mocks.site, isLoading: false, refetch: mocks.refetch }),
+}));
+vi.mock("@/components/ui/sonner", () => ({
+ toast: { success: mocks.toastSuccess, error: mocks.toastError },
+}));
+vi.mock("@/lib/const", async importOriginal => ({ ...(await importOriginal<object>()), IS_CLOUD: false }));
+vi.mock("@/lib/subscription/useStripeSubscription", () => ({ useStripeSubscription: () => ({ data: undefined }) }));
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>(res => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+beforeEach(() => {
+ mocks.site = {};
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe.each([
+ { name: "Web Vitals", Banner: EnableWebVitals, config: { webVitals: true }, done: "Web Vitals collection enabled" },
+ {
+ name: "error tracking",
+ Banner: EnableErrorTracking,
+ config: { trackErrors: true },
+ done: "Error tracking enabled",
+ },
+ {
+ name: "session replay",
+ Banner: EnableSessionReplay,
+ config: { sessionReplay: true },
+ done: "Session replay enabled",
+ },
+])("Enable $name", ({ name, Banner, config, done }) => {
+ it("stays busy until the site refetch lands, then confirms", async () => {
+ const refetch = deferred();
+ mocks.updateSiteConfig.mockResolvedValue({ success: true });
+ mocks.refetch.mockReturnValue(refetch.promise);
+ render(<Banner />);
+
+ const button = screen.getByRole("button", { name: "Enable" });
+ fireEvent.click(button);
+
+ await waitFor(() => expect(mocks.refetch).toHaveBeenCalled());
+ expect(mocks.updateSiteConfig).toHaveBeenCalledWith(7, config);
+ expect(button.getAttribute("aria-busy")).toBe("true");
+ expect(mocks.toastSuccess).not.toHaveBeenCalled();
+
+ // A second click while enabling does nothing.
+ fireEvent.click(button);
+ expect(mocks.updateSiteConfig).toHaveBeenCalledOnce();
+
+ await act(async () => refetch.resolve());
+ expect(mocks.toastSuccess).toHaveBeenCalledWith(done);
+ expect(button.hasAttribute("aria-busy")).toBe(false);
+ });
+
+ it("reports a failure and lets the user try again", async () => {
+ mocks.updateSiteConfig.mockRejectedValue(new Error("Session replay requires a Pro subscription"));
+ render(<Banner />);
+
+ const button = screen.getByRole("button", { name: "Enable" });
+ fireEvent.click(button);
+
+ await waitFor(() =>
+ expect(mocks.toastError).toHaveBeenCalledWith(
+ `Failed to enable ${name}: Session replay requires a Pro subscription`
+ )
+ );
+ expect(button.hasAttribute("aria-busy")).toBe(false);
+ expect(mocks.toastSuccess).not.toHaveBeenCalled();
+ expect(mocks.refetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
index 17744cb54..bf1c8ec85 100644
--- a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
+++ b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
@@ -3,6 +3,7 @@
import { useExtracted } from "next-intl";
import { AlertTriangle } from "lucide-react";
import { useParams } from "next/navigation";
+import { useState } from "react";
import { toast } from "@/components/ui/sonner";
import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
@@ -14,9 +15,25 @@ export function EnableErrorTracking() {
const params = useParams();
const siteId = Number(params.site);
const { data: siteMetadata, refetch } = useGetSite(siteId);
+ const [isEnabling, setIsEnabling] = useState(false);
if (siteMetadata?.trackErrors) return null;
+ const enable = async () => {
+ setIsEnabling(true);
+ try {
+ await updateSiteConfig(siteId, { trackErrors: true });
+ // Stay busy until the refetch hides this banner, so "Enable" never flashes back
+ await refetch();
+ toast.success(t("Error tracking enabled"));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ toast.error(t("Failed to enable error tracking: {message}", { message }));
+ } finally {
+ setIsEnabling(false);
+ }
+ };
+
return (
<Alert className="p-4">
<div className="flex items-start space-x-3">
@@ -27,17 +44,10 @@ export function EnableErrorTracking() {
</AlertTitle>
<AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80">
<div className="mb-2">
- {t("Error tracking captures JavaScript errors and exceptions from your application.")} <b>{t("Note:")}</b> {t("Enabling error tracking will increase your event usage.")}
+ {t("Error tracking captures JavaScript errors and exceptions from your application.")} <b>{t("Note:")}</b>{" "}
+ {t("Enabling error tracking will increase your event usage.")}
</div>
- <Button
- size="sm"
- variant="success"
- onClick={async () => {
- await updateSiteConfig(siteId, { trackErrors: true });
- toast.success(t("Error tracking enabled"));
- refetch();
- }}
- >
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
{t("Enable")}
</Button>
</AlertDescription>
diff --git a/client/src/app/[site]/goals/components/GoalFormModal.tsx b/client/src/app/[site]/goals/components/GoalFormModal.tsx
index 461f4da8a..eab1cc128 100644
--- a/client/src/app/[site]/goals/components/GoalFormModal.tsx
+++ b/client/src/app/[site]/goals/components/GoalFormModal.tsx
@@ -599,8 +599,13 @@ export default function GoalFormModal({
<Button variant="outline" type="button" onClick={onClose}>
{t("Cancel")}
</Button>
- <Button type="submit" disabled={createGoal.isPending || updateGoal.isPending} variant="success">
- {createGoal.isPending || updateGoal.isPending ? t("Saving...") : isEditMode ? t("Update") : t("Create")}
+ <Button
+ type="submit"
+ variant="success"
+ loading={createGoal.isPending || updateGoal.isPending}
+ loadingLabel={t("Saving...")}
+ >
+ {isEditMode ? t("Update") : t("Create")}
</Button>
</div>
</form>
diff --git a/client/src/app/[site]/performance/components/EnableWebVitals.tsx b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
index c9c015a79..06037c145 100644
--- a/client/src/app/[site]/performance/components/EnableWebVitals.tsx
+++ b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
@@ -3,6 +3,7 @@
import { useExtracted } from "next-intl";
import { Gauge } from "lucide-react";
import { useParams } from "next/navigation";
+import { useState } from "react";
import { toast } from "@/components/ui/sonner";
import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
@@ -14,9 +15,25 @@ export function EnableWebVitals() {
const params = useParams();
const siteId = Number(params.site);
const { data: siteMetadata, refetch } = useGetSite(siteId);
+ const [isEnabling, setIsEnabling] = useState(false);
if (siteMetadata?.webVitals) return null;
+ const enable = async () => {
+ setIsEnabling(true);
+ try {
+ await updateSiteConfig(siteId, { webVitals: true });
+ // Stay busy until the refetch hides this banner, so "Enable" never flashes back
+ await refetch();
+ toast.success(t("Web Vitals collection enabled"));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ toast.error(t("Failed to enable Web Vitals: {message}", { message }));
+ } finally {
+ setIsEnabling(false);
+ }
+ };
+
return (
<Alert className="p-4">
<div className="flex items-start space-x-3">
@@ -27,17 +44,10 @@ export function EnableWebVitals() {
</AlertTitle>
<AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80">
<div className="mb-2">
- {t("Web Vitals collection provides Core Web Vitals metrics like LCP, CLS, and INP.")} <b>{t("Note:")}</b> {t("Enabling Web Vitals will increase your event usage.")}
+ {t("Web Vitals collection provides Core Web Vitals metrics like LCP, CLS, and INP.")} <b>{t("Note:")}</b>{" "}
+ {t("Enabling Web Vitals will increase your event usage.")}
</div>
- <Button
- size="sm"
- variant="success"
- onClick={async () => {
- await updateSiteConfig(siteId, { webVitals: true });
- toast.success(t("Web Vitals collection enabled"));
- refetch();
- }}
- >
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
{t("Enable")}
</Button>
</AlertDescription>
diff --git a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
index d6c1fd272..9fa66dc49 100644
--- a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
+++ b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
@@ -3,6 +3,7 @@
import { Video } from "lucide-react";
import { useExtracted } from "next-intl";
import { useParams } from "next/navigation";
+import { useState } from "react";
import { toast } from "@/components/ui/sonner";
import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
@@ -18,11 +19,27 @@ export function EnableSessionReplay() {
const siteId = Number(params.site);
const { data: siteMetadata, isLoading, refetch } = useGetSite(siteId);
const { data: subscription } = useStripeSubscription();
+ const [isEnabling, setIsEnabling] = useState(false);
const canEnableReplay = !IS_CLOUD || planIncludesReplay(subscription);
if (isLoading || siteMetadata?.sessionReplay || !canEnableReplay) return null;
+ const enable = async () => {
+ setIsEnabling(true);
+ try {
+ await updateSiteConfig(siteId, { sessionReplay: true });
+ // Stay busy until the refetch hides this banner, so "Enable" never flashes back
+ await refetch();
+ toast.success(t("Session replay enabled"));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ toast.error(t("Failed to enable session replay: {message}", { message }));
+ } finally {
+ setIsEnabling(false);
+ }
+ };
+
return (
<Alert className="shrink-0 p-4">
<div className="flex items-start space-x-3">
@@ -37,15 +54,7 @@ export function EnableSessionReplay() {
{t("and the client will send significantly more and larger payloads.")}{" "}
<b>{t("Only enable this if you will actually use it.")}</b>
</div>
- <Button
- size="sm"
- variant="success"
- onClick={async () => {
- await updateSiteConfig(siteId, { sessionReplay: true });
- toast.success(t("Session replay enabled"));
- refetch();
- }}
- >
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
{t("Enable")}
</Button>
</AlertDescription>
diff --git a/client/src/app/components/AddSite.test.tsx b/client/src/app/components/AddSite.test.tsx
new file mode 100644
index 000000000..21c5cbd0a
--- /dev/null
+++ b/client/src/app/components/AddSite.test.tsx
@@ -0,0 +1,118 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { AddSite } from "./AddSite";
+
+const mocks = vi.hoisted(() => ({
+ addSite: vi.fn(),
+ push: vi.fn(),
+ refetch: vi.fn(),
+ setSite: vi.fn(),
+ resetStore: vi.fn(),
+}));
+
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("next/navigation", () => ({ useRouter: () => ({ push: mocks.push }) }));
+vi.mock("@/api/admin/endpoints", () => ({ addSite: mocks.addSite }));
+vi.mock("@/api/admin/hooks/useSites", () => ({
+ useGetSitesFromOrg: () => ({ data: { sites: [] }, refetch: mocks.refetch }),
+}));
+vi.mock("@/lib/auth", () => ({
+ authClient: { useActiveOrganization: () => ({ data: { id: "org_1" } }) },
+}));
+vi.mock("@/lib/const", async importOriginal => ({ ...(await importOriginal<object>()), IS_CLOUD: false }));
+vi.mock("@/lib/store", () => ({
+ resetStore: mocks.resetStore,
+ useStore: () => ({ setSite: mocks.setSite }),
+}));
+vi.mock("@/lib/subscription/useStripeSubscription", () => ({
+ useStripeSubscription: () => ({ data: undefined, isLoading: false }),
+}));
+
+beforeEach(() => {
+ // Radix radios render a hidden input inside forms and measure it.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+function openDialogAndType(domain: string) {
+ render(<AddSite />);
+ fireEvent.click(screen.getByRole("button", { name: "Add Site" }));
+ const input = screen.getByLabelText("Domain") as HTMLInputElement;
+ fireEvent.change(input, { target: { value: domain } });
+ return input;
+}
+
+describe("AddSite", () => {
+ it("adds the site when Enter is pressed in the domain field", async () => {
+ const request = deferred<{ siteId: number }>();
+ mocks.addSite.mockReturnValue(request.promise);
+ const input = openDialogAndType("Example.com");
+
+ const add = screen.getByRole("button", { name: "Add" }) as HTMLButtonElement;
+ expect(input.form).toBeTruthy();
+ expect(add.form).toBe(input.form);
+ expect(add.type).toBe("submit");
+
+ // What the browser does on Enter in a field.
+ act(() => input.form!.requestSubmit());
+
+ expect(mocks.addSite).toHaveBeenCalledWith(
+ "example.com",
+ "example.com",
+ "org_1",
+ expect.objectContaining({ type: "web" })
+ );
+
+ // Pending: same button, busy and focusable, label kept under the spinner.
+ const busy = screen.getByRole("button", { name: "Adding..." }) as HTMLButtonElement;
+ expect(busy).toBe(add);
+ expect(busy.getAttribute("aria-busy")).toBe("true");
+ expect(busy.disabled).toBe(false);
+ expect(busy.textContent).toBe("Add");
+
+ request.resolve({ siteId: 42 });
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/42"));
+ expect(mocks.setSite).toHaveBeenCalledWith("42");
+ });
+
+ it("shows the error and hands the button back when adding fails", async () => {
+ mocks.addSite.mockRejectedValue(new Error("Domain already in use"));
+ const input = openDialogAndType("example.com");
+
+ act(() => input.form!.requestSubmit());
+
+ expect(await screen.findByText("Error: Domain already in use")).toBeTruthy();
+ const add = screen.getByRole("button", { name: "Add" });
+ expect(add.hasAttribute("aria-busy")).toBe(false);
+ expect(mocks.push).not.toHaveBeenCalled();
+ });
+
+ it("keeps Add disabled until there is a domain, so an empty Enter does nothing", () => {
+ openDialogAndType("");
+
+ expect((screen.getByRole("button", { name: "Add" }) as HTMLButtonElement).disabled).toBe(true);
+ });
+});
diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsx
index bb85ae85b..b4af43eaa 100644
--- a/client/src/app/components/AddSite.tsx
+++ b/client/src/app/components/AddSite.tsx
@@ -84,6 +84,7 @@ export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disa
const [showAdvanced, setShowAdvanced] = useState(false);
const [toggles, setToggles] = useState({ ...DEFAULT_TOGGLES });
const [error, setError] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
const isMobile = siteType === "mobile";
const setToggle = (key: ToggleKey, checked: boolean) => setToggles(prev => ({ ...prev, [key]: checked }));
@@ -216,6 +217,7 @@ export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disa
return;
}
+ setIsSubmitting(true);
try {
const normalizedDomain = siteType === "web" ? normalizeDomain(domain) : domain.trim();
const siteName = name.trim() || normalizedDomain;
@@ -242,6 +244,8 @@ export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disa
} catch (error) {
setError(String(error));
return;
+ } finally {
+ setIsSubmitting(false);
}
setOpen(false);
@@ -352,96 +356,111 @@ export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disa
</DialogDescription>
</DialogHeader>
- <div className="grid gap-4 py-2">
- <RadioGroup
- value={siteType}
- onValueChange={value => setSiteType(value as SiteType)}
- className="grid grid-cols-2 gap-3"
- >
- <Label
- htmlFor="site-type-web"
- className="flex cursor-pointer items-center gap-2 rounded-md border border-neutral-200 p-3 text-sm dark:border-neutral-800"
- >
- <RadioGroupItem id="site-type-web" value="web" />
- <Globe2 className="h-4 w-4" />
- <span>{t("Website")}</span>
- </Label>
- <Label
- htmlFor="site-type-mobile"
- className="flex cursor-pointer items-center gap-2 rounded-md border border-neutral-200 p-3 text-sm dark:border-neutral-800"
+ {/* A real form, so Enter in the domain or name field submits */}
+ <form
+ onSubmit={e => {
+ e.preventDefault();
+ handleSubmit();
+ }}
+ className="grid gap-4"
+ >
+ <div className="grid gap-4 py-2">
+ <RadioGroup
+ value={siteType}
+ onValueChange={value => setSiteType(value as SiteType)}
+ className="grid grid-cols-2 gap-3"
>
- <RadioGroupItem id="site-type-mobile" value="mobile" />
- <Smartphone className="h-4 w-4" />
- <span>{t("React Native App")}</span>
- </Label>
- </RadioGroup>
-
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="domain" className="text-sm font-medium">
- {siteType === "web" ? t("Domain") : t("App Identifier")}
- </Label>
- <Input
- id="domain"
- value={domain}
- onChange={e => {
- const value = e.target.value.trim();
- setDomain(siteType === "web" ? value.toLowerCase() : value);
- }}
- placeholder={siteType === "web" ? "example.com or sub.example.com" : "com.example.app"}
- />
- </div>
- <div className="grid w-full items-center gap-1.5">
- <Label htmlFor="name" className="text-sm font-medium">
- {t("Name")}
- </Label>
- <Input
- id="name"
- value={name}
- onChange={e => setName(e.target.value)}
- placeholder={t("Display name (defaults to domain)")}
- />
- </div>
+ <Label
+ htmlFor="site-type-web"
+ className="flex cursor-pointer items-center gap-2 rounded-md border border-neutral-200 p-3 text-sm dark:border-neutral-800"
+ >
+ <RadioGroupItem id="site-type-web" value="web" />
+ <Globe2 className="h-4 w-4" />
+ <span>{t("Website")}</span>
+ </Label>
+ <Label
+ htmlFor="site-type-mobile"
+ className="flex cursor-pointer items-center gap-2 rounded-md border border-neutral-200 p-3 text-sm dark:border-neutral-800"
+ >
+ <RadioGroupItem id="site-type-mobile" value="mobile" />
+ <Smartphone className="h-4 w-4" />
+ <span>{t("React Native App")}</span>
+ </Label>
+ </RadioGroup>
- <div>
- <button
- type="button"
- onClick={() => setShowAdvanced(!showAdvanced)}
- aria-expanded={showAdvanced}
- className="inline-flex items-center gap-1 rounded-md text-sm font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:focus-visible:ring-neutral-300"
- >
- <ChevronRight
- className={`h-4 w-4 motion-safe:transition-transform ${showAdvanced ? "rotate-90" : ""}`}
+ <div className="grid w-full items-center gap-1.5">
+ <Label htmlFor="domain" className="text-sm font-medium">
+ {siteType === "web" ? t("Domain") : t("App Identifier")}
+ </Label>
+ <Input
+ id="domain"
+ value={domain}
+ onChange={e => {
+ const value = e.target.value.trim();
+ setDomain(siteType === "web" ? value.toLowerCase() : value);
+ }}
+ placeholder={siteType === "web" ? "example.com or sub.example.com" : "com.example.app"}
/>
- {t("Advanced options")}
- </button>
- {showAdvanced && (
- <div className="mt-3 max-h-[40vh] space-y-5 overflow-y-auto rounded-lg border border-neutral-150 p-4 dark:border-neutral-800">
- <p className="text-xs text-muted-foreground">
- {t("You can change any of these later in site settings.")}
- </p>
- {renderToggleGroup(t("Privacy & Security"), privacyToggles)}
- {renderToggleGroup(t("Analytics Features"), analyticsToggles)}
- {renderToggleGroup(t("Auto Capture"), autoCaptureToggles)}
- </div>
- )}
+ </div>
+ <div className="grid w-full items-center gap-1.5">
+ <Label htmlFor="name" className="text-sm font-medium">
+ {t("Name")}
+ </Label>
+ <Input
+ id="name"
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder={t("Display name (defaults to domain)")}
+ />
+ </div>
+
+ <div>
+ <button
+ type="button"
+ onClick={() => setShowAdvanced(!showAdvanced)}
+ aria-expanded={showAdvanced}
+ className="inline-flex items-center gap-1 rounded-md text-sm font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:focus-visible:ring-neutral-300"
+ >
+ <ChevronRight
+ className={`h-4 w-4 motion-safe:transition-transform ${showAdvanced ? "rotate-90" : ""}`}
+ />
+ {t("Advanced options")}
+ </button>
+ {showAdvanced && (
+ <div className="mt-3 max-h-[40vh] space-y-5 overflow-y-auto rounded-lg border border-neutral-150 p-4 dark:border-neutral-800">
+ <p className="text-xs text-muted-foreground">
+ {t("You can change any of these later in site settings.")}
+ </p>
+ {renderToggleGroup(t("Privacy & Security"), privacyToggles)}
+ {renderToggleGroup(t("Analytics Features"), analyticsToggles)}
+ {renderToggleGroup(t("Auto Capture"), autoCaptureToggles)}
+ </div>
+ )}
+ </div>
</div>
- </div>
- {error && (
- <Alert variant="destructive">
- <AlertCircle className="h-4 w-4" />
- <AlertTitle>{t("Error Adding Site")}</AlertTitle>
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
- <DialogFooter>
- <Button type="button" onClick={() => setOpen(false)} variant="outline">
- {t("Cancel")}
- </Button>
- <Button type="submit" variant={"success"} onClick={handleSubmit} disabled={!domain}>
- {t("Add")}
- </Button>
- </DialogFooter>
+ {error && (
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertTitle>{t("Error Adding Site")}</AlertTitle>
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+ <DialogFooter>
+ <Button type="button" onClick={() => setOpen(false)} variant="outline">
+ {t("Cancel")}
+ </Button>
+ <Button
+ type="submit"
+ variant={"success"}
+ disabled={!domain}
+ loading={isSubmitting}
+ loadingLabel={t("Adding...")}
+ >
+ {t("Add")}
+ </Button>
+ </DialogFooter>
+ </form>
</DialogContent>
</Dialog>
</div>
diff --git a/client/src/app/signup/components/AccountStep.test.tsx b/client/src/app/signup/components/AccountStep.test.tsx
new file mode 100644
index 000000000..78fd108ca
--- /dev/null
+++ b/client/src/app/signup/components/AccountStep.test.tsx
@@ -0,0 +1,77 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { AccountStep } from "./AccountStep";
+
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("next/link", () => ({
+ default: ({ href, children }: { href: string; children: React.ReactNode }) => <a href={href}>{children}</a>,
+}));
+vi.mock("@/lib/const", async importOriginal => ({ ...(await importOriginal<object>()), IS_CLOUD: false }));
+vi.mock("@/components/auth/SocialButtons", () => ({ SocialButtons: () => null }));
+vi.mock("@/components/auth/Turnstile", () => ({ Turnstile: () => null }));
+
+afterEach(cleanup);
+
+function renderStep(props: Partial<React.ComponentProps<typeof AccountStep>> = {}) {
+ const onSubmit = vi.fn();
+ render(
+ <AccountStep
+ setEmail={() => {}}
+ password="correct horse"
+ setPassword={() => {}}
+ turnstileToken=""
+ setTurnstileToken={() => {}}
+ isLoading={false}
+ onSubmit={onSubmit}
+ setError={() => {}}
+ {...props}
+ />
+ );
+ const email = screen.getByLabelText("Email") as HTMLInputElement;
+ return { onSubmit, email, form: email.form! };
+}
+
+describe("AccountStep", () => {
+ it("puts the fields and Continue in one form, so Enter submits", () => {
+ const { onSubmit, email, form } = renderStep();
+
+ const button = screen.getByRole("button", { name: "Continue" }) as HTMLButtonElement;
+ expect(form).toBeTruthy();
+ expect(button.form).toBe(form);
+ expect(button.type).toBe("submit");
+ expect((screen.getByLabelText("Password") as HTMLInputElement).form).toBe(email.form);
+
+ // What the browser does on Enter: submit through the form, validation included.
+ form.requestSubmit();
+ expect(onSubmit).toHaveBeenCalledOnce();
+ });
+
+ it("lets the browser's validation stop an invalid submit", () => {
+ const empty = renderStep({ email: "", password: "" });
+ empty.form.requestSubmit();
+ expect(empty.email.validity.valueMissing).toBe(true);
+ expect(empty.onSubmit).not.toHaveBeenCalled();
+ cleanup();
+
+ const malformed = renderStep({ email: "not-an-email" });
+ malformed.form.requestSubmit();
+ expect(malformed.email.validity.typeMismatch).toBe(true);
+ expect(malformed.onSubmit).not.toHaveBeenCalled();
+ });
+
+ it("keeps Continue in place, focusable and busy while the account is created", () => {
+ const { onSubmit, form } = renderStep({ isLoading: true });
+
+ const button = screen.getByRole("button", { name: "Creating account..." }) as HTMLButtonElement;
+ expect(button.getAttribute("aria-busy")).toBe("true");
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain("Continue");
+
+ // A second Enter while the first request runs is swallowed by the busy button.
+ button.click();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(form).toBeTruthy();
+ });
+});
diff --git a/client/src/app/signup/components/AccountStep.tsx b/client/src/app/signup/components/AccountStep.tsx
index 88bb569e4..c7a43192c 100644
--- a/client/src/app/signup/components/AccountStep.tsx
+++ b/client/src/app/signup/components/AccountStep.tsx
@@ -43,43 +43,50 @@ export function AccountStep({
<h2 className="text-2xl font-semibold mb-4">{t("Signup")}</h2>
<div className="space-y-4">
<SocialButtons onError={setError} callbackURL={socialCallbackURL} mode="signup" />
- <AuthInput
- id="email"
- label={t("Email")}
- type="email"
- placeholder="[email protected]"
- required
- value={email}
- onChange={e => setEmail(e.target.value)}
- />
- <AuthInput
- id="password"
- label={t("Password")}
- type="password"
- placeholder="••••••••"
- required
- value={password}
- onChange={e => setPassword(e.target.value)}
- />
- {IS_CLOUD && (
- <Turnstile
- onSuccess={token => setTurnstileToken(token)}
- onError={() => setTurnstileToken("")}
- onExpire={() => setTurnstileToken("")}
- className="flex justify-center"
- />
- )}
- <AuthButton
- isLoading={isLoading}
- loadingText={t("Creating account...")}
- onClick={onSubmit}
- type="button"
- className="mt-6 transition-all duration-300 h-11"
- disabled={IS_CLOUD ? !turnstileToken || isLoading : isLoading}
+ {/* A real form, so Enter submits and the browser checks required/type/minLength first */}
+ <form
+ onSubmit={e => {
+ e.preventDefault();
+ onSubmit();
+ }}
+ className="space-y-4"
>
- {t("Continue")}
- <ArrowRight className="ml-2 h-4 w-4" />
- </AuthButton>
+ <AuthInput
+ id="email"
+ label={t("Email")}
+ type="email"
+ placeholder="[email protected]"
+ required
+ value={email}
+ onChange={e => setEmail(e.target.value)}
+ />
+ <AuthInput
+ id="password"
+ label={t("Password")}
+ type="password"
+ placeholder="••••••••"
+ required
+ value={password}
+ onChange={e => setPassword(e.target.value)}
+ />
+ {IS_CLOUD && (
+ <Turnstile
+ onSuccess={token => setTurnstileToken(token)}
+ onError={() => setTurnstileToken("")}
+ onExpire={() => setTurnstileToken("")}
+ className="flex justify-center"
+ />
+ )}
+ <AuthButton
+ isLoading={isLoading}
+ loadingText={t("Creating account...")}
+ className="mt-6 transition-all duration-300 h-11"
+ disabled={IS_CLOUD && !turnstileToken}
+ >
+ {t("Continue")}
+ <ArrowRight className="ml-2 h-4 w-4" />
+ </AuthButton>
+ </form>
<div className="text-center text-sm">
{t("Already have an account?")}{" "}
<Link
diff --git a/client/src/app/signup/components/SetupStep.tsx b/client/src/app/signup/components/SetupStep.tsx
index 2beeae276..86eac5d83 100644
--- a/client/src/app/signup/components/SetupStep.tsx
+++ b/client/src/app/signup/components/SetupStep.tsx
@@ -32,11 +32,19 @@ export function SetupStep({
onSubmit,
}: SetupStepProps) {
const t = useExtracted();
+ const canSubmit = !!orgName && !!orgSlug && !!domain && isValidDomain(domain) && !(IS_CLOUD && !referralSource);
return (
<div>
<h2 className="text-2xl font-semibold mb-4">{t("Set up your workspace")}</h2>
- <div className="space-y-4">
+ {/* A real form, so Enter submits like the account step. */}
+ <form
+ className="space-y-4"
+ onSubmit={e => {
+ e.preventDefault();
+ if (canSubmit && !isLoading) onSubmit();
+ }}
+ >
<div className="space-y-2">
<Label htmlFor="domain">{t("Website Domain")}</Label>
<Input
@@ -48,9 +56,7 @@ export function SetupStep({
required
className="h-10 transition-all bg-neutral-100 dark:bg-neutral-800/50 border-neutral-200 dark:border-neutral-700"
/>
- <p className="text-xs text-muted-foreground">
- {t("Enter the domain of the website you want to track")}
- </p>
+ <p className="text-xs text-muted-foreground">{t("Enter the domain of the website you want to track")}</p>
</div>
<div className="space-y-2">
@@ -93,22 +99,16 @@ export function SetupStep({
)}
<Button
+ type="submit"
className="w-full transition-all duration-300 h-11 bg-emerald-600 hover:bg-emerald-500 text-white"
- onClick={onSubmit}
- disabled={
- isLoading ||
- !orgName ||
- !orgSlug ||
- !domain ||
- !isValidDomain(domain) ||
- (IS_CLOUD && !referralSource)
- }
+ loading={isLoading}
+ disabled={!canSubmit}
variant="success"
>
{IS_CLOUD ? t("Start free trial") : t("Continue")}
<ArrowRight className="ml-2 h-4 w-4" />
</Button>
- </div>
+ </form>
</div>
);
}
diff --git a/client/src/components/SiteSettings/ImportManager.tsx b/client/src/components/SiteSettings/ImportManager.tsx
index 661611ab8..4d8e11daf 100644
--- a/client/src/components/SiteSettings/ImportManager.tsx
+++ b/client/src/components/SiteSettings/ImportManager.tsx
@@ -206,8 +206,7 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
const hasActiveImport = IS_CLOUD && sortedImports.some(imp => imp.completedAt === null);
- const isImportDisabled =
- !selectedFile || !selectedPlatform || !!fileError || createImportMutation.isPending || disabled || hasActiveImport;
+ const isImportDisabled = !selectedFile || !selectedPlatform || !!fileError || disabled || hasActiveImport;
return (
<DisabledOverlay message="Data Import" requiredPlan="standard">
@@ -267,18 +266,15 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
</div>
{/* Import Button */}
- <Button type="submit" disabled={isImportDisabled} className="w-full sm:w-auto">
- {createImportMutation.isPending ? (
- <>
- <Loader2 className="h-4 w-4 animate-spin" />
- {t("Importing...")}
- </>
- ) : (
- <>
- <Upload className="h-4 w-4" />
- {t("Import")}
- </>
- )}
+ <Button
+ type="submit"
+ disabled={isImportDisabled}
+ loading={createImportMutation.isPending}
+ loadingLabel={t("Importing...")}
+ className="w-full sm:w-auto"
+ >
+ <Upload className="h-4 w-4" />
+ {t("Import")}
</Button>
</form>
diff --git a/client/src/components/auth/AuthButton.tsx b/client/src/components/auth/AuthButton.tsx
index 9bde81bc1..c276c9174 100644
--- a/client/src/components/auth/AuthButton.tsx
+++ b/client/src/components/auth/AuthButton.tsx
@@ -5,6 +5,7 @@ import { ReactNode } from "react";
interface AuthButtonProps {
isLoading: boolean;
+ /** Screen-reader name while loading; the visible label stays under the spinner. */
loadingText?: string;
children: ReactNode;
className?: string;
@@ -16,7 +17,7 @@ interface AuthButtonProps {
export function AuthButton({
isLoading,
- loadingText = "Loading...",
+ loadingText,
children,
className = "",
onClick,
@@ -24,9 +25,19 @@ export function AuthButton({
variant = "success",
disabled = false,
}: AuthButtonProps) {
+ // Callers still pass `disabled={... || isLoading}`; Button lets loading win,
+ // so the button keeps focus while the request runs.
return (
- <Button type={type} className={`w-full ${className}`} disabled={disabled || isLoading} variant={variant} onClick={onClick}>
- {isLoading ? loadingText : children}
+ <Button
+ type={type}
+ className={`w-full ${className}`}
+ loading={isLoading}
+ loadingLabel={loadingText}
+ disabled={disabled}
+ variant={variant}
+ onClick={onClick}
+ >
+ {children}
</Button>
);
}
diff --git a/client/src/components/subscription/components/PlanDialog.test.tsx b/client/src/components/subscription/components/PlanDialog.test.tsx
new file mode 100644
index 000000000..34e167cdb
--- /dev/null
+++ b/client/src/components/subscription/components/PlanDialog.test.tsx
@@ -0,0 +1,137 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { PlanDialog } from "./PlanDialog";
+
+const mocks = vi.hoisted(() => ({
+ toastSuccess: vi.fn(),
+ toastError: vi.fn(),
+ onOpenChange: vi.fn(),
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, string>) =>
+ message.replace(/\{(\w+)\}/g, (_, key: string) => values?.[key] ?? ""),
+}));
+vi.mock("@/lib/auth", () => ({
+ authClient: { useActiveOrganization: () => ({ data: { id: "org_1" } }) },
+}));
+vi.mock("@/components/ui/sonner", () => ({
+ toast: { success: mocks.toastSuccess, error: mocks.toastError },
+}));
+vi.mock("./CheckoutModal", () => ({ CheckoutModal: () => null }));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>(res => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function jsonResponse(body: unknown, ok = true) {
+ return { ok, json: async () => body } as Response;
+}
+
+const PREVIEW = {
+ success: true,
+ preview: {
+ currentPlan: { priceId: "price_old", amount: 1900, interval: "month" },
+ newPlan: { priceId: "price_new", amount: 2900, interval: "month" },
+ proration: { credit: 5, charge: 12, immediatePayment: 7, nextBillingDate: null },
+ },
+};
+
+// Stands in for the billing page: one query derived from the plan.
+function BillingPage({ fetchPlan }: { fetchPlan: () => Promise<string> }) {
+ const { data } = useQuery({ queryKey: ["stripe-subscription", "org_1"], queryFn: fetchPlan });
+ return (
+ <>
+ <p>Plan: {data}</p>
+ <PlanDialog open onOpenChange={mocks.onOpenChange} currentPlanName="standard100k" hasActiveSubscription />
+ </>
+ );
+}
+
+let update: ReturnType<typeof deferred<Response>>;
+
+beforeEach(() => {
+ // Radix Slider measures its thumbs.
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+ update = deferred<Response>();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (url: string) => {
+ if (url.endsWith("/stripe/preview-subscription-update")) return jsonResponse(PREVIEW);
+ if (url.endsWith("/stripe/update-subscription")) return update.promise;
+ throw new Error(`Unexpected fetch ${url}`);
+ })
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+});
+
+async function confirmPlanChange(fetchPlan: () => Promise<string>) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={queryClient}>
+ <BillingPage fetchPlan={fetchPlan} />
+ </QueryClientProvider>
+ );
+ expect(await screen.findByText("Plan: standard100k")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Change Plan" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Confirm Change" }));
+
+ // The preview closes; the plan button carries the pending state for the update.
+ const changePlan = await screen.findByRole("button", { name: "Change Plan" });
+ await waitFor(() => expect(changePlan.getAttribute("aria-busy")).toBe("true"));
+ expect((changePlan as HTMLButtonElement).disabled).toBe(false);
+ return changePlan;
+}
+
+describe("PlanDialog", () => {
+ it("updates the plan in place: stays busy until the plan refetch lands, then closes and toasts", async () => {
+ const refetch = deferred<string>();
+ const fetchPlan = vi.fn().mockResolvedValueOnce("standard100k").mockReturnValueOnce(refetch.promise);
+ const changePlan = await confirmPlanChange(fetchPlan);
+
+ await act(async () => update.resolve(jsonResponse({ success: true, subscription: {} })));
+
+ // The update succeeded, but the page hasn't caught up yet: nothing announced, dialog still open.
+ await waitFor(() => expect(fetchPlan).toHaveBeenCalledTimes(2));
+ expect(changePlan.getAttribute("aria-busy")).toBe("true");
+ expect(mocks.toastSuccess).not.toHaveBeenCalled();
+ expect(mocks.onOpenChange).not.toHaveBeenCalled();
+
+ await act(async () => refetch.resolve("standard250k"));
+
+ await waitFor(() => expect(mocks.onOpenChange).toHaveBeenCalledWith(false));
+ expect(mocks.toastSuccess).toHaveBeenCalledWith("Subscription updated");
+ // The new plan is on the page and the toast stays up: no reload.
+ expect(screen.getByText("Plan: standard250k")).toBeTruthy();
+ });
+
+ it("keeps the dialog open and reports the error when the update fails", async () => {
+ const changePlan = await confirmPlanChange(vi.fn().mockResolvedValue("standard100k"));
+
+ await act(async () => update.resolve(jsonResponse({ error: "Card declined" }, false)));
+
+ await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Subscription update failed: Card declined"));
+ await waitFor(() => expect(changePlan.hasAttribute("aria-busy")).toBe(false));
+ expect(mocks.onOpenChange).not.toHaveBeenCalled();
+ expect(mocks.toastSuccess).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/subscription/components/PlanDialog.tsx b/client/src/components/subscription/components/PlanDialog.tsx
index 1d615adb9..50e163144 100644
--- a/client/src/components/subscription/components/PlanDialog.tsx
+++ b/client/src/components/subscription/components/PlanDialog.tsx
@@ -9,6 +9,7 @@ import { EVENT_TIERS, findPriceForTier, formatEventTier } from "@/lib/subscripti
import { usePreviewSubscriptionUpdate, useUpdateSubscription } from "@/lib/subscription/useSubscriptionMutations";
import { cn } from "@/lib/utils";
import { ArrowRight } from "lucide-react";
+import { useExtracted } from "next-intl";
import { useMemo, useState } from "react";
import { CheckoutModal } from "./CheckoutModal";
import { PlanChangePreviewDialog } from "./PlanChangePreviewDialog";
@@ -42,6 +43,7 @@ function parseCurrentPlan(currentPlanName?: string) {
}
export function PlanDialog({ open, onOpenChange, currentPlanName, hasActiveSubscription }: PlanDialogProps) {
+ const t = useExtracted();
const defaults = useMemo(() => parseCurrentPlan(currentPlanName), [currentPlanName]);
// Default to next tier up for existing subscribers
@@ -137,11 +139,17 @@ export function PlanDialog({ open, onOpenChange, currentPlanName, hasActiveSubsc
if (!activeOrg || !pendingPriceId) return;
try {
+ // Resolves after the plan queries have refetched (see useUpdateSubscription),
+ // so the billing page already shows the new plan when this closes. No reload:
+ // it would wipe the success toast.
await updateMutation.mutateAsync({
organizationId: activeOrg.id,
newPriceId: pendingPriceId,
});
- window.location.reload();
+ previewMutation.reset();
+ setPendingPriceId(null);
+ setPendingPlanName(null);
+ onOpenChange(false);
} catch (error) {
// Error is already handled by the mutation
}
@@ -288,18 +296,12 @@ export function PlanDialog({ open, onOpenChange, currentPlanName, hasActiveSubsc
className="w-full h-11"
variant="success"
onClick={handleSelectPlan}
- disabled={isLoading || previewMutation.isPending || isCurrentSelection}
+ // Covers the preview request and, after confirming, the update itself
+ loading={isLoading || previewMutation.isPending || updateMutation.isPending}
+ disabled={isCurrentSelection}
>
- {isLoading || previewMutation.isPending
- ? "Loading..."
- : isCurrentSelection
- ? "Current Plan"
- : hasActiveSubscription
- ? "Change Plan"
- : "Subscribe"}
- {!isLoading && !previewMutation.isPending && !isCurrentSelection && (
- <ArrowRight className="ml-2 h-4 w-4" />
- )}
+ {isCurrentSelection ? t("Current Plan") : hasActiveSubscription ? t("Change Plan") : t("Subscribe")}
+ {!isCurrentSelection && <ArrowRight className="ml-2 h-4 w-4" />}
</Button>
)}
diff --git a/client/src/components/ui/button.test.tsx b/client/src/components/ui/button.test.tsx
new file mode 100644
index 000000000..025da6ee4
--- /dev/null
+++ b/client/src/components/ui/button.test.tsx
@@ -0,0 +1,171 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { Button } from "./button";
+
+afterEach(cleanup);
+
+// The two grid layers inside a loading-capable button: [label, spinner].
+function layers(button: HTMLElement) {
+ const grid = button.firstElementChild as HTMLElement;
+ return Array.from(grid.children) as HTMLElement[];
+}
+
+describe("Button", () => {
+ it("renders exactly as before when loading is not passed", () => {
+ render(
+ <Button variant="success" size="sm" className="w-full">
+ Save
+ </Button>
+ );
+
+ const button = screen.getByRole("button", { name: "Save" });
+ expect(button.innerHTML).toBe("Save");
+ expect(button.className).toContain("w-full");
+ expect(button.hasAttribute("aria-busy")).toBe(false);
+ expect(button.hasAttribute("aria-disabled")).toBe(false);
+ });
+
+ it("keeps the label in layout under a hidden spinner while idle", () => {
+ render(<Button loading={false}>Save</Button>);
+
+ const button = screen.getByRole("button", { name: "Save" });
+ const [label, spinner] = layers(button);
+ expect(label.textContent).toBe("Save");
+ expect(label.className).toContain("opacity-100");
+ expect(spinner.getAttribute("aria-hidden")).toBe("true");
+ expect(spinner.className).toContain("opacity-0");
+ expect(spinner.querySelector("svg")!.style.animationPlayState).toBe("paused");
+ expect(button.hasAttribute("aria-busy")).toBe(false);
+ expect(button.hasAttribute("aria-disabled")).toBe(false);
+ });
+
+ it("crossfades to the spinner while loading without removing the label", () => {
+ const { rerender } = render(<Button loading={false}>Save</Button>);
+ rerender(<Button loading>Save</Button>);
+
+ const button = screen.getByRole("button", { name: "Save" });
+ const [label, spinner] = layers(button);
+ // Same grid cell, so the invisible label still sets the width.
+ expect(label.className).toContain("col-start-1 row-start-1");
+ expect(spinner.className).toContain("col-start-1 row-start-1");
+ expect(label.textContent).toBe("Save");
+ expect(label.className).toContain("opacity-0");
+ expect(spinner.className).toContain("opacity-100");
+ expect(spinner.querySelector("svg")!.style.animationPlayState).toBe("");
+ });
+
+ it("stays focusable while loading: aria-busy and aria-disabled, never the disabled attribute", () => {
+ const { rerender } = render(<Button loading={false}>Save</Button>);
+ const button = screen.getByRole("button", { name: "Save" }) as HTMLButtonElement;
+ button.focus();
+
+ rerender(<Button loading>Save</Button>);
+
+ expect(button.disabled).toBe(false);
+ expect(button.getAttribute("aria-busy")).toBe("true");
+ expect(button.getAttribute("aria-disabled")).toBe("true");
+ expect(document.activeElement).toBe(button);
+ });
+
+ it("lets loading win over disabled, then hands disabled back", () => {
+ const { rerender } = render(
+ <Button loading disabled>
+ Save
+ </Button>
+ );
+ const button = screen.getByRole("button", { name: "Save" }) as HTMLButtonElement;
+ expect(button.disabled).toBe(false);
+ expect(button.getAttribute("aria-disabled")).toBe("true");
+
+ rerender(
+ <Button loading={false} disabled>
+ Save
+ </Button>
+ );
+ expect(button.disabled).toBe(true);
+ expect(button.hasAttribute("aria-disabled")).toBe(false);
+ });
+
+ it("ignores clicks while loading and handles them again afterwards", () => {
+ const onClick = vi.fn();
+ const { rerender } = render(
+ <Button loading onClick={onClick}>
+ Save
+ </Button>
+ );
+ const button = screen.getByRole("button", { name: "Save" });
+
+ const notCancelled = fireEvent.click(button);
+ expect(notCancelled).toBe(false);
+ expect(onClick).not.toHaveBeenCalled();
+
+ rerender(
+ <Button loading={false} onClick={onClick}>
+ Save
+ </Button>
+ );
+ fireEvent.click(button);
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+
+ it("does not submit its form while loading", () => {
+ const onSubmit = vi.fn((event: React.FormEvent) => event.preventDefault());
+ const { rerender } = render(
+ <form onSubmit={onSubmit}>
+ <Button type="submit" loading>
+ Save
+ </Button>
+ </form>
+ );
+ const button = screen.getByRole("button", { name: "Save" });
+
+ button.click();
+ expect(onSubmit).not.toHaveBeenCalled();
+
+ rerender(
+ <form onSubmit={onSubmit}>
+ <Button type="submit" loading={false}>
+ Save
+ </Button>
+ </form>
+ );
+ button.click();
+ expect(onSubmit).toHaveBeenCalledOnce();
+ });
+
+ it("announces loadingLabel as the accessible name only while loading", () => {
+ const { rerender } = render(
+ <Button loading={false} loadingLabel="Saving...">
+ Save
+ </Button>
+ );
+ expect(screen.getByRole("button", { name: "Save" })).toBeTruthy();
+
+ rerender(
+ <Button loading loadingLabel="Saving...">
+ Save
+ </Button>
+ );
+ expect(screen.getByRole("button", { name: "Saving..." })).toBeTruthy();
+ });
+
+ it("wraps an asChild element's children and blocks its clicks", () => {
+ const onClick = vi.fn();
+ render(
+ <Button asChild loading>
+ <a href="/billing" onClick={onClick}>
+ Billing
+ </a>
+ </Button>
+ );
+
+ const link = screen.getByText("Billing").closest("a")!;
+ expect(link.getAttribute("aria-busy")).toBe("true");
+ expect(link.className).toContain("inline-flex");
+ expect(layers(link)[0].textContent).toBe("Billing");
+
+ expect(fireEvent.click(link)).toBe(false);
+ expect(onClick).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/ui/button.tsx b/client/src/components/ui/button.tsx
index 180c24653..c721b446f 100644
--- a/client/src/components/ui/button.tsx
+++ b/client/src/components/ui/button.tsx
@@ -5,7 +5,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
- "inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 dark:focus-visible:ring-neutral-300",
+ "inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:pointer-events-none disabled:opacity-50 aria-busy:cursor-progress [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 dark:focus-visible:ring-neutral-300",
{
variants: {
variant: {
@@ -46,12 +46,93 @@ const buttonVariants = cva(
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
asChild?: boolean;
+ /**
+ * Swaps the label for a spinner without changing the button's width, and
+ * ignores clicks. The button stays focusable: it gets aria-busy and
+ * aria-disabled instead of the disabled attribute, so `loading` wins over
+ * `disabled`. Pass it from the first render (`loading={isPending}`) so both
+ * layers exist to crossfade between. Leave it out and the button renders
+ * exactly as it always has.
+ */
+ loading?: boolean;
+ /** Accessible name while loading, e.g. t("Saving..."). Defaults to the visible label. */
+ loadingLabel?: string;
+}
+
+// Loading layout adapted from interior.dev "Loading Button" (MIT). See
+// ../interior/THIRD_PARTY_LICENSES.md. The label and the spinner share one grid
+// cell, so the label keeps sizing the button while it is invisible. The fade is
+// CSS rather than framer so this file stays light and server-safe; the global
+// prefers-reduced-motion rule makes it instant and holds the spinner still.
+const LOADING_LAYER = "col-start-1 row-start-1 flex items-center justify-center gap-[inherit] transition-opacity";
+// FADE_IN and FADE_OUT from lib/motion.ts.
+const LOADING_LAYER_SHOWN = "opacity-100 duration-[180ms] ease-[cubic-bezier(0.23,1,0.32,1)]";
+const LOADING_LAYER_HIDDEN = "opacity-0 duration-[140ms] ease-in";
+
+function ButtonSpinner({ spinning }: { spinning: boolean }) {
+ // Sized by the button's [&_svg]:size-4, like any icon. Paused rather than
+ // removed when idle, so it doesn't snap back to 0° while fading out. Inline,
+ // because animate-spin's `animation` shorthand would reset a class-based pause.
+ return (
+ <svg
+ viewBox="0 0 16 16"
+ fill="none"
+ className="animate-spin"
+ style={spinning ? undefined : { animationPlayState: "paused" }}
+ >
+ <circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" strokeOpacity="0.25" />
+ <path d="M14 8a6 6 0 0 0-6-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
+ </svg>
+ );
+}
+
+function withLoadingLayers(label: React.ReactNode, loading: boolean) {
+ return (
+ <span className="grid place-items-center gap-[inherit]">
+ <span className={cn(LOADING_LAYER, loading ? LOADING_LAYER_HIDDEN : LOADING_LAYER_SHOWN)}>{label}</span>
+ <span aria-hidden="true" className={cn(LOADING_LAYER, loading ? LOADING_LAYER_SHOWN : LOADING_LAYER_HIDDEN)}>
+ <ButtonSpinner spinning={loading} />
+ </span>
+ </span>
+ );
+}
+
+// Capture phase, so it runs before any onClick on the button, its asChild
+// element or a Radix trigger, and cancels form submission and navigation.
+function blockClick(event: React.MouseEvent) {
+ event.preventDefault();
+ event.stopPropagation();
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
- ({ className, variant, size, asChild = false, ...props }, ref) => {
+ ({ className, variant, size, asChild = false, loading, loadingLabel, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
- return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
+ const classes = cn(buttonVariants({ variant, size, className }));
+
+ if (loading === undefined) {
+ return <Comp className={classes} ref={ref} {...props} />;
+ }
+
+ const { children, disabled, onClickCapture, ...rest } = props;
+ const content =
+ asChild && React.isValidElement<{ children?: React.ReactNode }>(children)
+ ? React.cloneElement(children, undefined, withLoadingLayers(children.props.children, loading))
+ : withLoadingLayers(children, loading);
+
+ return (
+ <Comp
+ className={classes}
+ ref={ref}
+ {...rest}
+ disabled={loading ? undefined : disabled}
+ aria-busy={loading || rest["aria-busy"] || undefined}
+ aria-disabled={loading || rest["aria-disabled"] || undefined}
+ aria-label={loading && loadingLabel ? loadingLabel : rest["aria-label"]}
+ onClickCapture={loading ? blockClick : onClickCapture}
+ >
+ {content}
+ </Comp>
+ );
}
);
Button.displayName = "Button";
diff --git a/client/src/lib/subscription/useSubscriptionMutations.ts b/client/src/lib/subscription/useSubscriptionMutations.ts
index 3cc95c8e6..87b9a9a7d 100644
--- a/client/src/lib/subscription/useSubscriptionMutations.ts
+++ b/client/src/lib/subscription/useSubscriptionMutations.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useExtracted } from "next-intl";
import { BACKEND_URL } from "../const";
import { toast } from "@/components/ui/sonner";
@@ -71,6 +72,7 @@ export function usePreviewSubscriptionUpdate() {
export function useUpdateSubscription() {
const queryClient = useQueryClient();
+ const t = useExtracted();
return useMutation<UpdateSubscriptionResponse, Error, UpdateSubscriptionParams>({
mutationFn: async ({ organizationId, newPriceId }) => {
@@ -94,13 +96,23 @@ export function useUpdateSubscription() {
return data;
},
- onSuccess: (data, variables) => {
- // Invalidate subscription data to refetch latest info
- queryClient.invalidateQueries({ queryKey: ["stripe-subscription", variables.organizationId] });
- toast.success("Subscription updated successfully!");
+ onSuccess: async (_data, { organizationId }) => {
+ // The server drops its Stripe cache in the same request, so refetching
+ // everything derived from the plan updates the page in place: no reload,
+ // and the toast survives. Returning this promise keeps the mutation
+ // pending (mutateAsync unresolved) until the fresh data has landed.
+ await Promise.all([
+ // Billing page: plan card, usage cards, limits.
+ queryClient.invalidateQueries({ queryKey: ["stripe-subscription", organizationId] }),
+ // A mid-cycle change creates a prorated invoice.
+ queryClient.invalidateQueries({ queryKey: ["stripe-invoices", organizationId] }),
+ // Organization + plan summary behind feature gates (DisabledOverlay) and usage banners.
+ queryClient.invalidateQueries({ queryKey: ["get-sites-from-org", organizationId] }),
+ ]);
+ toast.success(t("Subscription updated"));
},
onError: error => {
- toast.error(`Subscription update failed: ${error.message}`);
+ toast.error(t("Subscription update failed: {message}", { message: error.message }));
},
});
}