Skip to content

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

feat(dashboard): flash numbers that change on refresh, and show overview errors (#1257)

Goldflag3c6c75222204
diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
index 6db17eec5..f7eced6d5 100644
--- a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
@@ -1,8 +1,9 @@
-import NumberFlow from "@number-flow/react";
import { useIntersectionObserver } from "@uidotdev/usehooks";
import { Rewind } from "lucide-react";
import { useExtracted } from "next-intl";
import { useEffect, useMemo } from "react";
+import { FlashNumber } from "@/components/interior/value-flash";
+import { useStore } from "@/lib/store";
import { useGetLiveUserCount } from "../../../../api/analytics/hooks/useGetLiveUserCount";
import { useGetSessionsInfinite } from "../../../../api/analytics/hooks/useGetUserSessions";
import { NothingFound } from "../../../../components/NothingFound";
@@ -15,7 +16,8 @@ import { ScrollArea } from "../../../../components/ui/scroll-area";
export function LiveUserCount() {
const t = useExtracted();
- const { data } = useGetLiveUserCount(5);
+ const site = useStore(state => state.site);
+ const { data, isFetching } = useGetLiveUserCount(5);
const {
data: sessionsData,
@@ -63,8 +65,14 @@ export function LiveUserCount() {
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
<span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>
</span>
- <span className="text-sm text-neutral-700 dark:text-neutral-200 ml-1 font-medium">
- {<NumberFlow value={data?.count ?? 0} />}
+ <span className="text-sm text-neutral-700 dark:text-neutral-200 ml-1 font-medium tabular-nums">
+ {data ? (
+ // Flashes when a poll moves the count; never on first paint or when the site changes.
+ <FlashNumber value={data.count} resetKey={site} fetching={isFetching} />
+ ) : (
+ // Not "0": nothing is known yet (loading, or the request failed).
+ <span className="text-neutral-400 dark:text-neutral-500">–</span>
+ )}
</span>
</div>
</Button>
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 57f77d395..0b75d1ac5 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -2,7 +2,7 @@
import { Card, CardContent, CardLoader } from "@/components/ui/card";
import { DateTime } from "luxon";
import { Tilt_Warp } from "next/font/google";
-import { MessageSquarePlus } from "lucide-react";
+import { AlertCircle, MessageSquarePlus } from "lucide-react";
import { useExtracted } from "next-intl";
import Link from "next/link";
import { useState } from "react";
@@ -11,6 +11,7 @@ import { Button } from "@/components/ui/button";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { BucketSelection } from "../../../../../components/BucketSelection";
+import { ErrorState } from "../../../../../components/ErrorState";
import { RybbitTextLogo } from "../../../../../components/RybbitLogo";
import { useWhiteLabel } from "../../../../../hooks/useIsWhiteLabel";
import { authClient } from "../../../../../lib/auth";
@@ -40,18 +41,25 @@ export function MainSection() {
const getSelectedStatLabel = () => {
switch (selectedStat) {
- case "pageviews": return t("Pageviews");
- case "sessions": return t("Sessions");
- case "pages_per_session": return t("Pages per Session");
- case "bounce_rate": return t("Bounce Rate");
- case "session_duration": return t("Session Duration");
- case "users": return t("Users");
- default: return selectedStat;
+ case "pageviews":
+ return t("Pageviews");
+ case "sessions":
+ return t("Sessions");
+ case "pages_per_session":
+ return t("Pages per Session");
+ case "bounce_rate":
+ return t("Bounce Rate");
+ case "session_duration":
+ return t("Session Duration");
+ case "users":
+ return t("Users");
+ default:
+ return selectedStat;
}
};
// Current period data
- const { data, isFetching, isPlaceholderData, error } = useGetOverviewBucketed({
+ const { data, isFetching, isPlaceholderData, error, refetch } = useGetOverviewBucketed({
site,
bucket,
});
@@ -61,12 +69,18 @@ export function MainSection() {
data: previousData,
isFetching: isPreviousFetching,
error: previousError,
+ refetch: refetchPrevious,
} = useGetOverviewBucketed({
periodTime: "previous",
site,
bucket,
});
+ // A failed load renders as an error, not as an empty chart that reads as zero traffic. A background
+ // refetch that fails keeps the data it already had, so these only fire when there's nothing to show.
+ const chartFailed = !!error && !data;
+ const comparisonFailed = !chartFailed && !!previousError && !previousData && time.mode !== "all-time";
+
const { isFetching: isOverviewFetching } = useGetOverview({ site });
const { isFetching: isOverviewFetchingPrevious } = useGetOverview({
site,
@@ -111,10 +125,7 @@ export function MainSection() {
<div className="flex items-center justify-between px-2 md:px-0">
<div className="flex items-center space-x-4">
{!isWhiteLabel && (
- <Link
- href={session.data ? "/" : "https://rybbit.com"}
- className="opacity-75"
- >
+ <Link href={session.data ? "/" : "https://rybbit.com"} className="opacity-75">
<RybbitTextLogo width={80} />
</Link>
)}
@@ -130,16 +141,37 @@ export function MainSection() {
<BucketSelection />
</div>
</div>
- <div className="h-[200px] md:h-[290px]">
- <Chart
- data={data}
- max={maxOfDataAndPreviousData}
- previousData={time.mode === "all-time" ? undefined : previousData}
- chartXMax={chartXMax}
- annotations={annotations}
- onCreateAnnotation={canAnnotate ? date => setAnnotationEditor({ mode: "create", date }) : undefined}
- onEditAnnotation={annotation => setAnnotationEditor({ mode: "edit", annotation })}
- />
+ {comparisonFailed && (
+ <div className="flex items-center justify-center gap-2 px-2 pt-2 text-xs text-neutral-500 dark:text-neutral-400">
+ <AlertCircle className="size-3.5 shrink-0 text-amber-400" aria-hidden="true" />
+ <span>{t("Failed to load comparison data")}</span>
+ <Button variant="ghost" size="xs" onClick={() => void refetchPrevious()}>
+ {t("Try Again")}
+ </Button>
+ </div>
+ )}
+ {/* The error takes the chart's height but may grow: a long message must not spill out of the card. */}
+ <div className={chartFailed ? "flex min-h-[200px] flex-col md:min-h-[290px]" : "h-[200px] md:h-[290px]"}>
+ {chartFailed ? (
+ <ErrorState
+ title={t("Failed to load chart data")}
+ message={error?.message ?? ""}
+ refetch={() => {
+ void refetch();
+ if (previousError) void refetchPrevious();
+ }}
+ />
+ ) : (
+ <Chart
+ data={data}
+ max={maxOfDataAndPreviousData}
+ previousData={time.mode === "all-time" ? undefined : previousData}
+ chartXMax={chartXMax}
+ annotations={annotations}
+ onCreateAnnotation={canAnnotate ? date => setAnnotationEditor({ mode: "create", date }) : undefined}
+ onEditAnnotation={annotation => setAnnotationEditor({ mode: "edit", annotation })}
+ />
+ )}
</div>
</CardContent>
</Card>
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.test.tsx b/client/src/app/[site]/main/components/MainSection/Overview.test.tsx
new file mode 100644
index 000000000..86f52e158
--- /dev/null
+++ b/client/src/app/[site]/main/components/MainSection/Overview.test.tsx
@@ -0,0 +1,156 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { useStore } from "@/lib/store";
+import { Overview } from "./Overview";
+
+// Drives the real query layer (keys, placeholder data, refetches) with only the network mocked, so the
+// flash rules are checked against React Query's actual flag sequence.
+
+const BASE = {
+ users: 100,
+ sessions: 150,
+ pageviews: 400,
+ pages_per_session: 2.7,
+ bounce_rate: 41.2,
+ session_duration: 95,
+};
+
+const api = vi.hoisted(() => ({ overview: {} as Record<string, number> | Error }));
+
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("@number-flow/react", () => ({ default: ({ value }: { value: number }) => <span>{value}</span> }));
+vi.mock("./SparklinesChart", () => ({ SparklinesChart: () => null }));
+vi.mock("@/api/utils", async importOriginal => ({
+ ...(await importOriginal<typeof import("@/api/utils")>()),
+ authedFetch: vi.fn(async (url: string) => {
+ if (url.endsWith("/overview/time-series")) return { data: [] };
+ if (api.overview instanceof Error) throw api.overview;
+ return { data: { ...api.overview } };
+ }),
+}));
+
+function renderOverview() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <TooltipProvider>
+ <Overview />
+ </TooltipProvider>
+ </QueryClientProvider>
+ );
+ return client;
+}
+
+// The ValueFlash wrapper of a tile, found from the tile's title.
+const mark = (title: string) => screen.getByText(title).nextElementSibling!.firstElementChild as HTMLElement;
+const flashing = (title: string) => /text-(accent|red)-600/.test(mark(title).className);
+
+beforeEach(() => {
+ api.overview = { ...BASE };
+ useStore.setState({
+ site: "1",
+ time: { mode: "day", day: "2026-09-28" },
+ previousTime: null,
+ bucket: "hour",
+ filters: [],
+ selectedStat: "users",
+ timezone: "UTC",
+ });
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("Overview stat tiles", () => {
+ it("don't flash on first paint, and flash only the number a background refetch moved", async () => {
+ const client = renderOverview();
+ await screen.findByText("100");
+ expect(flashing("Unique Users")).toBe(false);
+
+ api.overview = { ...BASE, users: 120 };
+ await act(() => client.refetchQueries());
+ await screen.findByText("120");
+
+ expect(mark("Unique Users").className).toContain("text-accent-600");
+ expect(mark("Unique Users").querySelector("[data-slot='value-flash-glyph'][aria-hidden='true']")).not.toBeNull();
+ expect(flashing("Sessions")).toBe(false);
+ });
+
+ it("tint a rising bounce rate red", async () => {
+ const client = renderOverview();
+ await screen.findByText("100");
+
+ api.overview = { ...BASE, bounce_rate: 55 };
+ await act(() => client.refetchQueries());
+ await screen.findByText("55");
+
+ expect(mark("Bounce Rate").className).toContain("text-red-600");
+ });
+
+ it("don't flash when the user asks a different question (date range)", async () => {
+ renderOverview();
+ await screen.findByText("100");
+
+ api.overview = { ...BASE, users: 500 };
+ act(() => useStore.setState({ time: { mode: "day", day: "2026-09-27" } }));
+ await screen.findByText("500");
+
+ expect(flashing("Unique Users")).toBe(false);
+ });
+
+ it("don't flash when a filter changes", async () => {
+ renderOverview();
+ await screen.findByText("100");
+
+ api.overview = { ...BASE, users: 40 };
+ act(() => useStore.setState({ filters: [{ parameter: "browser", type: "equals", value: ["Firefox"] }] }));
+ await screen.findByText("40");
+
+ expect(flashing("Unique Users")).toBe(false);
+ });
+});
+
+describe("Overview on a new site's first pageview", () => {
+ const TILES = ["Unique Users", "Sessions", "Pageviews", "Pages per Session", "Bounce Rate", "Session Duration"];
+ const EMPTY = { users: 0, sessions: 0, pageviews: 0, pages_per_session: 0, bounce_rate: 0, session_duration: 0 };
+ const FIRST = { users: 1, sessions: 1, pageviews: 1, pages_per_session: 1, bounce_rate: 100, session_duration: 0 };
+
+ it("fills the tiles without flashing, then flashes later changes as usual", async () => {
+ api.overview = { ...EMPTY };
+ const client = renderOverview();
+ await screen.findAllByText("0");
+
+ // The arrival: the first-pageview card invalidates the site's queries, refetching this same one.
+ api.overview = { ...FIRST };
+ await act(() => client.invalidateQueries());
+ await screen.findByText("100");
+ for (const title of TILES) expect(flashing(title)).toBe(false);
+
+ // From then on a background refetch that moves a number flashes it, bounce rate included.
+ api.overview = { ...FIRST, users: 2, sessions: 2, pageviews: 3, pages_per_session: 1.5, bounce_rate: 50 };
+ await act(() => client.refetchQueries());
+ await screen.findByText("50");
+ expect(mark("Unique Users").className).toContain("text-accent-600");
+ expect(mark("Bounce Rate").className).toContain("text-accent-600");
+ });
+});
+
+describe("Overview load failure", () => {
+ it("says so instead of rendering a row of zeros, and recovers on retry", async () => {
+ api.overview = new Error("Timeout exceeded: elapsed 30 seconds");
+ renderOverview();
+
+ await screen.findByText("Failed to load stats");
+ expect(screen.getByText("Timeout exceeded: elapsed 30 seconds")).toBeTruthy();
+ expect(screen.queryByText("Unique Users")).toBeNull();
+ expect(screen.queryByText("0")).toBeNull();
+
+ api.overview = { ...BASE };
+ fireEvent.click(screen.getByRole("button", { name: /Try Again/ }));
+ await screen.findByText("100");
+ expect(flashing("Unique Users")).toBe(false);
+ });
+});
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index e3fc9eeb0..d03a25fa8 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -1,17 +1,27 @@
"use client";
+import { ValueFlash, type ValueFlashProps } from "@/components/interior/value-flash";
+import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn, formatSecondsAsMinutesAndSeconds } from "@/lib/utils";
import NumberFlow from "@number-flow/react";
-import { ArrowDown, ArrowUp, ChevronDown, ChevronUp } from "lucide-react";
+import { AlertCircle, ArrowDown, ArrowUp, ChevronDown, ChevronUp, RefreshCcw } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
-import { StatType, useComparisonEnabled, useStore } from "../../../../../lib/store";
+import { StatType, useComparisonEnabled, useStore, useTimezone } from "../../../../../lib/store";
import { SparklinesChart } from "./SparklinesChart";
+const COMPACT = { notation: "compact" } as const;
+const STANDARD = { notation: "standard" } as const;
+// The tile's text as NumberFlow renders it (same default locale), so a change that rounding hides
+// ("12K" → "12K") doesn't flash.
+const compactNumber = new Intl.NumberFormat(undefined, COMPACT);
+
+type FlashInputs = Pick<ValueFlashProps, "resetKey" | "ready" | "fetching" | "empty">;
+
export const ChangePercentage = ({
current,
previous,
@@ -62,19 +72,23 @@ const Stat = ({
decimals,
postfix,
reverseColor,
+ flash,
}: {
title: string;
id: StatType;
value: number;
- previous: number;
+ // Undefined when there is no comparison to draw: turned off, or the previous period failed to load.
+ previous: number | undefined;
valueFormatter?: (value: number) => string;
isLoading: boolean;
decimals?: number;
postfix?: string;
reverseColor?: boolean;
+ flash: FlashInputs;
}) => {
const { selectedStat, setSelectedStat, site, bucket, time } = useStore();
const [isHovering, setIsHovering] = useState(false);
+ const displayValue = decimals ? Number(value.toFixed(decimals)) : value;
// Consolidated bucketed data for sparklines - automatically handles both modes
const { data } = useGetOverviewBucketed({
@@ -121,32 +135,26 @@ const Stat = ({
) : (
<>
{valueFormatter ? (
- valueFormatter(value)
+ <ValueFlash value={value} format={valueFormatter} invert={reverseColor} {...flash}>
+ {valueFormatter(value)}
+ </ValueFlash>
) : (
- <span>
- {
- <Tooltip>
- <TooltipTrigger>
- <NumberFlow
-
- value={decimals ? Number(value.toFixed(decimals)) : value}
- format={{ notation: "compact" }}
- />
- </TooltipTrigger>
- <TooltipContent>
- <NumberFlow
-
- value={decimals ? Number(value.toFixed(decimals)) : value}
- format={{ notation: "standard" }}
- />
- {postfix && <span>{postfix}</span>}
- </TooltipContent>
- </Tooltip>
- }
+ <ValueFlash value={displayValue} format={compactNumber.format} invert={reverseColor} {...flash}>
+ <Tooltip>
+ <TooltipTrigger>
+ <NumberFlow value={displayValue} format={COMPACT} />
+ </TooltipTrigger>
+ <TooltipContent>
+ <NumberFlow value={displayValue} format={STANDARD} />
+ {postfix && <span>{postfix}</span>}
+ </TooltipContent>
+ </Tooltip>
{postfix && <span>{postfix}</span>}
- </span>
+ </ValueFlash>
+ )}
+ {previous !== undefined && (
+ <ChangePercentage current={value} previous={previous} reverseColor={reverseColor} />
)}
- <ChangePercentage current={value} previous={previous} reverseColor={reverseColor} />
</>
)}
</div>
@@ -159,7 +167,8 @@ const Stat = ({
};
export function Overview() {
- const { site } = useStore();
+ const { site, time, filters, bucket } = useStore();
+ const timeZone = useTimezone();
const t = useExtracted();
// Current period - automatically handles both regular time-based and past-minutes queries
@@ -167,7 +176,9 @@ export function Overview() {
data: overviewData,
isFetching: isOverviewFetching,
isLoading: isOverviewLoading,
+ isPlaceholderData: isOverviewPlaceholder,
error: overviewError,
+ refetch: refetchOverview,
} = useGetOverview({
site,
});
@@ -178,63 +189,108 @@ export function Overview() {
periodTime: "previous",
});
+ // A failed load is not zero traffic: say so rather than render a row of zeros.
+ if (overviewError && !overviewData) {
+ return (
+ <OverviewError
+ message={overviewError.message || t("An error occurred while fetching data")}
+ onRetry={() => void refetchOverview()}
+ />
+ );
+ }
+
const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
- const currentUsers = overviewData?.users ?? 0;
- const previousUsers = overviewDataPrevious?.users ?? 0;
+ // Tiles flash only when a background refetch of the same question moves a number: never on first
+ // paint, never on a site/range/filter/bucket change, never while the previous range's numbers stand in.
+ const flash: FlashInputs = {
+ resetKey: JSON.stringify([site, time, filters, bucket, timeZone]),
+ ready: overviewData !== undefined && !isOverviewPlaceholder,
+ fetching: isOverviewFetching,
+ // No sessions means every tile reads 0 for want of data. The first data after that (a new site's
+ // first pageview, which refetches this same query) is a first paint, not a rise.
+ empty: !overviewData?.sessions,
+ };
+ const currentUsers = overviewData?.users ?? 0;
const currentSessions = overviewData?.sessions ?? 0;
- const previousSessions = overviewDataPrevious?.sessions ?? 0;
-
const currentPageviews = overviewData?.pageviews ?? 0;
- const previousPageviews = overviewDataPrevious?.pageviews ?? 0;
-
const currentPagesPerSession = overviewData?.pages_per_session ?? 0;
- const previousPagesPerSession = overviewDataPrevious?.pages_per_session ?? 0;
-
const currentBounceRate = overviewData?.bounce_rate ?? 0;
- const previousBounceRate = overviewDataPrevious?.bounce_rate ?? 0;
-
const currentSessionDuration = overviewData?.session_duration ?? 0;
- const previousSessionDuration = overviewDataPrevious?.session_duration ?? 0;
return (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-0 items-center">
- <Stat title={t("Unique Users")} id="users" value={currentUsers} previous={previousUsers} isLoading={isLoading} />
- <Stat title={t("Sessions")} id="sessions" value={currentSessions} previous={previousSessions} isLoading={isLoading} />
+ <Stat
+ title={t("Unique Users")}
+ id="users"
+ value={currentUsers}
+ previous={overviewDataPrevious?.users}
+ isLoading={isLoading}
+ flash={flash}
+ />
+ <Stat
+ title={t("Sessions")}
+ id="sessions"
+ value={currentSessions}
+ previous={overviewDataPrevious?.sessions}
+ isLoading={isLoading}
+ flash={flash}
+ />
<Stat
title={t("Pageviews")}
id="pageviews"
value={currentPageviews}
- previous={previousPageviews}
+ previous={overviewDataPrevious?.pageviews}
isLoading={isLoading}
+ flash={flash}
/>
<Stat
title={t("Pages per Session")}
id="pages_per_session"
value={currentPagesPerSession}
- previous={previousPagesPerSession}
+ previous={overviewDataPrevious?.pages_per_session}
decimals={1}
isLoading={isLoading}
+ flash={flash}
/>
<Stat
title={t("Bounce Rate")}
id="bounce_rate"
value={currentBounceRate}
- previous={previousBounceRate}
+ previous={overviewDataPrevious?.bounce_rate}
isLoading={isLoading}
postfix="%"
decimals={1}
reverseColor={true}
+ flash={flash}
/>
<Stat
title={t("Session Duration")}
id="session_duration"
value={currentSessionDuration}
- previous={previousSessionDuration}
+ previous={overviewDataPrevious?.session_duration}
isLoading={isLoading}
valueFormatter={formatSecondsAsMinutesAndSeconds}
+ flash={flash}
/>
</div>
);
}
+
+// Takes the stat row's place when the current period fails to load; as tall as one row of tiles.
+function OverviewError({ message, onRetry }: { message: string; onRetry: () => void }) {
+ const t = useExtracted();
+
+ return (
+ <div className="flex min-h-[88px] flex-wrap items-center justify-center gap-x-3 gap-y-2 px-4 py-3 text-sm">
+ <AlertCircle className="size-4 shrink-0 text-amber-400" aria-hidden="true" />
+ <span className="font-medium text-neutral-900 dark:text-neutral-100">{t("Failed to load stats")}</span>
+ <span className="text-neutral-500 dark:text-neutral-400">{message}</span>
+ <Button variant="outline" size="sm" onClick={onRetry}>
+ <RefreshCcw />
+ {t("Try Again")}
+ </Button>
+ </div>
+ );
+}
diff --git a/client/src/components/interior/use-value-flash.ts b/client/src/components/interior/use-value-flash.ts
new file mode 100644
index 000000000..0ced6cc60
--- /dev/null
+++ b/client/src/components/interior/use-value-flash.ts
@@ -0,0 +1,152 @@
+// Adapted from interior.dev "Value Flash" (MIT). See ./THIRD_PARTY_LICENSES.md
+"use client";
+
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+
+// Runs before paint in the browser, so the tint lands in the same frame as the new number.
+const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
+
+// Nothing has been seen yet: the first settled value becomes the baseline without a flash.
+const UNSEEN = Symbol("value-flash:unseen");
+
+export type FlashDirection = "up" | "down";
+
+export type UseValueFlashOptions<T> = {
+ /**
+ * Identity of the question the value answers: site, time range, filters, bucket. When it changes,
+ * the next settled value becomes the baseline silently. A number that moved because the user asked
+ * something else is not news. Compared with Object.is, so pass a string, not a fresh object.
+ */
+ resetKey?: unknown;
+ /** False while the value is not real data yet: loading, placeholder data from the previous query, an error. */
+ ready?: boolean;
+ /**
+ * The value has nothing behind it yet: a range with no sessions reads 0 on every tile, and its bounce
+ * rate is 0 only because there is nothing to divide. Entering or leaving this state re-baselines
+ * silently, like a resetKey change: a site's first data is a first paint, not a rise (and a first
+ * visit's 100% bounce rate is not bad news).
+ */
+ empty?: boolean;
+ /**
+ * A request for the value is in flight. After a resetKey change (or on mount) the hook waits for it
+ * to land, so a stale cache being refreshed right after navigation doesn't flash.
+ */
+ fetching?: boolean;
+ /**
+ * Signed size of the change: positive is up, negative is down, 0 means nothing visible changed (for
+ * example 12,345 → 12,351 both rendered as "12K"). Defaults to next - previous for numbers.
+ */
+ compare?: (next: T, previous: T) => number;
+ /** How long the mark holds before it fades, in ms. */
+ hold?: number;
+ /** Minimum time between two flashes, in ms. A faster change moves the baseline without flashing. */
+ cooldown?: number;
+};
+
+export type ValueFlashState = {
+ /** Direction of the latest flash; kept after it ends so the mark can fade out in place. */
+ direction: FlashDirection | null;
+ flashing: boolean;
+ /** Increments once per flash. */
+ changeId: number;
+};
+
+/**
+ * Marks a value that changed while the user was looking at the same question: a background refetch,
+ * a poll. It never flashes on first render, on a resetKey change, into or out of `empty`, or while
+ * `ready` is false, and it flashes at most once per change.
+ */
+export function useValueFlash<T>(
+ value: T,
+ {
+ resetKey,
+ ready = true,
+ fetching = false,
+ empty = false,
+ compare,
+ hold = 900,
+ cooldown = 2000,
+ }: UseValueFlashOptions<T> = {}
+): ValueFlashState {
+ const [state, setState] = useState<ValueFlashState>({ direction: null, flashing: false, changeId: 0 });
+
+ const seen = useRef<{
+ key: unknown;
+ empty: boolean;
+ settling: boolean;
+ baseline: T;
+ lastFlashAt: number;
+ rising: boolean;
+ }>({
+ key: UNSEEN,
+ empty,
+ settling: true,
+ baseline: value,
+ lastFlashAt: Number.NEGATIVE_INFINITY,
+ rising: true,
+ });
+ const measure = useRef(compare);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useIsoLayoutEffect(() => {
+ measure.current = compare;
+ });
+
+ useIsoLayoutEffect(() => {
+ const current = seen.current;
+ // A new question, or the first data for this one (or its data vanishing): nothing to compare with.
+ if (!Object.is(current.key, resetKey) || current.empty !== empty) {
+ current.key = resetKey;
+ current.empty = empty;
+ current.settling = true;
+ }
+ if (!ready) return;
+
+ const previous = current.baseline;
+ current.baseline = value;
+
+ // First answer to a new question: take it as the baseline. Stay in this state until no request
+ // is in flight, so a cached value refreshed right after the change is absorbed too.
+ if (current.settling) {
+ if (!fetching) current.settling = false;
+ return;
+ }
+
+ if (Object.is(previous, value)) return;
+ const delta = measure.current
+ ? measure.current(value, previous)
+ : typeof value === "number" && typeof previous === "number"
+ ? value - previous
+ : 0;
+ if (!delta) return;
+
+ const end = () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ setState(prev => (prev.flashing ? { ...prev, flashing: false } : prev));
+ };
+
+ const now = Date.now();
+ const rising = delta > 0;
+ if (now - current.lastFlashAt < cooldown) {
+ // Throttled: no new flash. If the mark still showing now points the wrong way, drop it early.
+ if (timer.current && rising !== current.rising) end();
+ return;
+ }
+ current.lastFlashAt = now;
+ current.rising = rising;
+
+ setState(prev => ({ direction: rising ? "up" : "down", flashing: true, changeId: prev.changeId + 1 }));
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(end, hold);
+ }, [value, resetKey, ready, fetching, empty, hold, cooldown]);
+
+ useEffect(
+ () => () => {
+ if (timer.current) clearTimeout(timer.current);
+ },
+ []
+ );
+
+ return state;
+}
diff --git a/client/src/components/interior/value-flash.test.tsx b/client/src/components/interior/value-flash.test.tsx
new file mode 100644
index 000000000..71f467c58
--- /dev/null
+++ b/client/src/components/interior/value-flash.test.tsx
@@ -0,0 +1,242 @@
+import { act, cleanup, render, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { type UseValueFlashOptions, useValueFlash } from "./use-value-flash";
+import { ValueFlash } from "./value-flash";
+
+type Props = { value: number } & UseValueFlashOptions<number>;
+
+const QUESTION = { resetKey: "site 1 · today · no filters", ready: true, fetching: false };
+
+function setup(initial: Partial<Props> = {}) {
+ let props: Props = { value: 100, ...QUESTION, ...initial };
+ const hook = renderHook((p: Props) => useValueFlash(p.value, p), { initialProps: props });
+ return {
+ result: hook.result,
+ update(next: Partial<Props>) {
+ props = { ...props, ...next };
+ hook.rerender(props);
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe("useValueFlash", () => {
+ it("never flashes on first render", () => {
+ const { result } = setup();
+ expect(result.current).toEqual({ direction: null, flashing: false, changeId: 0 });
+ });
+
+ it("flashes once, in the direction of travel, when the same question gets a new answer", () => {
+ const { result, update } = setup();
+
+ update({ value: 120 });
+ expect(result.current).toEqual({ direction: "up", flashing: true, changeId: 1 });
+
+ act(() => vi.advanceTimersByTime(900));
+ // The mark ends but keeps its direction so it can fade out in place.
+ expect(result.current).toEqual({ direction: "up", flashing: false, changeId: 1 });
+
+ act(() => vi.advanceTimersByTime(5000));
+ update({ value: 90 });
+ expect(result.current).toMatchObject({ direction: "down", flashing: true, changeId: 2 });
+ });
+
+ it("stays quiet on re-renders that don't change the value", () => {
+ const { result, update } = setup();
+ update({ value: 100 });
+ update({ fetching: true });
+ update({ fetching: false });
+ expect(result.current.changeId).toBe(0);
+ });
+
+ it("re-baselines silently when the question changes (site, range, filters, bucket)", () => {
+ const { result, update } = setup();
+
+ update({ resetKey: "site 1 · yesterday · no filters", value: 40 });
+ expect(result.current.changeId).toBe(0);
+
+ // The new question's own background refetch does flash.
+ update({ value: 45 });
+ expect(result.current).toMatchObject({ direction: "up", flashing: true, changeId: 1 });
+ });
+
+ it("doesn't flash while placeholder data stands in, nor when the real answer replaces it", () => {
+ const { result, update } = setup();
+
+ // Range changed: the previous range's number is still on screen as placeholder data.
+ update({ resetKey: "site 1 · last 7 days · no filters", ready: false, fetching: true });
+ update({ value: 700, ready: true, fetching: false });
+ expect(result.current.changeId).toBe(0);
+
+ update({ value: 710 });
+ expect(result.current.changeId).toBe(1);
+ });
+
+ it("absorbs a stale cached answer being refreshed right after the question changes", () => {
+ const { result, update } = setup();
+
+ update({ resetKey: "site 1 · yesterday · no filters", value: 40, fetching: true });
+ update({ value: 55, fetching: false });
+ expect(result.current.changeId).toBe(0);
+
+ update({ fetching: true });
+ update({ value: 60, fetching: false });
+ expect(result.current.changeId).toBe(1);
+ });
+
+ it("absorbs the refetch that runs on mount when the cache was stale", () => {
+ const { result, update } = setup({ fetching: true });
+ update({ value: 130, fetching: false });
+ expect(result.current.changeId).toBe(0);
+ });
+
+ it("treats first data after an empty value as a baseline, even when a background refetch brings it", () => {
+ // A new site reads 0 everywhere until its first pageview; the arrival refetches this same question.
+ const { result, update } = setup({ value: 0, empty: true });
+ update({ fetching: true });
+ update({ value: 1, fetching: false, empty: false });
+ expect(result.current.changeId).toBe(0);
+
+ // From then on it is data like any other.
+ update({ value: 3 });
+ expect(result.current).toMatchObject({ direction: "up", flashing: true, changeId: 1 });
+ });
+
+ it("doesn't flash when the data vanishes back to empty", () => {
+ const { result, update } = setup({ value: 5 });
+ update({ value: 0, empty: true });
+ expect(result.current.changeId).toBe(0);
+ });
+
+ it("ignores values that aren't real data yet", () => {
+ const { result, update } = setup({ ready: false });
+ update({ value: 0 });
+ update({ value: 250 });
+ expect(result.current.changeId).toBe(0);
+ });
+
+ it("stays quiet when compare says nothing visible changed", () => {
+ const compact = new Intl.NumberFormat("en", { notation: "compact" });
+ const compare = (next: number, previous: number) =>
+ compact.format(next) === compact.format(previous) ? 0 : next - previous;
+ const { result, update } = setup({ value: 12_345, compare });
+
+ update({ value: 12_351 });
+ expect(result.current.changeId).toBe(0);
+
+ update({ value: 13_020 });
+ expect(result.current).toMatchObject({ direction: "up", changeId: 1 });
+ });
+
+ it("flashes at most once per cooldown on a fast feed", () => {
+ const { result, update } = setup({ cooldown: 2000 });
+
+ update({ value: 101 });
+ act(() => vi.advanceTimersByTime(500));
+ update({ value: 102 });
+ act(() => vi.advanceTimersByTime(500));
+ update({ value: 103 });
+ expect(result.current.changeId).toBe(1);
+
+ act(() => vi.advanceTimersByTime(1500));
+ update({ value: 99 });
+ expect(result.current).toMatchObject({ direction: "down", changeId: 2 });
+ });
+
+ it("drops a throttled mark early rather than let it point the wrong way", () => {
+ const { result, update } = setup({ cooldown: 2000 });
+
+ update({ value: 120 });
+ act(() => vi.advanceTimersByTime(300));
+ update({ value: 125 });
+ expect(result.current).toMatchObject({ direction: "up", flashing: true, changeId: 1 });
+
+ update({ value: 110 });
+ expect(result.current).toMatchObject({ flashing: false, changeId: 1 });
+ });
+});
+
+describe("ValueFlash", () => {
+ const glyphOf = (container: HTMLElement) => container.querySelector<HTMLElement>("[data-slot='value-flash-glyph']");
+
+ function renderFlash(value: number, extra: { invert?: boolean; format?: (value: number) => string } = {}) {
+ return render(
+ <ValueFlash value={value} {...QUESTION} {...extra}>
+ <span>{value}</span>
+ </ValueFlash>
+ );
+ }
+
+ it("renders the value with no mark at rest", () => {
+ const { container } = renderFlash(100);
+ expect(container.textContent).toBe("100");
+ expect(glyphOf(container)).toBeNull();
+ });
+
+ it("tints the text emerald and shows a decorative ▲ on a rise, then fades both", () => {
+ const { container, rerender } = renderFlash(100);
+ rerender(
+ <ValueFlash value={120} {...QUESTION}>
+ <span>120</span>
+ </ValueFlash>
+ );
+
+ const mark = container.firstElementChild as HTMLElement;
+ const glyph = glyphOf(container)!;
+ expect(mark.className).toContain("text-accent-600");
+ expect(mark.className).not.toContain("scale");
+ expect(glyph.getAttribute("aria-hidden")).toBe("true");
+ expect(glyph.style.clipPath).toBe("polygon(50% 0, 100% 100%, 0 100%)");
+ expect(glyph.className).toContain("opacity-100");
+
+ act(() => vi.advanceTimersByTime(900));
+ expect(mark.className).not.toContain("text-accent-600");
+ expect(glyph.className).toContain("opacity-0");
+ });
+
+ it("tints a rise red when up is bad news (bounce rate)", () => {
+ const { container, rerender } = renderFlash(40, { invert: true });
+ rerender(
+ <ValueFlash value={45} invert {...QUESTION}>
+ <span>45</span>
+ </ValueFlash>
+ );
+ expect((container.firstElementChild as HTMLElement).className).toContain("text-red-600");
+ // Still points the way the number moved.
+ expect(glyphOf(container)!.style.clipPath).toBe("polygon(50% 0, 100% 100%, 0 100%)");
+ });
+
+ it("greets a first visit's 100% bounce rate without bad-news red", () => {
+ const { container, rerender } = render(
+ <ValueFlash value={0} invert empty {...QUESTION}>
+ <span>0</span>
+ </ValueFlash>
+ );
+ rerender(
+ <ValueFlash value={100} invert empty={false} {...QUESTION}>
+ <span>100</span>
+ </ValueFlash>
+ );
+ expect((container.firstElementChild as HTMLElement).className).not.toContain("text-red-600");
+ expect(glyphOf(container)).toBeNull();
+ });
+
+ it("doesn't flash when the rendered text is unchanged", () => {
+ const format = (value: number) => `${Math.floor(value / 60)}m`;
+ const { container, rerender } = renderFlash(125, { format });
+ rerender(
+ <ValueFlash value={130} format={format} {...QUESTION}>
+ <span>2m</span>
+ </ValueFlash>
+ );
+ expect(glyphOf(container)).toBeNull();
+ });
+});
diff --git a/client/src/components/interior/value-flash.tsx b/client/src/components/interior/value-flash.tsx
new file mode 100644
index 000000000..c883c81b2
--- /dev/null
+++ b/client/src/components/interior/value-flash.tsx
@@ -0,0 +1,85 @@
+// Adapted from interior.dev "Value Flash" (MIT). See ./THIRD_PARTY_LICENSES.md
+"use client";
+
+import NumberFlow, { type Format } from "@number-flow/react";
+import { type ReactNode, useMemo } from "react";
+
+import { cn } from "@/lib/utils";
+
+import { type UseValueFlashOptions, useValueFlash } from "./use-value-flash";
+
+// Upstream's solid ▲ / ▼, drawn as a clipped span that the triangle fills edge to edge. A span rather
+// than an <svg> so a parent's [&_svg] sizing (every Button has one) can't resize it.
+const GLYPH = {
+ up: "polygon(50% 0, 100% 100%, 0 100%)",
+ down: "polygon(0 0, 100% 0, 50% 100%)",
+} as const;
+
+const GOOD = "text-accent-600 dark:text-accent-400";
+const BAD = "text-red-600 dark:text-red-400";
+
+export type ValueFlashProps = Omit<UseValueFlashOptions<number>, "compare"> & {
+ /** The number on screen. Its change sets the direction. */
+ value: number;
+ /** The value as the user reads it. When given, only a change in this text flashes. */
+ format?: (value: number) => string;
+ /** A rise is bad news (bounce rate): tint it red and a fall emerald. The glyph still points the way it moved. */
+ invert?: boolean;
+ className?: string;
+ children: ReactNode;
+};
+
+/**
+ * Marks a number that just changed under the user: its text takes the delta color and a ▲/▼ appears
+ * beside it, then both fade back. No scale bump (too loud for a data tool). The glyph is absolutely
+ * positioned so the mark never shifts the layout, and it is decorative: the number itself is the content.
+ */
+export function ValueFlash({ value, format, invert = false, className, children, ...options }: ValueFlashProps) {
+ const { direction, flashing } = useValueFlash(value, {
+ ...options,
+ compare: format ? (next, previous) => (format(next) === format(previous) ? 0 : next - previous) : undefined,
+ });
+ const tone = (direction === "up") !== invert ? GOOD : BAD;
+
+ return (
+ <span
+ className={cn(
+ "relative inline-flex items-baseline transition-colors ease-out",
+ // Arrive fast, leave slowly.
+ flashing ? cn("duration-150", tone) : "duration-700",
+ className
+ )}
+ >
+ {children}
+ {direction && (
+ <span
+ aria-hidden="true"
+ data-slot="value-flash-glyph"
+ style={{ clipPath: GLYPH[direction] }}
+ className={cn(
+ "pointer-events-none absolute top-[0.2em] left-full ml-[0.15em] h-[0.4em] w-[0.5em] bg-current transition-opacity ease-out",
+ tone,
+ flashing ? "opacity-100 duration-150" : "opacity-0 duration-700"
+ )}
+ />
+ )}
+ </span>
+ );
+}
+
+export type FlashNumberProps = Omit<ValueFlashProps, "children" | "format"> & {
+ /** NumberFlow's Intl options. Pass a stable object; it also decides when a change is visible. */
+ format?: Format;
+ locales?: Intl.LocalesArgument;
+};
+
+/** NumberFlow that flashes when the number it shows changes in place. */
+export function FlashNumber({ value, format, locales, ...flash }: FlashNumberProps) {
+ const formatter = useMemo(() => new Intl.NumberFormat(locales, format), [locales, format]);
+
+ return (
+ <ValueFlash value={value} format={formatter.format} {...flash}>
+ <NumberFlow value={value} format={format} locales={locales} />
+ </ValueFlash>
+ );
+}