Skip to content

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

feat(onboarding): turn the first pageview into a moment instead of a vanishing card (#1255)

Goldflagab17075a40a8
diff --git a/client/src/app/[site]/components/Header/FirstPageviewCard.tsx b/client/src/app/[site]/components/Header/FirstPageviewCard.tsx
new file mode 100644
index 000000000..99570732e
--- /dev/null
+++ b/client/src/app/[site]/components/Header/FirstPageviewCard.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { motion } from "framer-motion";
+import { useExtracted, useLocale } from "next-intl";
+import type { Ref } from "react";
+import { SparkBurst } from "../../../../components/interior/spark-burst";
+import { TaskSteps } from "../../../../components/interior/task-steps";
+import { Button } from "../../../../components/ui/button";
+import { useWhiteLabel } from "../../../../hooks/useIsWhiteLabel";
+import { SPRING_POP } from "../../../../lib/motion";
+
+// The card mounts once the install card has faded out, so its beats start at zero: the frog lands,
+// the sparks leave it just after, and the checks pop once both are under way.
+const SPARKS_DELAY = 0.06;
+const CHECKS_DELAY = 0.15;
+
+export interface FirstVisitor {
+ country: string;
+ browser: string;
+}
+
+interface FirstPageviewCardProps {
+ headingId: string;
+ siteName: string;
+ isMobileSite: boolean;
+ /** The dashboard's refetch has landed. */
+ dashboardReady: boolean;
+ /** Present only when the live-sessions query already fetched it. */
+ visitor?: FirstVisitor;
+ onDismiss: () => void;
+ dismissRef?: Ref<HTMLButtonElement>;
+}
+
+function regionName(code: string, locale: string) {
+ try {
+ return new Intl.DisplayNames([locale], { type: "region" }).of(code.toUpperCase()) ?? code;
+ } catch {
+ return code;
+ }
+}
+
+export function FirstPageviewCard({
+ headingId,
+ siteName,
+ isMobileSite,
+ dashboardReady,
+ visitor,
+ onDismiss,
+ dismissRef,
+}: FirstPageviewCardProps) {
+ const t = useExtracted();
+ const locale = useLocale();
+ // The frog is Rybbit's mark; white-labelled dashboards keep the card without it.
+ const { isWhiteLabel } = useWhiteLabel();
+
+ const country = visitor?.country ? regionName(visitor.country, locale) : "";
+ const browser = visitor?.browser ?? "";
+ const origin = !country
+ ? undefined
+ : browser
+ ? t("from {country} · {browser}", { country, browser })
+ : t("from {country}", { country });
+
+ const steps = [
+ { id: "installed", label: isMobileSite ? t("SDK installed") : t("Snippet installed") },
+ {
+ id: "received",
+ label: isMobileSite ? t("First screen view received") : t("First pageview received"),
+ meta: origin,
+ },
+ { id: "dashboard", label: t("Your dashboard is filling in") },
+ ];
+
+ return (
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
+ <div className="flex min-w-0 items-start gap-3">
+ {!isWhiteLabel && (
+ // 56px wide and centred beside the checklist, so the burst has room on every side: its sparks
+ // land within ±42px across and ±36px down, inside the card and short of the title.
+ <div aria-hidden="true" className="relative grid w-14 shrink-0 place-items-center self-stretch">
+ <motion.img
+ src="/rybbit/frog_white.svg"
+ alt=""
+ width={32}
+ height={21}
+ className="h-auto w-8 invert dark:invert-0"
+ initial={{ opacity: 0, scale: 0.6 }}
+ animate={{ opacity: 1, scale: 1 }}
+ transition={SPRING_POP}
+ />
+ <SparkBurst inner={{ x: 18, y: 13 }} outer={{ x: 42, y: 36 }} delay={SPARKS_DELAY} />
+ </div>
+ )}
+ <div className="flex min-w-0 flex-col gap-1.5">
+ <h2
+ id={headingId}
+ className="break-words text-base font-semibold tracking-tight text-neutral-900 dark:text-neutral-50"
+ >
+ {siteName ? t("Now tracking {name}", { name: siteName }) : t("Now tracking your site")}
+ </h2>
+ <TaskSteps
+ steps={steps}
+ current={dashboardReady ? steps.length : steps.length - 1}
+ appear
+ appearDelay={CHECKS_DELAY}
+ announce={false}
+ label={t("Setup progress")}
+ />
+ </div>
+ </div>
+ <Button ref={dismissRef} size="sm" onClick={onDismiss} className="shrink-0 self-start">
+ {t("Explore your dashboard")}
+ </Button>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/components/Header/NoData.test.tsx b/client/src/app/[site]/components/Header/NoData.test.tsx
new file mode 100644
index 000000000..2aa9d59c2
--- /dev/null
+++ b/client/src/app/[site]/components/Header/NoData.test.tsx
@@ -0,0 +1,251 @@
+import React from "react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { MotionGlobalConfig } from "framer-motion";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { useGetLiveUserCount } from "@/api/analytics/hooks/useGetLiveUserCount";
+import { useGetSessionsInfinite } from "@/api/analytics/hooks/useGetUserSessions";
+import { useStore } from "@/lib/store";
+import { NoData } from "./NoData";
+
+const mocks = vi.hoisted(() => ({
+ fetch: vi.fn(),
+ hasData: false,
+ live: 0,
+ sessions: [] as unknown[],
+}));
+
+vi.mock("@/api/utils", async importOriginal => ({
+ ...(await importOriginal<typeof import("@/api/utils")>()),
+ authedFetch: mocks.fetch,
+}));
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, unknown>) =>
+ message.replace(/\{(\w+)(?:, \w+)?\}/g, (_, key: string) => String(values?.[key] ?? "")),
+ useLocale: () => "en",
+}));
+vi.mock("@/hooks/useIsWhiteLabel", () => ({ useWhiteLabel: () => ({ isWhiteLabel: false }) }));
+vi.mock("@/components/CodeSnippet", () => ({ CodeSnippet: ({ code }: { code: string }) => <pre>{code}</pre> }));
+
+// What SubHeader's LiveUserCount mounts on every dashboard page.
+function LiveUserCountProbe() {
+ useGetLiveUserCount(5);
+ useGetSessionsInfinite({
+ timeOverride: { mode: "past-minutes", pastMinutesStart: 5, pastMinutesEnd: 0 },
+ limit: 25,
+ refetchInterval: 10000,
+ });
+ return null;
+}
+
+let client: QueryClient;
+
+const callsTo = (path: string) => mocks.fetch.mock.calls.filter(([called]) => called === path).length;
+const waitingHeading = () => screen.findByRole("heading", { name: "Waiting for the first pageview from acme.dev" });
+const arrivedHeading = () => screen.findByRole("heading", { name: "Now tracking acme.dev" });
+
+// has-data's own 30 s poll (or the live-count nudge) asking again after the first pageview landed.
+async function firstPageviewLands() {
+ mocks.hasData = true;
+ await act(() => client.invalidateQueries({ queryKey: ["site-has-data", "7"] }));
+}
+
+function show(extra?: React.ReactNode) {
+ return render(
+ <QueryClientProvider client={client}>
+ <NoData />
+ {extra}
+ </QueryClientProvider>
+ );
+}
+
+beforeAll(() => {
+ MotionGlobalConfig.skipAnimations = true;
+ // framer restores the scroll position after measuring an "auto" height; jsdom has no scrollTo.
+ vi.spyOn(window, "scrollTo").mockImplementation(() => {});
+});
+
+afterAll(() => {
+ MotionGlobalConfig.skipAnimations = false;
+});
+
+beforeEach(() => {
+ mocks.fetch.mockReset();
+ mocks.hasData = false;
+ mocks.live = 0;
+ mocks.sessions = [];
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ useStore.setState({ site: "7", timezone: "UTC", filters: [] });
+ mocks.fetch.mockImplementation(async (path: string) => {
+ if (path === "/sites/7/has-data") return { hasData: mocks.hasData };
+ if (path === "/sites/7") return { id: null, siteId: 7, name: "acme.dev", domain: "acme.dev", type: "web" };
+ if (path === "/sites/7/live-user-count") return { count: mocks.live };
+ if (path === "/sites/7/sessions") return { data: mocks.sessions };
+ return { data: [] };
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ client.clear();
+ vi.useRealTimers();
+});
+
+describe("NoData", () => {
+ it("shows the install card while the site has no data", async () => {
+ show();
+
+ expect(await waitingHeading()).toBeTruthy();
+ expect(screen.getByRole("status").textContent).toBe("");
+ });
+
+ it("stays out of the way when the site already had data on load", async () => {
+ mocks.hasData = true;
+ show();
+
+ await waitFor(() => expect(client.getQueryData(["site-has-data", "7"])).toBe(true));
+ await waitFor(() => expect(client.getQueryData(["get-site", "7"])).toBeTruthy());
+ expect(screen.queryByRole("heading")).toBeNull();
+ });
+
+ it("turns into a confirmation when has-data flips during the visit, and announces it once", async () => {
+ show();
+ await waitingHeading();
+
+ await firstPageviewLands();
+
+ expect(await arrivedHeading()).toBeTruthy();
+ expect(screen.getByRole("status").textContent).toBe("First pageview received");
+ await waitFor(() => expect(screen.queryByRole("heading", { name: /Waiting/ })).toBeNull());
+ });
+
+ it("asks has-data again as soon as the live count LiveUserCount polls sees a visitor", async () => {
+ show(<LiveUserCountProbe />);
+ await waitingHeading();
+ await waitFor(() => expect(callsTo("/sites/7/live-user-count")).toBe(1));
+
+ // NoData only listens to the cache: the query keeps LiveUserCount's single observer and interval.
+ const liveQueries = client.getQueryCache().findAll({ queryKey: ["live-user-count"] });
+ expect(liveQueries).toHaveLength(1);
+ expect(liveQueries[0].getObserversCount()).toBe(1);
+
+ const before = callsTo("/sites/7/has-data");
+ await act(() => client.refetchQueries({ queryKey: ["live-user-count", "7"] }));
+ expect(callsTo("/sites/7/has-data")).toBe(before);
+
+ mocks.live = 1;
+ mocks.hasData = true;
+ await act(() => client.refetchQueries({ queryKey: ["live-user-count", "7"] }));
+
+ expect(await arrivedHeading()).toBeTruthy();
+ expect(callsTo("/sites/7/has-data")).toBe(before + 1);
+ });
+
+ it("refreshes this site's analytics queries once the morph has settled, then ticks the dashboard step", async () => {
+ show(<LiveUserCountProbe />);
+ await waitingHeading();
+ const params = { time_zone: "UTC" };
+ client.setQueryData(["overview", "7", "overview", params, undefined], { sessions: 0 });
+ client.setQueryData(["overview", "8", "overview", params, undefined], { sessions: 0 });
+ const liveBefore = callsTo("/sites/7/live-user-count");
+ const sessionsBefore = callsTo("/sites/7/sessions");
+
+ await firstPageviewLands();
+ await arrivedHeading();
+
+ // Nothing refetches during the swap: the dashboard's re-renders would stall the height spring.
+ expect(callsTo("/sites/7/live-user-count")).toBe(liveBefore);
+ const step = screen.getByText("Your dashboard is filling in").closest("li")!;
+ expect(step.textContent).toContain("In progress:");
+
+ // Then real useAnalyticsQuery keys on screen refetch; off-screen ones are only marked stale.
+ await waitFor(() => expect(callsTo("/sites/7/live-user-count")).toBe(liveBefore + 1), { timeout: 2000 });
+ expect(callsTo("/sites/7/sessions")).toBe(sessionsBefore + 1);
+ expect(client.getQueryState(["overview", "7", "overview", params, undefined])?.isInvalidated).toBe(true);
+ expect(client.getQueryState(["overview", "8", "overview", params, undefined])?.isInvalidated).toBe(false);
+ expect(client.getQueryState(["get-site", "7"])?.isInvalidated).toBe(false);
+ await waitFor(() => expect(step.textContent).toContain("Done:"), { timeout: 2000 });
+ });
+
+ it("still refreshes the dashboard straight away when the confirmation is dismissed early", async () => {
+ show(<LiveUserCountProbe />);
+ await waitingHeading();
+ const liveBefore = callsTo("/sites/7/live-user-count");
+
+ await firstPageviewLands();
+ await arrivedHeading();
+ fireEvent.click(screen.getByRole("button", { name: "Explore your dashboard" }));
+
+ // Well inside ARRIVAL_REFRESH_DELAY_MS: the dismissal itself started the refetch.
+ await waitFor(() => expect(callsTo("/sites/7/live-user-count")).toBe(liveBefore + 1), { timeout: 300 });
+ });
+
+ it("lets the install card finish fading out before the confirmation mounts", async () => {
+ // A real 0.14 s exit, so there is a window to look into (skipped animations end on the next frame).
+ MotionGlobalConfig.skipAnimations = false;
+ try {
+ show();
+ await waitingHeading();
+
+ await firstPageviewLands();
+ // The commit that announces the arrival is the one that starts the install card's exit.
+ await waitFor(() => expect(screen.getByRole("status").textContent).toBe("First pageview received"));
+
+ // Mid-exit: the install card is still laid out (and inert); the confirmation isn't mounted yet.
+ expect(screen.getByText("Waiting for the first pageview from acme.dev")).toBeTruthy();
+ expect(screen.queryByText("Now tracking acme.dev")).toBeNull();
+
+ await arrivedHeading();
+ expect(screen.queryByText("Waiting for the first pageview from acme.dev")).toBeNull();
+ } finally {
+ MotionGlobalConfig.skipAnimations = true;
+ }
+ });
+
+ it("names the first visitor from sessions the live list already fetched", async () => {
+ mocks.sessions = [
+ { session_id: "s2", session_start: "2026-09-28 10:04:00", country: "FR", browser: "Safari" },
+ { session_id: "s1", session_start: "2026-09-28 10:01:00", country: "DE", browser: "Firefox" },
+ ];
+ show(<LiveUserCountProbe />);
+ await waitingHeading();
+
+ await firstPageviewLands();
+
+ expect(await screen.findByText("from Germany · Firefox")).toBeTruthy();
+ });
+
+ it("moves focus into the confirmation when it was inside the waiting card", async () => {
+ show();
+ await waitingHeading();
+ screen.getByRole("tab", { name: "AI agent" }).focus();
+
+ await firstPageviewLands();
+ await arrivedHeading();
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getByRole("button", { name: "Explore your dashboard" }))
+ );
+ });
+
+ it("leaves focus alone when it wasn't in the waiting card", async () => {
+ show();
+ await waitingHeading();
+
+ await firstPageviewLands();
+ await arrivedHeading();
+
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it("collapses when dismissed", async () => {
+ show();
+ await waitingHeading();
+ await firstPageviewLands();
+ await arrivedHeading();
+
+ fireEvent.click(screen.getByRole("button", { name: "Explore your dashboard" }));
+
+ await waitFor(() => expect(screen.queryByRole("heading", { name: "Now tracking acme.dev" })).toBeNull());
+ });
+});
diff --git a/client/src/app/[site]/components/Header/NoData.tsx b/client/src/app/[site]/components/Header/NoData.tsx
index 4269262ee..f4ea6e7ed 100644
--- a/client/src/app/[site]/components/Header/NoData.tsx
+++ b/client/src/app/[site]/components/Header/NoData.tsx
@@ -33,14 +33,20 @@ import {
SiWoocommerce,
SiWordpress,
} from "@icons-pack/react-simple-icons";
+import { AnimatePresence, motion, useIsPresent, useReducedMotion } from "framer-motion";
import { ChevronRight } from "lucide-react";
import { useExtracted } from "next-intl";
-import React, { useState } from "react";
+import React, { type Ref, useCallback, useId, useLayoutEffect, useRef, useState } from "react";
+import type { SiteResponse } from "../../../../api/admin/endpoints";
import { useGetSite, useSiteHasData } from "../../../../api/admin/hooks/useSites";
import { CodeSnippet } from "../../../../components/CodeSnippet";
import { ExternalLink } from "../../../../components/ExternalLink";
+import { AutoHeight } from "../../../../components/interior/auto-height";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/tabs";
+import { FADE_IN, FADE_OUT, INSTANT, SPRING_DISCLOSE } from "../../../../lib/motion";
import { useStore } from "../../../../lib/store";
+import { FirstPageviewCard } from "./FirstPageviewCard";
+import { useArrivalRefresh, useFirstPageviewJourney, useFirstSession, useLiveVisitorNudge } from "./firstPageview";
const ICON = "h-3.5 w-3.5";
@@ -115,19 +121,120 @@ const VISIBLE_PLATFORM_COUNT = 12;
const FOCUS_RING =
"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 dark:focus-visible:ring-neutral-300";
+// A card on its way out keeps its layout while it animates, but must not take focus or clicks.
+function InertWhileExiting(props: React.ComponentProps<"div">) {
+ const isPresent = useIsPresent();
+ return <div {...props} inert={!isPresent} />;
+}
+
+/**
+ * The install card. It waits for the site's first pageview, then turns in place into a short
+ * confirmation that stays until dismissed. A site that already had data when the page loaded shows
+ * nothing: only a false → true has-data flip seen in this page session counts as an arrival.
+ */
export function NoData() {
const t = useExtracted();
- const { site } = useStore();
- const [showAllPlatforms, setShowAllPlatforms] = useState(false);
- const [showJsFallback, setShowJsFallback] = useState(false);
- const { data: siteHasData, isLoading } = useSiteHasData(site);
+ const site = useStore(state => state.site);
+ const reduceMotion = useReducedMotion();
+ const { data: siteHasData } = useSiteHasData(site);
const { data: siteMetadata, isLoading: isLoadingSiteMetadata } = useGetSite(site);
+ const { phase, settle, dismiss } = useFirstPageviewJourney(site, siteHasData);
+ const waitingHeadingId = useId();
+ const arrivedHeadingId = useId();
+ const waitingRef = useRef<HTMLDivElement>(null);
+ const focusDismissOnMount = useRef(false);
+ // The confirmation mounts only once the install card has faded out, so focus is handed over here.
+ const dismissRef = useCallback((button: HTMLButtonElement | null) => {
+ if (!button || !focusDismissOnMount.current) return;
+ focusDismissOnMount.current = false;
+ button.focus({ preventScroll: true });
+ }, []);
const siteId = siteMetadata?.id ?? siteMetadata?.siteId ?? (site || undefined);
+ const isMobileSite = siteMetadata?.type === "mobile";
+ const waiting = phase === "waiting";
+ const filling = phase === "filling";
+ const arrived = filling || phase === "ready";
- if (siteHasData || isLoading || isLoadingSiteMetadata || !siteId) {
- return null;
- }
+ useLiveVisitorNudge(site, waiting);
+ useArrivalRefresh(site, filling, settle);
+ const firstSession = useFirstSession(site, arrived);
+
+ useLayoutEffect(() => {
+ // The waiting card goes inert as it fades out; keep keyboard focus in the card it turns into.
+ if (filling && waitingRef.current?.contains(document.activeElement)) focusDismissOnMount.current = true;
+ }, [filling]);
+
+ const showCard = (waiting || arrived) && !isLoadingSiteMetadata;
+
+ return (
+ <AnimatePresence initial={false}>
+ {showCard && siteId ? (
+ <motion.div
+ key={site}
+ className="overflow-hidden"
+ exit={{ height: 0, opacity: 0 }}
+ transition={reduceMotion ? INSTANT : { height: SPRING_DISCLOSE, opacity: FADE_OUT }}
+ >
+ <InertWhileExiting className="pt-4">
+ <section
+ aria-labelledby={arrived ? arrivedHeadingId : waitingHeadingId}
+ className="overflow-hidden rounded-lg border border-neutral-100 bg-white dark:border-neutral-850 dark:bg-neutral-900"
+ >
+ {/* "wait": the install card keeps its height and fades out completely before the
+ confirmation mounts; AutoHeight then carries the change in one continuous spring. */}
+ <AutoHeight contentClassName="p-4">
+ <AnimatePresence initial={false} mode="wait">
+ {arrived ? (
+ <motion.div key="arrived" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={FADE_IN}>
+ <FirstPageviewCard
+ headingId={arrivedHeadingId}
+ siteName={siteMetadata?.name ?? ""}
+ isMobileSite={isMobileSite}
+ dashboardReady={phase === "ready"}
+ visitor={
+ firstSession ? { country: firstSession.country, browser: firstSession.browser } : undefined
+ }
+ onDismiss={dismiss}
+ dismissRef={dismissRef}
+ />
+ </motion.div>
+ ) : (
+ <motion.div key="waiting" exit={{ opacity: 0 }} transition={FADE_OUT}>
+ <WaitingCard
+ ref={waitingRef}
+ headingId={waitingHeadingId}
+ siteId={siteId}
+ siteMetadata={siteMetadata ?? undefined}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </AutoHeight>
+ {/* Mounted, empty, while waiting so the arrival is announced exactly once. */}
+ <p role="status" className="sr-only">
+ {arrived ? (isMobileSite ? t("First screen view received") : t("First pageview received")) : ""}
+ </p>
+ </section>
+ </InertWhileExiting>
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
+ );
+}
+
+interface WaitingCardProps {
+ ref?: Ref<HTMLDivElement>;
+ headingId: string;
+ siteId: string | number;
+ siteMetadata?: SiteResponse;
+}
+
+function WaitingCard({ ref, headingId, siteId, siteMetadata }: WaitingCardProps) {
+ const t = useExtracted();
+ const isPresent = useIsPresent();
+ const [showAllPlatforms, setShowAllPlatforms] = useState(false);
+ const [showJsFallback, setShowJsFallback] = useState(false);
const visibleGuides = showAllPlatforms ? PLATFORM_GUIDES : PLATFORM_GUIDES.slice(0, VISIBLE_PLATFORM_COUNT);
const hiddenCount = PLATFORM_GUIDES.length - VISIBLE_PLATFORM_COUNT;
@@ -164,15 +271,18 @@ await rybbit.init({
const rnAiPrompt = `Install Rybbit analytics in this React Native app.\n\n1. Install the SDK:\n\nnpm install @rybbit/react-native @react-native-async-storage/async-storage\n\n2. Initialize it once in the app entry point:\n\n${rnInitSnippet}\n\n3. If the app uses React Navigation, track screens automatically:\n\nconst navigationTracker = rybbit.createNavigationTracker();\n\n<NavigationContainer\n ref={navigationRef}\n onReady={() => navigationTracker.onReady(navigationRef)}\n onStateChange={() => navigationTracker.onStateChange(navigationRef)}\n>\n\nDocs: https://rybbit.com/docs/sdks/react-native\n`;
return (
- <section className="mt-4 rounded-lg border border-neutral-100 bg-white p-4 dark:border-neutral-850 dark:bg-neutral-900">
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-1">
+ <div ref={ref} inert={!isPresent} className="flex flex-col gap-3">
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
+ <div className="flex min-w-0 flex-col gap-1">
<div className="flex items-start gap-3">
<span className="relative mt-1.5 flex h-3 w-3 shrink-0" aria-hidden="true">
<span className="absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75 motion-safe:animate-ping"></span>
<span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>
</span>
- <h2 className="break-words text-base font-semibold tracking-tight text-neutral-900 dark:text-neutral-50">
+ <h2
+ id={headingId}
+ className="break-words text-base font-semibold tracking-tight text-neutral-900 dark:text-neutral-50"
+ >
{isMobileSite
? t("Waiting for the first screen view from {name}", { name: siteMetadata?.name ?? "" })
: t("Waiting for the first pageview from {name}", { name: siteMetadata?.name ?? "" })}
@@ -184,111 +294,111 @@ await rybbit.init({
: t("Install the snippet below, then open your site. This page updates on its own once data arrives.")}
</p>
</div>
+ </div>
- <div className="flex flex-col gap-2">
- <Tabs defaultValue={isMobileSite ? "sdk" : "html"}>
- <TabsList>
- {isMobileSite ? (
- <TabsTrigger value="sdk">React Native</TabsTrigger>
- ) : (
- <TabsTrigger value="html">HTML</TabsTrigger>
- )}
- <TabsTrigger value="ai">{t("AI agent")}</TabsTrigger>
- </TabsList>
- {isMobileSite && (
- <TabsContent value="sdk" className="flex flex-col gap-2">
- <p className="text-xs text-neutral-600 dark:text-neutral-400">{t("Install the SDK package:")}</p>
- <CodeSnippet language="bash" code={rnInstallSnippet} className="text-xs" />
- <p className="text-xs text-neutral-600 dark:text-neutral-400">
- {t("Initialize it once in your app entry point:")}
- </p>
- <CodeSnippet language="TypeScript" code={rnInitSnippet} className="text-xs" />
- </TabsContent>
- )}
- {!isMobileSite && (
- <TabsContent value="html" className="flex flex-col gap-2">
- <p className="text-xs text-neutral-600 dark:text-neutral-400">
- {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}
- </p>
- <CodeSnippet language="HTML" code={htmlSnippet} className="text-xs" />
- <div>
- <button
- type="button"
- onClick={() => setShowJsFallback(!showJsFallback)}
- aria-expanded={showJsFallback}
- className={`inline-flex items-center gap-1 rounded-md text-xs text-neutral-600 transition-colors hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-50 ${FOCUS_RING}`}
- >
- <ChevronRight
- className={`h-3.5 w-3.5 motion-safe:transition-transform ${showJsFallback ? "rotate-90" : ""}`}
- />
- {t("If the snippet doesn't work, try JavaScript injection")}
- </button>
- {showJsFallback && (
- <div className="mt-2 flex flex-col gap-2">
- <p className="text-xs text-neutral-600 dark:text-neutral-400">
- {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}
- </p>
- <CodeSnippet language="HTML" code={jsSnippet} className="text-xs" />
- </div>
- )}
- </div>
- </TabsContent>
+ <div className="flex flex-col gap-2">
+ <Tabs defaultValue={isMobileSite ? "sdk" : "html"}>
+ <TabsList>
+ {isMobileSite ? (
+ <TabsTrigger value="sdk">React Native</TabsTrigger>
+ ) : (
+ <TabsTrigger value="html">HTML</TabsTrigger>
)}
- <TabsContent value="ai" className="flex flex-col gap-2">
+ <TabsTrigger value="ai">{t("AI agent")}</TabsTrigger>
+ </TabsList>
+ {isMobileSite && (
+ <TabsContent value="sdk" className="flex flex-col gap-2">
+ <p className="text-xs text-neutral-600 dark:text-neutral-400">{t("Install the SDK package:")}</p>
+ <CodeSnippet language="bash" code={rnInstallSnippet} className="text-xs" />
<p className="text-xs text-neutral-600 dark:text-neutral-400">
- {t("Copy this prompt into Claude Code, Cursor, or another coding agent:")}
+ {t("Initialize it once in your app entry point:")}
</p>
- <CodeSnippet code={isMobileSite ? rnAiPrompt : aiPrompt} className="text-xs" />
+ <CodeSnippet language="TypeScript" code={rnInitSnippet} className="text-xs" />
</TabsContent>
- </Tabs>
- <div className="flex flex-wrap items-center gap-2 text-xs">
- {isMobileSite ? (
- <ExternalLink href="https://rybbit.com/docs/sdks/react-native">{t("React Native SDK docs")}</ExternalLink>
- ) : (
- <>
- <ExternalLink href="https://rybbit.com/docs/script">{t("Installation docs")}</ExternalLink>
- <span className="text-neutral-300 dark:text-neutral-600" aria-hidden="true">
- ·
- </span>
- <ExternalLink href="https://rybbit.com/docs/script-troubleshooting">
- {t("Troubleshooting guide")}
- </ExternalLink>
- </>
- )}
- </div>
+ )}
+ {!isMobileSite && (
+ <TabsContent value="html" className="flex flex-col gap-2">
+ <p className="text-xs text-neutral-600 dark:text-neutral-400">
+ {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}
+ </p>
+ <CodeSnippet language="HTML" code={htmlSnippet} className="text-xs" />
+ <div>
+ <button
+ type="button"
+ onClick={() => setShowJsFallback(!showJsFallback)}
+ aria-expanded={showJsFallback}
+ className={`inline-flex items-center gap-1 rounded-md text-xs text-neutral-600 transition-colors hover:text-neutral-900 dark:text-neutral-400 dark:hover:text-neutral-50 ${FOCUS_RING}`}
+ >
+ <ChevronRight
+ className={`h-3.5 w-3.5 motion-safe:transition-transform ${showJsFallback ? "rotate-90" : ""}`}
+ />
+ {t("If the snippet doesn't work, try JavaScript injection")}
+ </button>
+ {showJsFallback && (
+ <div className="mt-2 flex flex-col gap-2">
+ <p className="text-xs text-neutral-600 dark:text-neutral-400">
+ {t("Paste this into the {headTag} of your website:", { headTag: "<head>" })}
+ </p>
+ <CodeSnippet language="HTML" code={jsSnippet} className="text-xs" />
+ </div>
+ )}
+ </div>
+ </TabsContent>
+ )}
+ <TabsContent value="ai" className="flex flex-col gap-2">
+ <p className="text-xs text-neutral-600 dark:text-neutral-400">
+ {t("Copy this prompt into Claude Code, Cursor, or another coding agent:")}
+ </p>
+ <CodeSnippet code={isMobileSite ? rnAiPrompt : aiPrompt} className="text-xs" />
+ </TabsContent>
+ </Tabs>
+ <div className="flex flex-wrap items-center gap-2 text-xs">
+ {isMobileSite ? (
+ <ExternalLink href="https://rybbit.com/docs/sdks/react-native">{t("React Native SDK docs")}</ExternalLink>
+ ) : (
+ <>
+ <ExternalLink href="https://rybbit.com/docs/script">{t("Installation docs")}</ExternalLink>
+ <span className="text-neutral-300 dark:text-neutral-600" aria-hidden="true">
+ ·
+ </span>
+ <ExternalLink href="https://rybbit.com/docs/script-troubleshooting">
+ {t("Troubleshooting guide")}
+ </ExternalLink>
+ </>
+ )}
</div>
+ </div>
- {!isMobileSite && (
- <div className="flex flex-col gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-850">
- <h3 className="text-xs font-medium text-neutral-600 dark:text-neutral-400">
- {t("Or follow a setup guide for your platform")}
- </h3>
- <div className="flex flex-wrap items-center gap-1.5">
- {visibleGuides.map(guide => (
- <a
- key={guide.title}
- href={guide.href}
- target="_blank"
- rel="noopener noreferrer"
- className={`group inline-flex h-7 items-center gap-1.5 rounded-md border border-neutral-150 bg-white px-2.5 text-xs font-medium text-neutral-700 transition-colors hover:border-neutral-300 hover:text-neutral-900 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-300 dark:hover:border-neutral-600 dark:hover:text-neutral-50 ${FOCUS_RING}`}
- >
- <span className="text-neutral-500 transition-colors group-hover:text-emerald-500 dark:text-neutral-400 dark:group-hover:text-emerald-400">
- {guide.icon}
- </span>
- {guide.title}
- </a>
- ))}
- <button
- type="button"
- onClick={() => setShowAllPlatforms(!showAllPlatforms)}
- className={`inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-100 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50 ${FOCUS_RING}`}
+ {!isMobileSite && (
+ <div className="flex flex-col gap-2 border-t border-neutral-100 pt-3 dark:border-neutral-850">
+ <h3 className="text-xs font-medium text-neutral-600 dark:text-neutral-400">
+ {t("Or follow a setup guide for your platform")}
+ </h3>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {visibleGuides.map(guide => (
+ <a
+ key={guide.title}
+ href={guide.href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={`group inline-flex h-7 items-center gap-1.5 rounded-md border border-neutral-150 bg-white px-2.5 text-xs font-medium text-neutral-700 transition-colors hover:border-neutral-300 hover:text-neutral-900 dark:border-neutral-800 dark:bg-neutral-850 dark:text-neutral-300 dark:hover:border-neutral-600 dark:hover:text-neutral-50 ${FOCUS_RING}`}
>
- {showAllPlatforms ? t("Show fewer") : t("Show {count} more", { count: String(hiddenCount) })}
- </button>
- </div>
+ <span className="text-neutral-500 transition-colors group-hover:text-emerald-500 dark:text-neutral-400 dark:group-hover:text-emerald-400">
+ {guide.icon}
+ </span>
+ {guide.title}
+ </a>
+ ))}
+ <button
+ type="button"
+ onClick={() => setShowAllPlatforms(!showAllPlatforms)}
+ className={`inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium text-neutral-600 transition-colors hover:bg-neutral-100 hover:text-neutral-900 dark:text-neutral-400 dark:hover:bg-neutral-800 dark:hover:text-neutral-50 ${FOCUS_RING}`}
+ >
+ {showAllPlatforms ? t("Show fewer") : t("Show {count} more", { count: String(hiddenCount) })}
+ </button>
</div>
- )}
- </div>
- </section>
+ </div>
+ )}
+ </div>
);
}
diff --git a/client/src/app/[site]/components/Header/firstPageview.test.ts b/client/src/app/[site]/components/Header/firstPageview.test.ts
new file mode 100644
index 000000000..1b05f6873
--- /dev/null
+++ b/client/src/app/[site]/components/Header/firstPageview.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from "vitest";
+import {
+ earliestSession,
+ type FirstPageviewPhase,
+ isSiteAnalyticsQueryKey,
+ nextFirstPageviewPhase,
+} from "./firstPageview";
+
+const hasData = (value: boolean | undefined) => ({ type: "has-data", hasData: value }) as const;
+
+describe("nextFirstPageviewPhase", () => {
+ it("waits when has-data first answers false, and stays quiet when it first answers true", () => {
+ expect(nextFirstPageviewPhase("unknown", hasData(false))).toBe("waiting");
+ expect(nextFirstPageviewPhase("unknown", hasData(true))).toBe("none");
+ expect(nextFirstPageviewPhase("unknown", hasData(undefined))).toBe("unknown");
+ });
+
+ it("celebrates only a false → true flip, then settles and dismisses", () => {
+ let phase: FirstPageviewPhase = "unknown";
+ phase = nextFirstPageviewPhase(phase, hasData(false));
+ phase = nextFirstPageviewPhase(phase, hasData(undefined));
+ expect(phase).toBe("waiting");
+ phase = nextFirstPageviewPhase(phase, hasData(true));
+ expect(phase).toBe("filling");
+ expect(nextFirstPageviewPhase(phase, hasData(true))).toBe("filling");
+ phase = nextFirstPageviewPhase(phase, { type: "settled" });
+ expect(phase).toBe("ready");
+ phase = nextFirstPageviewPhase(phase, { type: "dismiss" });
+ expect(phase).toBe("dismissed");
+ expect(nextFirstPageviewPhase(phase, hasData(false))).toBe("dismissed");
+ });
+
+ it("can be dismissed while the dashboard is still filling, and ignores stray events", () => {
+ expect(nextFirstPageviewPhase("filling", { type: "dismiss" })).toBe("dismissed");
+ expect(nextFirstPageviewPhase("waiting", { type: "dismiss" })).toBe("waiting");
+ expect(nextFirstPageviewPhase("waiting", { type: "settled" })).toBe("waiting");
+ expect(nextFirstPageviewPhase("none", hasData(false))).toBe("none");
+ });
+});
+
+describe("isSiteAnalyticsQueryKey", () => {
+ const params = { time_zone: "UTC" };
+
+ it("matches useAnalyticsQuery keys for the site, whatever the key prefix", () => {
+ expect(isSiteAnalyticsQueryKey(["overview", "7", "overview", params, undefined], "7")).toBe(true);
+ expect(isSiteAnalyticsQueryKey(["user-info", "u1", "7", "users/u1", params, undefined], "7")).toBe(true);
+ expect(isSiteAnalyticsQueryKey(["pathname", 7, "metric", params, undefined], "7")).toBe(true);
+ expect(isSiteAnalyticsQueryKey(["sessions-infinite", "7", "sessions", params, undefined, "infinite"], "7")).toBe(
+ true
+ );
+ });
+
+ it("leaves other sites, organization scopes and non-analytics keys alone", () => {
+ expect(isSiteAnalyticsQueryKey(["overview", "8", "overview", params, undefined], "7")).toBe(false);
+ expect(isSiteAnalyticsQueryKey(["site-cards", "organization:org", "site-cards", params, {}], "7")).toBe(false);
+ expect(isSiteAnalyticsQueryKey(["get-site", "7"], "7")).toBe(false);
+ expect(isSiteAnalyticsQueryKey(["site-has-data", "7"], "7")).toBe(false);
+ expect(isSiteAnalyticsQueryKey(["gsc-data", "pages", "7", "2026-09-01", "2026-09-28", "UTC"], "7")).toBe(false);
+ expect(isSiteAnalyticsQueryKey(["site-event-count-range", 7, "2026-09-01", "2026-09-28", "UTC"], "7")).toBe(false);
+ });
+});
+
+describe("earliestSession", () => {
+ const session = (id: string, start: string) => ({ session_id: id, session_start: start }) as never;
+
+ it("picks the earliest session across every cached page and query", () => {
+ const live = { pages: [[session("b", "2026-09-28 10:05:00")], null], pageParams: [1, 2] };
+ const other = { pages: [[session("a", "2026-09-28 10:01:00"), session("c", "2026-09-28 10:09:00")]] };
+ expect(earliestSession([live, undefined, other])?.session_id).toBe("a");
+ });
+
+ it("is undefined when nothing has been fetched", () => {
+ expect(earliestSession([])).toBeUndefined();
+ expect(earliestSession([undefined, { pages: [[]] }])).toBeUndefined();
+ });
+});
diff --git a/client/src/app/[site]/components/Header/firstPageview.ts b/client/src/app/[site]/components/Header/firstPageview.ts
new file mode 100644
index 000000000..d4006d9a8
--- /dev/null
+++ b/client/src/app/[site]/components/Header/firstPageview.ts
@@ -0,0 +1,179 @@
+import { type InfiniteData, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
+import type { GetSessionsResponse, LiveUserCountResponse } from "../../../../api/analytics/endpoints";
+
+export type FirstPageviewPhase = "unknown" | "none" | "waiting" | "filling" | "ready" | "dismissed";
+
+export type FirstPageviewEvent =
+ | { type: "has-data"; hasData: boolean | undefined }
+ | { type: "settled" }
+ | { type: "dismiss" };
+
+type Session = GetSessionsResponse[number];
+
+// useSiteHasData's key.
+const SITE_HAS_DATA_KEY = "site-has-data";
+// Both polled every 10 s by SubHeader's LiveUserCount (useGetLiveUserCount, useGetSessionsInfinite).
+const LIVE_USER_COUNT_KEY = "live-user-count";
+const LIVE_SESSIONS_KEY = "sessions-infinite";
+// The dashboard refetch waits for the morph (install card fade-out, then the height spring) to mostly
+// settle: its re-renders would otherwise stall the spring on the main thread into visible jumps. It
+// also keeps "Your dashboard is filling in" on screen long enough to read.
+export const ARRIVAL_REFRESH_DELAY_MS = 600;
+
+/**
+ * The install card's lifecycle for one site:
+ * unknown → waiting (has-data answered false) → filling (it flipped to true while we watched)
+ * → ready (the dashboard's queries refetched) → dismissed.
+ * A site that already had data when has-data first answered goes to "none": nothing to celebrate.
+ */
+export function nextFirstPageviewPhase(phase: FirstPageviewPhase, event: FirstPageviewEvent): FirstPageviewPhase {
+ switch (event.type) {
+ case "has-data":
+ if (event.hasData === undefined) return phase;
+ if (phase === "unknown") return event.hasData ? "none" : "waiting";
+ return phase === "waiting" && event.hasData ? "filling" : phase;
+ case "settled":
+ return phase === "filling" ? "ready" : phase;
+ case "dismiss":
+ return phase === "filling" || phase === "ready" ? "dismissed" : phase;
+ }
+}
+
+/**
+ * Whether a query was built by useAnalyticsQuery / useAnalyticsInfiniteQuery for `site`. Those keys are
+ * one or more key parts followed by [scope, path, params, body], plus "infinite" for infinite queries.
+ */
+export function isSiteAnalyticsQueryKey(queryKey: readonly unknown[], site: string): boolean {
+ const end = queryKey[queryKey.length - 1] === "infinite" ? queryKey.length - 1 : queryKey.length;
+ const scope = end - 4;
+ const params = queryKey[scope + 2];
+ return (
+ scope >= 1 &&
+ String(queryKey[scope]) === site &&
+ typeof queryKey[scope + 1] === "string" &&
+ typeof params === "object" &&
+ params !== null
+ );
+}
+
+/** The session with the earliest start across cached session-list pages. */
+export function earliestSession(cached: readonly unknown[]): Session | undefined {
+ let earliest: Session | undefined;
+ for (const data of cached) {
+ for (const page of (data as InfiniteData<GetSessionsResponse | null> | undefined)?.pages ?? []) {
+ for (const session of page ?? []) {
+ if (!earliest || session.session_start < earliest.session_start) earliest = session;
+ }
+ }
+ }
+ return earliest;
+}
+
+interface Journey {
+ site: string;
+ phase: FirstPageviewPhase;
+}
+
+const startJourney = (site: string): Journey => ({ site, phase: "unknown" });
+
+/** The card's phase for one site. Switching sites starts over. */
+export function useFirstPageviewJourney(site: string, hasData: boolean | undefined) {
+ const [journey, setJourney] = useState(() => startJourney(site));
+
+ // Folded in during render rather than in an effect, so a has-data flip never paints a stale card.
+ const base = journey.site === site ? journey : startJourney(site);
+ const phase = nextFirstPageviewPhase(base.phase, { type: "has-data", hasData });
+ if (base !== journey || phase !== journey.phase) setJourney({ ...base, phase });
+
+ const settle = useCallback(
+ () => setJourney(current => ({ ...current, phase: nextFirstPageviewPhase(current.phase, { type: "settled" }) })),
+ []
+ );
+ const dismiss = useCallback(
+ () => setJourney(current => ({ ...current, phase: nextFirstPageviewPhase(current.phase, { type: "dismiss" }) })),
+ []
+ );
+ return { phase, settle, dismiss };
+}
+
+/**
+ * While the site has no data, re-ask has-data the moment the live-user-count query (which SubHeader's
+ * LiveUserCount polls every 10 s) sees a visitor, instead of waiting out has-data's 30 s poll.
+ *
+ * It listens to the query cache instead of mounting a useGetLiveUserCount observer of its own: each
+ * observer runs its own refetch interval, and one mounted here, in the layout that outlives every page's
+ * LiveUserCount, would drift out of phase with it and double the requests, or start a new 10 s poll on
+ * pages that have no LiveUserCount. Pages without one fall back to has-data's own poll.
+ */
+export function useLiveVisitorNudge(site: string, enabled: boolean) {
+ const queryClient = useQueryClient();
+
+ useEffect(() => {
+ if (!enabled || !site) return;
+ const cache = queryClient.getQueryCache();
+ const someoneOnline = () =>
+ cache
+ .findAll({ queryKey: [LIVE_USER_COUNT_KEY, site] })
+ .some(query => ((query.state.data as LiveUserCountResponse | undefined)?.count ?? 0) > 0);
+ const nudge = () => void queryClient.invalidateQueries({ queryKey: [SITE_HAS_DATA_KEY, site], exact: true });
+
+ let online = someoneOnline();
+ if (online) nudge();
+ return cache.subscribe(event => {
+ if (event.type !== "updated" || event.action.type !== "success") return;
+ const [key, scope] = event.query.queryKey;
+ if (key !== LIVE_USER_COUNT_KEY || scope !== site) return;
+ const now = someoneOnline();
+ if (now && !online) nudge();
+ online = now;
+ });
+ }, [enabled, queryClient, site]);
+}
+
+/**
+ * The first visitor, read from sessions the live-sessions query has already fetched for the site.
+ * Never fetches: undefined until (and unless) that data is in the cache.
+ */
+export function useFirstSession(site: string, enabled: boolean): Session | undefined {
+ const cache = useQueryClient().getQueryCache();
+ const subscribe = useCallback(
+ (onChange: () => void) => (enabled ? cache.subscribe(onChange) : () => {}),
+ [cache, enabled]
+ );
+ const getSnapshot = () =>
+ enabled && site
+ ? earliestSession(cache.findAll({ queryKey: [LIVE_SESSIONS_KEY, site] }).map(query => query.state.data))
+ : undefined;
+ return useSyncExternalStore(subscribe, getSnapshot, () => undefined);
+}
+
+/**
+ * Shortly after arrival, refetch this site's analytics queries that are on screen and mark the rest
+ * stale, so the dashboard fills in now rather than after their 60 s staleTime. Calls `onSettled` once
+ * they land. Dismissing (or leaving) before the delay runs out starts the refetch at once.
+ */
+export function useArrivalRefresh(site: string, enabled: boolean, onSettled: () => void) {
+ const queryClient = useQueryClient();
+
+ useEffect(() => {
+ if (!enabled || !site) return;
+ let current = true;
+ let started = false;
+ const refresh = () => {
+ if (started) return;
+ started = true;
+ void queryClient
+ .invalidateQueries({ predicate: query => isSiteAnalyticsQueryKey(query.queryKey, site) })
+ .then(() => {
+ if (current) onSettled();
+ });
+ };
+ const timeout = window.setTimeout(refresh, ARRIVAL_REFRESH_DELAY_MS);
+ return () => {
+ current = false;
+ window.clearTimeout(timeout);
+ refresh();
+ };
+ }, [enabled, onSettled, queryClient, site]);
+}
diff --git a/client/src/components/interior/auto-height.test.tsx b/client/src/components/interior/auto-height.test.tsx
new file mode 100644
index 000000000..087beab77
--- /dev/null
+++ b/client/src/components/interior/auto-height.test.tsx
@@ -0,0 +1,93 @@
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { MotionGlobalConfig } from "framer-motion";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AutoHeight } from "./auto-height";
+
+const mocks = vi.hoisted(() => ({ reduced: false }));
+vi.mock("framer-motion", async importOriginal => ({
+ ...(await importOriginal<typeof import("framer-motion")>()),
+ useReducedMotion: () => mocks.reduced,
+}));
+
+// jsdom has no layout, so the content's height and the ResizeObserver deliveries are driven by hand.
+let contentHeight = 0;
+let deliver: () => void = () => {};
+
+beforeEach(() => {
+ mocks.reduced = false;
+ contentHeight = 100;
+ MotionGlobalConfig.skipAnimations = true;
+ Object.defineProperty(HTMLElement.prototype, "offsetHeight", { configurable: true, get: () => contentHeight });
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ constructor(callback: ResizeObserverCallback) {
+ deliver = () => callback([], this as unknown as ResizeObserver);
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ MotionGlobalConfig.skipAnimations = false;
+ delete (HTMLElement.prototype as { offsetHeight?: number }).offsetHeight;
+ vi.unstubAllGlobals();
+});
+
+function mountBox() {
+ const { container } = render(
+ <AutoHeight contentClassName="p-4">
+ <p>content</p>
+ </AutoHeight>
+ );
+ return container.firstElementChild as HTMLElement;
+}
+
+describe("AutoHeight", () => {
+ it("rests at auto height and clips only while a change animates", () => {
+ const box = mountBox();
+
+ act(() => deliver());
+
+ expect(box.style.height).toBe("");
+ expect(box.className).toContain("overflow-hidden");
+ });
+
+ it("pins the old height before the change paints, springs, then returns to auto", async () => {
+ const box = mountBox();
+
+ contentHeight = 240;
+ act(() => deliver());
+ expect(box.style.height).toBe("100px");
+
+ await waitFor(() => expect(box.style.height).toBe(""));
+ });
+
+ it("pins the old height in the microtask after React commits a swap, before any resize observation", async () => {
+ const Swap = ({ swapped }: { swapped: boolean }) => (
+ <AutoHeight>{swapped ? <p key="after">after</p> : <p key="before">before</p>}</AutoHeight>
+ );
+ const { container, rerender } = render(<Swap swapped={false} />);
+ const box = container.firstElementChild as HTMLElement;
+
+ contentHeight = 40;
+ rerender(<Swap swapped />);
+ await Promise.resolve();
+
+ expect(box.style.height).toBe("100px");
+ });
+
+ it("follows the content without animating under reduced motion", () => {
+ mocks.reduced = true;
+ const box = mountBox();
+
+ contentHeight = 240;
+ act(() => deliver());
+
+ expect(box.style.height).toBe("");
+ });
+});
diff --git a/client/src/components/interior/auto-height.tsx b/client/src/components/interior/auto-height.tsx
new file mode 100644
index 000000000..915a3ddf8
--- /dev/null
+++ b/client/src/components/interior/auto-height.tsx
@@ -0,0 +1,101 @@
+// Adapted from interior.dev "Show More" (MIT). See ./THIRD_PARTY_LICENSES.md
+"use client";
+
+import {
+ animate,
+ type AnimationPlaybackControls,
+ motionValue,
+ useReducedMotion,
+ type ValueAnimationTransition,
+} from "framer-motion";
+import { type ReactNode, useLayoutEffect, useRef } from "react";
+import { SPRING_DISCLOSE } from "@/lib/motion";
+import { cn } from "@/lib/utils";
+
+export type AutoHeightProps = {
+ children: ReactNode;
+ transition?: ValueAnimationTransition<number>;
+ className?: string;
+ /** Classes for the measured box, e.g. padding, so focus rings sit inside the clip. */
+ contentClassName?: string;
+};
+
+/**
+ * Springs its height when its content grows or shrinks, so swapping or disclosing content morphs the
+ * box in place instead of jumping the layout below it. At rest the height is auto; it is pinned in px
+ * only while a spring runs, and under reduced motion it simply follows the content.
+ *
+ * The spring drives a standalone motion value that writes the style itself instead of a motion.div's
+ * animate prop: a paint dropped by the render loop can then never leave content clipped.
+ */
+export function AutoHeight({ children, transition = SPRING_DISCLOSE, className, contentClassName }: AutoHeightProps) {
+ const boxRef = useRef<HTMLDivElement>(null);
+ const contentRef = useRef<HTMLDivElement>(null);
+ const reduceMotion = useReducedMotion();
+ const options = useRef({ transition, reduceMotion });
+
+ useLayoutEffect(() => {
+ options.current = { transition, reduceMotion };
+ });
+
+ useLayoutEffect(() => {
+ const box = boxRef.current;
+ const content = contentRef.current;
+ if (!box || !content || typeof ResizeObserver === "undefined") return;
+
+ // The content's height at rest, and the spring (if any) currently carrying the box towards it.
+ let settled = content.offsetHeight;
+ let spring: AnimationPlaybackControls | undefined;
+ const height = motionValue(settled);
+ const unsubscribe = height.on("change", value => {
+ box.style.height = `${value}px`;
+ });
+
+ const sync = () => {
+ const target = content.offsetHeight;
+ if (target === settled) return;
+ const from = spring ? height.get() : settled;
+ spring?.stop();
+ spring = undefined;
+ settled = target;
+
+ if (options.current.reduceMotion) {
+ box.style.height = "";
+ return;
+ }
+ // Pinned directly: jump() stays silent when the value hasn't moved, which it hasn't at rest.
+ box.style.height = `${from}px`;
+ height.jump(from);
+ spring = animate(height, target, {
+ ...options.current.transition,
+ onComplete: () => {
+ box.style.height = "";
+ spring = undefined;
+ },
+ });
+ };
+
+ // React commits a swap or a disclosure as one batch of DOM mutations. Checking in the microtask
+ // right after that commit pins the old height before anything can lay out or paint the new one.
+ const mutations = new MutationObserver(sync);
+ mutations.observe(content, { childList: true, subtree: true, characterData: true });
+ // Everything else that resizes the content (fonts, images, reflow) is caught before paint here.
+ const resizes = new ResizeObserver(sync);
+ resizes.observe(content);
+
+ return () => {
+ mutations.disconnect();
+ resizes.disconnect();
+ spring?.stop();
+ unsubscribe();
+ };
+ }, []);
+
+ return (
+ <div ref={boxRef} className={cn("overflow-hidden", className)}>
+ <div ref={contentRef} className={contentClassName}>
+ {children}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/interior/spark-burst.test.ts b/client/src/components/interior/spark-burst.test.ts
new file mode 100644
index 000000000..a93de8e76
--- /dev/null
+++ b/client/src/components/interior/spark-burst.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import { sparkFlights } from "./spark-burst";
+
+// The first-pageview card's frog: a 32×21 glyph, with the burst landing inside the card.
+const inner = { x: 18, y: 13 };
+const outer = { x: 42, y: 36 };
+const flights = sparkFlights(inner, outer);
+
+describe("sparkFlights", () => {
+ it("launches eight 4–6px sparks, staggered by at most 60ms", () => {
+ expect(flights).toHaveLength(8);
+ for (const flight of flights) {
+ expect(flight.size).toBeGreaterThanOrEqual(4);
+ expect(flight.size).toBeLessThanOrEqual(6);
+ expect(flight.delay).toBeLessThanOrEqual(0.06);
+ }
+ });
+
+ it("starts around the glyph rather than on it, and travels outward 16–28px", () => {
+ for (const { from, to } of flights) {
+ // On the inner ellipse, which clears a 32×21 glyph's edges.
+ expect((from.x / inner.x) ** 2 + (from.y / inner.y) ** 2).toBeCloseTo(1, 1);
+ expect(Math.hypot(to.x, to.y)).toBeGreaterThan(Math.hypot(from.x, from.y));
+ const travel = Math.hypot(to.x - from.x, to.y - from.y);
+ expect(travel).toBeGreaterThanOrEqual(16);
+ expect(travel).toBeLessThanOrEqual(28);
+ }
+ });
+
+ it("lands inside the outer ellipse, so a clipping parent sized to it never cuts a spark off", () => {
+ for (const { to } of flights) {
+ expect((to.x / outer.x) ** 2 + (to.y / outer.y) ** 2).toBeLessThanOrEqual(1.001);
+ }
+ });
+
+ it("is the same burst every time", () => {
+ expect(sparkFlights(inner, outer)).toEqual(flights);
+ });
+});
diff --git a/client/src/components/interior/spark-burst.tsx b/client/src/components/interior/spark-burst.tsx
new file mode 100644
index 000000000..0fbc3e29b
--- /dev/null
+++ b/client/src/components/interior/spark-burst.tsx
@@ -0,0 +1,90 @@
+// Adapted from interior.dev "Like Burst" (MIT). See ./THIRD_PARTY_LICENSES.md
+"use client";
+
+import { motion } from "framer-motion";
+import { EASE_OUT } from "@/lib/motion";
+import { cn } from "@/lib/utils";
+
+const round = (value: number) => Math.round(value * 10) / 10;
+
+// Fixed jitter per spark, so the burst looks hand-placed and is identical every time: nothing is
+// random at render. It nudges each spark's angle, reach, size and start.
+const JITTER = [0.55, 0.1, 0.8, 0.35, 0.95, 0.2, 0.65, 0.45];
+
+const SPARKS = JITTER.map((jitter, i) => {
+ const angle = (i / JITTER.length) * Math.PI * 2 - Math.PI / 2 + (jitter - 0.5) * 0.5;
+ return {
+ cos: Math.cos(angle),
+ sin: Math.sin(angle),
+ // Outer reach between 80% and 100% of the outer ellipse.
+ reach: 0.8 + jitter * 0.2,
+ size: 4 + Math.round(jitter * 2),
+ delay: Math.round(jitter * 60) / 1000,
+ };
+});
+
+// Alternates the success signal (emerald) with the data hue (periwinkle): the first data point landing.
+const SPARK_TONES = ["bg-emerald-500 dark:bg-emerald-400", "bg-dataviz"];
+
+const DURATION = 0.7;
+// Sparks appear fast, hold full strength for most of the flight and only fade near the end.
+const OPACITY_TIMES = [0, 0.12, 0.6, 1];
+
+type Ellipse = { x: number; y: number };
+
+/** Where each spark starts and lands, in px from the burst's centre, with its size and stagger. */
+export function sparkFlights(inner: Ellipse, outer: Ellipse) {
+ return SPARKS.map(spark => ({
+ from: { x: round(spark.cos * inner.x), y: round(spark.sin * inner.y) },
+ to: { x: round(spark.cos * outer.x * spark.reach), y: round(spark.sin * outer.y * spark.reach) },
+ size: spark.size,
+ delay: spark.delay,
+ }));
+}
+
+export type SparkBurstProps = {
+ /** Half-extents of the glyph the sparks surround, in px: they start just outside it, not on it. */
+ inner?: Ellipse;
+ /** Half-extents of where they land, in px. Keep it inside any clipping parent. */
+ outer?: Ellipse;
+ /** Seconds before the sparks leave, e.g. to let the glyph they surround land first. */
+ delay?: number;
+ className?: string;
+};
+
+/**
+ * One small burst of eight 4–6px sparks from around the centre of its positioned parent. It plays once
+ * on mount (remount it with a new `key` to play again) and is hidden entirely under
+ * prefers-reduced-motion, where the transforms would be dropped and only a flash of dots would remain.
+ */
+export function SparkBurst({
+ inner = { x: 12, y: 12 },
+ outer = { x: 36, y: 36 },
+ delay = 0,
+ className,
+}: SparkBurstProps) {
+ return (
+ <span
+ aria-hidden="true"
+ className={cn("pointer-events-none absolute left-1/2 top-1/2 block size-0 motion-reduce:hidden", className)}
+ >
+ {sparkFlights(inner, outer).map(({ from, to, size, delay: stagger }, index) => {
+ const start = delay + stagger;
+ return (
+ <motion.span
+ key={index}
+ className={cn("absolute block rounded-[1px]", SPARK_TONES[index % SPARK_TONES.length])}
+ style={{ width: size, height: size, marginLeft: -size / 2, marginTop: -size / 2 }}
+ initial={{ x: from.x, y: from.y, opacity: 0, scale: 0.8 }}
+ animate={{ x: to.x, y: to.y, opacity: [0, 1, 1, 0], scale: [0.8, 1, 1, 0.7] }}
+ transition={{
+ default: { duration: DURATION, delay: start, ease: EASE_OUT },
+ opacity: { duration: DURATION, delay: start, times: OPACITY_TIMES, ease: "linear" },
+ scale: { duration: DURATION, delay: start, times: OPACITY_TIMES, ease: "linear" },
+ }}
+ />
+ );
+ })}
+ </span>
+ );
+}
diff --git a/client/src/components/interior/task-steps.test.tsx b/client/src/components/interior/task-steps.test.tsx
new file mode 100644
index 000000000..6140232ff
--- /dev/null
+++ b/client/src/components/interior/task-steps.test.tsx
@@ -0,0 +1,89 @@
+import { act, cleanup, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TaskSteps, taskStepStatus } from "./task-steps";
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, unknown>) =>
+ message.replace(/\{(\w+)(?:, \w+)?\}/g, (_, key: string) => String(values?.[key] ?? "")),
+}));
+
+const steps = [
+ { id: "a", label: "Install" },
+ { id: "b", label: "Receive", meta: "from Germany" },
+ { id: "c", label: "Fill in" },
+];
+
+const liveRegions = (container: HTMLElement) => container.querySelectorAll('[role="status"], [aria-live]');
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("taskStepStatus", () => {
+ it("marks earlier steps done, the current one active or failed, and later ones pending", () => {
+ expect([0, 1, 2].map(i => taskStepStatus(i, 1, false, 3))).toEqual(["done", "active", "pending"]);
+ expect([0, 1, 2].map(i => taskStepStatus(i, 1, true, 3))).toEqual(["done", "error", "pending"]);
+ expect([0, 1, 2].map(i => taskStepStatus(i, 3, false, 3))).toEqual(["done", "done", "done"]);
+ });
+});
+
+describe("TaskSteps", () => {
+ it("exposes each step's status to assistive tech and marks the current step", () => {
+ render(<TaskSteps steps={steps} current={1} label="Setup" />);
+
+ const items = screen.getAllByRole("listitem");
+ expect(screen.getByRole("list", { name: "Setup" })).toBeTruthy();
+ expect(items[0].textContent).toBe("Done: Install");
+ expect(items[1].textContent).toMatch(/^In progress: Receive/);
+ expect(items[2].textContent).toBe("Not started: Fill in");
+ expect(items[1].getAttribute("aria-current")).toBe("step");
+ });
+
+ it("keeps a step's detail hidden until the step is done", () => {
+ const { rerender } = render(<TaskSteps steps={steps} current={1} />);
+ expect(screen.getByText("from Germany").getAttribute("aria-hidden")).toBe("true");
+
+ rerender(<TaskSteps steps={steps} current={2} />);
+ expect(screen.getByText("from Germany").getAttribute("aria-hidden")).toBe("false");
+ });
+
+ it("holds the spinner still under reduced motion", () => {
+ const { container } = render(<TaskSteps steps={steps} current={1} />);
+
+ const spinner = container.querySelector("li[aria-current] svg")!;
+ expect(spinner.getAttribute("class")).toContain("motion-safe:animate-spin");
+ });
+
+ it("announces progress after it settles, through a single live region", () => {
+ const { container, rerender } = render(<TaskSteps steps={steps} current={1} />);
+ expect(liveRegions(container)).toHaveLength(1);
+
+ act(() => vi.advanceTimersByTime(500));
+ expect(screen.getByRole("status").textContent).toBe("Receive, step 2 of 3");
+
+ rerender(<TaskSteps steps={steps} current={3} />);
+ act(() => vi.advanceTimersByTime(500));
+ expect(screen.getByRole("status").textContent).toBe("All 3 steps complete");
+ expect(liveRegions(container)).toHaveLength(1);
+ });
+
+ it("announces a failure", () => {
+ render(<TaskSteps steps={steps} current={2} failed />);
+
+ act(() => vi.advanceTimersByTime(500));
+ expect(screen.getByRole("status").textContent).toBe("Failed at Fill in");
+ expect(screen.getAllByRole("listitem")[2].textContent).toBe("Failed: Fill in");
+ });
+
+ it("stays silent when the caller owns the announcement", () => {
+ const { container } = render(<TaskSteps steps={steps} current={3} announce={false} />);
+
+ act(() => vi.advanceTimersByTime(500));
+ expect(liveRegions(container)).toHaveLength(0);
+ });
+});
diff --git a/client/src/components/interior/task-steps.tsx b/client/src/components/interior/task-steps.tsx
new file mode 100644
index 000000000..23169b99f
--- /dev/null
+++ b/client/src/components/interior/task-steps.tsx
@@ -0,0 +1,210 @@
+// Adapted from interior.dev "Task Steps" (MIT). See ./THIRD_PARTY_LICENSES.md
+"use client";
+
+import { AnimatePresence, motion } from "framer-motion";
+import { Check, X } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useEffect, useState } from "react";
+import { INSTANT, SPRING_CELL, SPRING_POP } from "@/lib/motion";
+import { cn } from "@/lib/utils";
+
+export type TaskStep = {
+ id: string;
+ label: string;
+ /** Secondary detail, revealed once the step is done. */
+ meta?: string;
+};
+
+export type TaskStepStatus = "pending" | "active" | "done" | "error";
+
+export type UseTaskStepsOptions = {
+ steps: TaskStep[];
+ /** Index of the step in progress: earlier steps are done, `steps.length` means all of them are. */
+ current: number;
+ failed?: boolean;
+};
+
+// Gap between the checks of steps that are already done when the list first renders with `appear`.
+const APPEAR_STAGGER = 0.08;
+// Upstream waits this long before speaking, so a burst of quick steps is announced once, not per step.
+const ANNOUNCE_DELAY_MS = 500;
+
+export function taskStepStatus(index: number, current: number, failed: boolean, stepCount: number): TaskStepStatus {
+ if (index < current) return "done";
+ if (index === current && failed) return "error";
+ if (index === current && current < stepCount) return "active";
+ return "pending";
+}
+
+export function useTaskSteps({ steps, current, failed = false }: UseTaskStepsOptions) {
+ const t = useExtracted();
+ const complete = !failed && current >= steps.length;
+ const rows = steps.map((step, index) => ({ ...step, status: taskStepStatus(index, current, failed, steps.length) }));
+ const active = rows.find(row => row.status === "active");
+
+ const sentence = failed
+ ? t("Failed at {step}", { step: steps[Math.min(current, steps.length - 1)]?.label ?? "" })
+ : complete
+ ? t("All {count, number} steps complete", { count: steps.length })
+ : active
+ ? t("{step}, step {current, number} of {total, number}", {
+ step: active.label,
+ current: current + 1,
+ total: steps.length,
+ })
+ : "";
+
+ return { rows, complete, failed, sentence };
+}
+
+const LABEL_TONE: Record<TaskStepStatus, string> = {
+ done: "text-neutral-700 dark:text-neutral-200",
+ active: "font-medium text-neutral-900 dark:text-neutral-50",
+ pending: "text-neutral-600 dark:text-neutral-400",
+ error: "font-medium text-red-600 dark:text-red-400",
+};
+
+function StepIcon({ status, delay }: { status: TaskStepStatus; delay: number }) {
+ const cell = "col-start-1 row-start-1";
+
+ if (status === "done" || status === "error") {
+ const done = status === "done";
+ return (
+ <motion.span
+ className={cn(
+ cell,
+ "grid size-4 place-items-center rounded-md",
+ done
+ ? "bg-emerald-500/15 text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400"
+ : "bg-red-500/15 text-red-600 dark:bg-red-400/15 dark:text-red-400"
+ )}
+ initial={{ opacity: 0, scale: 0.4 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, transition: INSTANT }}
+ transition={{ ...SPRING_POP, delay }}
+ >
+ {done ? <Check className="size-3" strokeWidth={3} /> : <X className="size-3" strokeWidth={3} />}
+ </motion.span>
+ );
+ }
+
+ if (status === "active") {
+ return (
+ <motion.span
+ className={cn(cell, "text-neutral-500 dark:text-neutral-400")}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0, transition: INSTANT }}
+ transition={SPRING_CELL}
+ >
+ {/* Upstream spun this with a JS animation that ignored reduced motion; a CSS spin gated on
+ motion-safe simply stays still for those users. */}
+ <svg viewBox="0 0 16 16" className="size-3 motion-safe:animate-spin">
+ <circle cx="8" cy="8" r="6" fill="none" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2" />
+ <path d="M8 2 a6 6 0 0 1 6 6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
+ </svg>
+ </motion.span>
+ );
+ }
+
+ return (
+ <motion.span
+ className={cn(cell, "size-[5px] rounded-[1px] bg-neutral-300 dark:bg-neutral-600")}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0, transition: INSTANT }}
+ transition={INSTANT}
+ />
+ );
+}
+
+export type TaskStepsProps = UseTaskStepsOptions & {
+ /** Accessible name of the list. */
+ label?: string;
+ /** Pop in the checks of steps that are already done on the first render, staggered. */
+ appear?: boolean;
+ /** Seconds before that first stagger starts, e.g. to wait for the surrounding card to fade in. */
+ appearDelay?: number;
+ /** Speak progress in a polite live region. Turn off when the caller announces the outcome itself. */
+ announce?: boolean;
+ className?: string;
+};
+
+export function TaskSteps({
+ steps,
+ current,
+ failed = false,
+ label,
+ appear = false,
+ appearDelay = 0,
+ announce = true,
+ className,
+}: TaskStepsProps) {
+ const t = useExtracted();
+ const { rows, sentence } = useTaskSteps({ steps, current, failed });
+ // Steps done at first render are the ones that stagger in; a step that finishes later pops at once.
+ const [doneOnMount] = useState(() => new Set(rows.filter(row => row.status === "done").map(row => row.id)));
+
+ // One live region, always mounted, fed after a short settle. Upstream flipped a second region's
+ // aria-live on in the same update as its text, so completion was announced twice.
+ const [spoken, setSpoken] = useState("");
+ useEffect(() => {
+ if (!announce || !sentence) return;
+ const timeout = window.setTimeout(() => setSpoken(sentence), ANNOUNCE_DELAY_MS);
+ return () => window.clearTimeout(timeout);
+ }, [announce, sentence]);
+
+ const statusText: Record<TaskStepStatus, string> = {
+ done: t("Done:"),
+ active: t("In progress:"),
+ pending: t("Not started:"),
+ error: t("Failed:"),
+ };
+
+ return (
+ <div className={cn("w-full", className)}>
+ <ol aria-label={label ?? t("Progress")} className="flex flex-col">
+ {rows.map((row, index) => (
+ // Hanging indent: when the detail doesn't fit beside the label it wraps under it, instead of
+ // squeezing the label into an ellipsis on narrow screens.
+ <li
+ key={row.id}
+ aria-current={row.status === "active" ? "step" : undefined}
+ className="relative flex flex-wrap items-baseline gap-x-2 py-1 pl-6"
+ >
+ <span aria-hidden="true" className="absolute left-0 top-1.5 grid size-4 place-items-center">
+ <AnimatePresence initial={appear}>
+ <StepIcon
+ key={row.status}
+ status={row.status}
+ delay={appear && doneOnMount.has(row.id) ? appearDelay + index * APPEAR_STAGGER : 0}
+ />
+ </AnimatePresence>
+ </span>
+ <span
+ className={cn("min-w-0 max-w-full truncate text-sm leading-5 transition-colors", LABEL_TONE[row.status])}
+ >
+ <span className="sr-only">{statusText[row.status]} </span>
+ {row.label}
+ </span>
+ {/* Always mounted, so a detail that turns up after the step is done still fades in. */}
+ <span
+ aria-hidden={row.status !== "done" || !row.meta}
+ className={cn(
+ "min-w-0 max-w-full truncate text-xs leading-4 text-neutral-600 transition-opacity duration-200 dark:text-neutral-400",
+ row.status === "done" && row.meta ? "opacity-100" : "opacity-0"
+ )}
+ >
+ {row.meta}
+ </span>
+ </li>
+ ))}
+ </ol>
+ {announce ? (
+ <span role="status" className="sr-only">
+ {spoken}
+ </span>
+ ) : null}
+ </div>
+ );
+}