🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
fix(ui): billing success redirect, funnel delete, map overlay, errors skeleton and sidebar focus (#1252)
Goldflagc135930ff1c4
diff --git a/client/src/app/[site]/components/shared/Map/MapComponent.test.tsx b/client/src/app/[site]/components/shared/Map/MapComponent.test.tsxnew file mode 100644index 000000000..cd0a5392e--- /dev/null+++ b/client/src/app/[site]/components/shared/Map/MapComponent.test.tsx@@ -0,0 +1,65 @@+import React from "react";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ loading: { country: false, region: false } as Record<string, boolean>,+ // Stable references, like React Query: MapComponent bumps a version whenever data identity changes.+ data: { country: { data: [] }, region: { data: [] } } as Record<string, { data: never[] }>,+}));++vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));+vi.mock("@/api/analytics/hooks/useGetMetric", () => ({+ useMetric: ({ parameter }: { parameter: string }) => ({+ data: mocks.loading[parameter] ? undefined : mocks.data[parameter],+ isLoading: mocks.loading[parameter],+ isFetching: mocks.loading[parameter],+ }),+}));+vi.mock("@/lib/geo", () => ({ useCountries: () => ({ data: null }), useSubdivisions: () => ({ data: null }) }));+vi.mock("@uidotdev/usehooks", () => ({ useMeasure: () => [() => {}, { height: 340 }] }));+vi.mock("./hooks/useMapInstance", () => ({+ useMapInstance: () => ({+ mapRef: { current: null },+ mapInstanceRef: { current: null },+ mapViewRef: { current: null },+ }),+}));+vi.mock("./hooks/useMapLayers", () => ({ useMapLayers: () => {} }));+vi.mock("./hooks/useMapStyles", () => ({ useMapStyles: () => ({ colorScale: () => "" }) }));+vi.mock("../icons/CountryFlag", () => ({ CountryFlag: () => null }));++import { MapComponent } from "./MapComponent";++const overlay = () => screen.queryByText("Loading map data…");++afterEach(cleanup);++describe("MapComponent loading overlay", () => {+ it("covers the country view while country data loads", () => {+ mocks.loading = { country: true, region: false };+ render(<MapComponent height="340px" />);+ expect(overlay()).toBeTruthy();+ });++ it("doesn't hold the country view for the region query", () => {+ mocks.loading = { country: false, region: true };+ render(<MapComponent height="340px" />);+ expect(overlay()).toBeNull();+ });++ it("covers the region view while region data loads", () => {+ mocks.loading = { country: false, region: true };+ render(<MapComponent height="340px" mapView="subdivisions" />);+ expect(overlay()).toBeTruthy();+ });++ it("is scoped to the map box and gone once data is in", () => {+ mocks.loading = { country: true, region: false };+ const { container, rerender } = render(<MapComponent height="340px" />);+ expect((container.firstChild as HTMLElement).className).toContain("relative");+ mocks.loading = { country: false, region: false };+ rerender(<MapComponent height="340px" />);+ expect(overlay()).toBeNull();+ });+});diff --git a/client/src/app/[site]/components/shared/Map/MapComponent.tsx b/client/src/app/[site]/components/shared/Map/MapComponent.tsxindex 2d20a07a2..2b3eee13d 100644--- a/client/src/app/[site]/components/shared/Map/MapComponent.tsx+++ b/client/src/app/[site]/components/shared/Map/MapComponent.tsx@@ -1,6 +1,7 @@"use client";import { useMeasure } from "@uidotdev/usehooks";+import { useExtracted } from "next-intl";import "ol/ol.css";import { useEffect, useState } from "react";import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";@@ -13,6 +14,7 @@ import { useMapStyles } from "./hooks/useMapStyles";import type { MapComponentProps, TooltipContent, TooltipPosition } from "./types";export function MapComponent({ height, mapView: controlledMapView }: MapComponentProps) {+ const t = useExtracted();const {data: countryData,isLoading: isCountryLoading,@@ -80,22 +82,26 @@ export function MapComponent({ height, mapView: controlledMapView }: MapComponenhoveredId,});+ // useMapLayers draws a view only once that view's data has arrived, so cover the map while it+ // loads. The country view doesn't wait on the much larger region query.+ const isViewLoading = mapView === "countries" ? isCountryLoading : isSubdivisionLoading;+return (<div+ className="relative"style={{height: height,}}ref={ref}>- {isCountryLoading ||- (isSubdivisionLoading && (- <div className="absolute inset-0 bg-neutral-900/30 backdrop-blur-sm z-10 flex items-center justify-center">- <div className="flex flex-col items-center gap-2">- <div className="h-8 w-8 rounded-full border-2 border-accent-400 border-t-transparent animate-spin"></div>- <span className="text-sm text-neutral-300">Loading map data…</span>- </div>+ {isViewLoading && (+ <div className="absolute inset-0 bg-white/60 dark:bg-neutral-900/30 backdrop-blur-sm z-10 flex items-center justify-center">+ <div className="flex flex-col items-center gap-2">+ <div className="h-8 w-8 rounded-full border-2 border-neutral-500 border-t-transparent animate-spin"></div>+ <span className="text-sm text-neutral-600 dark:text-neutral-300">{t("Loading map data…")}</span></div>- ))}+ </div>+ )}<divref={mapRef}style={{diff --git a/client/src/app/[site]/errors/page.test.tsx b/client/src/app/[site]/errors/page.test.tsxnew file mode 100644index 000000000..c5c08f1eb--- /dev/null+++ b/client/src/app/[site]/errors/page.test.tsx@@ -0,0 +1,96 @@+import React from "react";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ErrorNameItem, ErrorNamesPaginatedResponse } from "@/api/analytics/endpoints";+import { useStore } from "@/lib/store";++type QueryState = {+ data?: ErrorNamesPaginatedResponse;+ isLoading: boolean;+ isFetching: boolean;+ isPlaceholderData: boolean;+ isError: boolean;+ error: Error | null;+};++const mocks = vi.hoisted(() => ({ query: {} as QueryState }));++vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));+vi.mock("@/api/analytics/hooks/errors/useGetErrorNames", () => ({ useGetErrorNamesPaginated: () => mocks.query }));+vi.mock("@/hooks/useSetPageTitle", () => ({ useSetPageTitle: () => {} }));+vi.mock("@/components/DisabledOverlay", () => ({+ DisabledOverlay: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));+vi.mock("@/components/pagination", () => ({+ Pagination: ({ isLoading }: { isLoading?: boolean }) => (+ <div data-testid="pagination">{isLoading ? "pagination loading" : "pagination idle"}</div>+ ),+}));+vi.mock("../components/SubHeader/SubHeader", () => ({ SubHeader: () => null }));+vi.mock("./components/EnableErrorTracking", () => ({ EnableErrorTracking: () => null }));+vi.mock("./components/ErrorListSkeleton", () => ({ ErrorListSkeleton: () => <div data-testid="skeleton" /> }));+vi.mock("./components/ErrorListItem", () => ({+ ErrorListItem: ({ errorData }: { errorData: ErrorNameItem }) => <div data-testid="error-item">{errorData.value}</div>,+}));++import Errors from "./page";++const response = (values: string[]): ErrorNamesPaginatedResponse => ({+ data: values.map(value => ({ value, errorName: "TypeError", count: 3, sessionCount: 2, percentage: 50 })),+ totalCount: 25,+});++const settled: QueryState = {+ data: response(["a is undefined", "b is not a function"]),+ isLoading: false,+ isFetching: false,+ isPlaceholderData: false,+ isError: false,+ error: null,+};++// Load the first page, then switch the query into a refetch state.+function renderThenRefetch(refetch: Partial<QueryState>) {+ mocks.query = settled;+ const view = render(<Errors />);+ mocks.query = { ...settled, ...refetch };+ view.rerender(<Errors />);+ return view;+}++const list = () => screen.getAllByTestId("error-item")[0].parentElement!;++beforeEach(() => {+ useStore.setState({ site: "1" });+});+afterEach(cleanup);++describe("Errors page loading states", () => {+ it("shows the skeleton only while there is nothing to show yet", () => {+ mocks.query = { ...settled, data: undefined, isLoading: true, isFetching: true };+ render(<Errors />);+ expect(screen.getByTestId("skeleton")).toBeTruthy();+ expect(screen.queryAllByTestId("error-item")).toHaveLength(0);+ });++ it("keeps the previous list on screen, dimmed, while a new page or filter loads", () => {+ renderThenRefetch({ isFetching: true, isPlaceholderData: true });+ expect(screen.queryByTestId("skeleton")).toBeNull();+ expect(screen.getAllByTestId("error-item")).toHaveLength(2);+ expect(list().getAttribute("aria-busy")).toBe("true");+ expect(list().className).toContain("opacity-60");+ expect(screen.getByTestId("pagination").textContent).toBe("pagination loading");+ });++ it("leaves current data untouched during a background refetch", () => {+ renderThenRefetch({ isFetching: true });+ expect(screen.queryByTestId("skeleton")).toBeNull();+ expect(list().className).not.toContain("opacity-60");+ expect(screen.getByTestId("pagination").textContent).toBe("pagination idle");+ });++ it("keeps the empty state instead of blanking while an empty result refetches", () => {+ renderThenRefetch({ data: response([]), isFetching: true, isPlaceholderData: true });+ expect(screen.getByText("No error events found")).toBeTruthy();+ });+});diff --git a/client/src/app/[site]/errors/page.tsx b/client/src/app/[site]/errors/page.tsxindex 1cd2a9864..b6c5a2bdb 100644--- a/client/src/app/[site]/errors/page.tsx+++ b/client/src/app/[site]/errors/page.tsx@@ -6,6 +6,7 @@ import { ErrorNameItem } from "@/api/analytics/endpoints";import { Pagination } from "@/components/pagination";import { useSetPageTitle } from "@/hooks/useSetPageTitle";import { useStore } from "@/lib/store";+import { cn } from "@/lib/utils";import { useEffect, useState } from "react";import { DisabledOverlay } from "../../../components/DisabledOverlay";import { SubHeader } from "../components/SubHeader/SubHeader";@@ -47,8 +48,6 @@ export default function Errors() {const errorsDataArray: ErrorNameItem[] | undefined = apiResponse?.data;const totalCount: number | undefined = apiResponse?.totalCount;- const isLoading = isLoadingErrors || isFetching;-// Create a minimal table object with the required pagination methodsconst table = {getState: () => ({@@ -104,7 +103,9 @@ export default function Errors() {<SubHeader /><EnableErrorTracking />- {isLoading ? (+ {/* Skeleton on the first load only. A new page, filter or time range keeps the previous list+ on screen (placeholder data), dimmed until the answer arrives. */}+ {isLoadingErrors ? (<ErrorListSkeleton count={pagination.pageSize} />) : isErrorErrors ? (<div className="text-center p-8 text-destructive">@@ -113,26 +114,28 @@ export default function Errors() {</div>) : errorsDataArray && errorsDataArray.length > 0 ? (<>- {errorsDataArray.map((errorItem: ErrorNameItem, index: number) => (- <ErrorListItem key={`${errorItem.value}-${index}-${pagination.pageIndex}`} errorData={errorItem} />- ))}+ <div aria-busy={isFetching} className={cn("transition-opacity", isPlaceholderData && "opacity-60")}>+ {errorsDataArray.map((errorItem: ErrorNameItem, index: number) => (+ <ErrorListItem key={`${errorItem.value}-${index}-${pagination.pageIndex}`} errorData={errorItem} />+ ))}+ </div>{totalPages > 0 && (<Paginationtable={table}data={{ items: errorsDataArray || [], total: totalCount || 0 }}pagination={pagination}setPagination={setPagination}- isLoading={isLoading}- itemName="errors"+ isLoading={isPlaceholderData}+ itemName={t("errors")}/>)}</>- ) : !isLoadingErrors && !isFetching ? (+ ) : (<NothingFoundtitle={t("No error events found")}description={t("Errors will appear here once error tracking is enabled and errors occur on your site.")}/>- ) : null}+ )}</div></DisabledOverlay>);diff --git a/client/src/app/[site]/funnels/components/FunnelRow.test.tsx b/client/src/app/[site]/funnels/components/FunnelRow.test.tsxnew file mode 100644index 000000000..4bd904190--- /dev/null+++ b/client/src/app/[site]/funnels/components/FunnelRow.test.tsx@@ -0,0 +1,102 @@+import React from "react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { SavedFunnel } from "@/api/analytics/endpoints";+import { TooltipProvider } from "@/components/ui/tooltip";+import { useStore } from "@/lib/store";++const mocks = vi.hoisted(() => ({ deleteFunnel: vi.fn(), toastSuccess: vi.fn() }));++vi.mock("next-intl", () => ({+ useExtracted:+ () =>+ (message: string, values: Record<string, string> = {}) =>+ message.replace(/\{(\w+)\}/g, (_, key: string) => values[key] ?? key),+}));+vi.mock("@/api/analytics/endpoints/funnels", async importOriginal => ({+ ...(await importOriginal<typeof import("@/api/analytics/endpoints/funnels")>()),+ deleteFunnel: mocks.deleteFunnel,+}));+vi.mock("@/api/analytics/hooks/funnels/useGetFunnel", () => ({+ useGetFunnel: () => ({ data: undefined, isError: false, error: null, isLoading: false, isSuccess: false }),+}));+vi.mock("@/components/ui/sonner", () => ({ toast: { success: mocks.toastSuccess, error: vi.fn() } }));+vi.mock("./EditFunnel", () => ({ EditFunnelDialog: () => null }));+vi.mock("./Funnel", () => ({ Funnel: () => null }));++import { FunnelRow } from "./FunnelRow";++const funnel: SavedFunnel = {+ id: 7,+ name: "Signup",+ steps: [+ { type: "page", value: "/" },+ { type: "page", value: "/signup" },+ ],+ createdAt: "2026-09-01T00:00:00Z",+ updatedAt: "2026-09-01T00:00:00Z",+ conversionRate: null,+ totalVisitors: null,+};++function renderRow() {+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ return render(+ <QueryClientProvider client={client}>+ <TooltipProvider>+ <FunnelRow funnel={funnel} index={1} />+ </TooltipProvider>+ </QueryClientProvider>+ );+}++// The row's icon buttons are labelled by tooltips only, so find the delete one by its icon.+function openDeleteDialog(container: HTMLElement) {+ const trash = container.querySelector(".lucide-trash-2, .lucide-trash2")?.closest("button");+ fireEvent.click(trash!);+}++beforeEach(() => {+ useStore.setState({ site: "42" });+ vi.spyOn(console, "error").mockImplementation(() => {});+});+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++describe("FunnelRow delete", () => {+ it("keeps the dialog open and shows the server error when the delete fails", async () => {+ mocks.deleteFunnel.mockRejectedValue(new Error("Funnel is used by a dashboard"));+ const { container } = renderRow();++ openDeleteDialog(container);+ fireEvent.click(await screen.findByRole("button", { name: "Delete" }));++ expect(await screen.findByText(/Funnel is used by a dashboard/)).toBeTruthy();+ expect(screen.getByRole("dialog")).toBeTruthy();+ expect(mocks.toastSuccess).not.toHaveBeenCalled();+ });++ it("toasts only after the server confirms, and can't be submitted twice meanwhile", async () => {+ let resolve!: (value: { success: boolean }) => void;+ mocks.deleteFunnel.mockReturnValue(new Promise(r => (resolve = r)));+ const { container } = renderRow();++ openDeleteDialog(container);+ fireEvent.click(await screen.findByRole("button", { name: "Delete" }));++ const pending = (await screen.findByRole("button", { name: "Deleting..." })) as HTMLButtonElement;+ expect(pending.disabled).toBe(true);+ expect(mocks.toastSuccess).not.toHaveBeenCalled();++ await act(async () => resolve({ success: true }));++ await waitFor(() => expect(mocks.toastSuccess).toHaveBeenCalledWith("Funnel deleted successfully"));+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ expect(mocks.deleteFunnel).toHaveBeenCalledTimes(1);+ expect(mocks.deleteFunnel).toHaveBeenCalledWith("42", 7);+ });+});diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsxindex 4e61ba6d1..e54f01a44 100644--- a/client/src/app/[site]/funnels/components/FunnelRow.tsx+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx@@ -53,8 +53,8 @@ export function FunnelRow({ funnel, index }: FunnelRowProps) {: undefined);- // Delete funnel mutation- const { mutate: deleteFunnel, isPending: isDeleting } = useDeleteFunnel();+ // Delete funnel mutation. mutateAsync so the modal waits for the server and shows its errors.+ const { mutateAsync: deleteFunnel, isPending: isDeleting } = useDeleteFunnel();// Handle expansionconst handleExpand = () => {@@ -210,6 +210,7 @@ export function FunnelRow({ funnel, index }: FunnelRowProps) {primaryAction={{children: isDeleting ? t("Deleting...") : t("Delete"),variant: "destructive",+ disabled: isDeleting,}}/>diff --git a/client/src/app/auth/subscription/success/page.test.tsx b/client/src/app/auth/subscription/success/page.test.tsxnew file mode 100644index 000000000..662df665b--- /dev/null+++ b/client/src/app/auth/subscription/success/page.test.tsx@@ -0,0 +1,41 @@+import React from "react";+import { act, cleanup, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({ replace: vi.fn(), push: vi.fn() }));++vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));+vi.mock("next/navigation", () => ({ useRouter: () => ({ replace: mocks.replace, push: mocks.push }) }));++import StripeSuccessPage from "./page";++beforeEach(() => {+ vi.useFakeTimers();+});+afterEach(() => {+ cleanup();+ vi.useRealTimers();+ vi.clearAllMocks();+ window.history.replaceState(null, "", "/");+});++describe("legacy Stripe success page", () => {+ it("confirms the payment, then replaces itself with billing settings", () => {+ window.history.replaceState(null, "", "/auth/subscription/success");+ render(<StripeSuccessPage />);+ expect(screen.getByText("Payment Successful!")).toBeTruthy();+ expect(mocks.replace).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1000));+ expect(mocks.replace).toHaveBeenCalledWith("/settings/billing");+ expect(mocks.push).not.toHaveBeenCalled();+ });++ it("forwards the checkout session id so billing can record the conversion", () => {+ window.history.replaceState(null, "", "/auth/subscription/success?session_id=cs_test_123");+ render(<StripeSuccessPage />);++ act(() => vi.advanceTimersByTime(1000));+ expect(mocks.replace).toHaveBeenCalledWith("/settings/billing?session_id=cs_test_123");+ });+});diff --git a/client/src/app/auth/subscription/success/page.tsx b/client/src/app/auth/subscription/success/page.tsxindex 236ea8de7..32be4e066 100644--- a/client/src/app/auth/subscription/success/page.tsx+++ b/client/src/app/auth/subscription/success/page.tsx@@ -1,16 +1,20 @@"use client";-import { useEffect } from "react";+import { useExtracted } from "next-intl";import { useRouter } from "next/navigation";+import { useEffect } from "react";+// Legacy Stripe success URL: checkouts now return to /{siteId} or /settings/billing. Anyone who still+// lands here goes to billing, keeping session_id so that page can record the conversion.export default function StripeSuccessPage() {+ const t = useExtracted();const router = useRouter();useEffect(() => {- // Add a small delay to ensure the page has fully loaded before redirecting+ // Leave the confirmation on screen for a moment before redirectingconst redirectTimer = setTimeout(() => {- // Redirect to the subscription settings page- router.push("/organization/subscription");+ const sessionId = new URLSearchParams(window.location.search).get("session_id");+ router.replace(sessionId ? `/settings/billing?session_id=${encodeURIComponent(sessionId)}` : "/settings/billing");}, 1000);// Clean up the timer if the component unmounts@@ -20,14 +24,16 @@ export default function StripeSuccessPage() {return (<div className="min-h-dvh flex flex-col items-center justify-center"><div className="text-center">- <h1 className="text-2xl font-bold mb-4">Payment Successful!</h1>+ <h1 className="text-2xl font-bold mb-4">{t("Payment Successful!")}</h1><div className="mb-4"><div className="inline-block w-12 h-12 border-4 border-emerald-500 border-t-transparent rounded-full animate-spin"></div></div><p className="text-lg text-neutral-600 dark:text-neutral-400">- Your subscription has been processed successfully.+ {t("Your subscription has been processed successfully.")}+ </p>+ <p className="text-neutral-600 dark:text-neutral-400 mt-2">+ {t("Redirecting you to your subscription details…")}</p>- <p className="text-neutral-600 dark:text-neutral-400 mt-2">Redirecting you to your subscription details…</p></div></div>);diff --git a/client/src/components/sidebar/Sidebar.tsx b/client/src/components/sidebar/Sidebar.tsxindex 801c51c3e..1d7063395 100644--- a/client/src/components/sidebar/Sidebar.tsx+++ b/client/src/components/sidebar/Sidebar.tsx@@ -39,7 +39,11 @@ function Item({icon?: React.ReactNode;}) {return (- <Link href={href} className="focus:outline-none">+ <Link+ href={href}+ aria-current={active ? "page" : undefined}+ className="block rounded-lg focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:focus-visible:ring-neutral-300"+ ><divclassName={cn("px-3 py-2 rounded-lg transition-colors w-full",