refactor(dashboard): compose the page from a tile registry

The dashboard page held every tile and chart card in one 2,100-line
function: a 1,279-line inline block pushed 24 cards behind 36 show flags.
The cards now live in components/dashboard/tiles/, each with its layout
widget, its own visibility rule (data floor, module, resolved layout) and
its render; the layout toggle and order are applied once by the registry.

- use-dashboard-data: the snapshot or legacy reads, the layout, mood,
  thresholds, the batched chart series and the loading gate
- tile-context: summaries, display units, comparison deltas, freshness,
  directions and target bands, derived once per render
- strip-tiles / chart-tiles: the two registries and their builders
- dashboard-tiles: the strip, the chart row, their skeletons and the
  empty state

The page is a composer of about 170 lines. Rendering is unchanged. The
guards that read page-client.tsx read the whole registry through one
helper; the weight-direction, HRV freshness, BP-in-target comparison and
chart-reveal checks now build the real tiles instead of matching text.
This commit is contained in:
Marc-André Bombeck committed 2026-10-23 11:06:32 +02:00
1 parent 9de64cae3e
commit e25b6365fd
27 files changed
+2179 -2425

No files matched your search

@@ -1,6 +1,5 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
/**
* v1.4.39.2 — dashboard analytics slim/thick split.
@@ -26,16 +25,10 @@ import { join } from "node:path";
* slim/thick split still drives the page, so the protective intent
* holds; the matchers only relaxed to tolerate the `enabled` arg.
*/
const ROOT = join(__dirname, "../../..");
const PAGE_PATH = join(ROOT, "src/app/page-client.tsx");
function load(path: string): string {
return readFileSync(path, "utf8");
}
describe("v1.4.39.2 — dashboard analytics slim/thick split", () => {
it("mounts both the slim slice and the thick slice in parallel", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
// Slim slice — `?slice=summaries` paints the per-type tile strip.
expect(src).toMatch(/useAnalyticsQuery\(\{\s*\n?\s*slice:\s*"summaries"/);
// Thick slice — the no-slice `useAnalyticsQuery` feeds the
@@ -45,7 +38,7 @@ describe("v1.4.39.2 — dashboard analytics slim/thick split", () => {
});
it("merges slim and thick results so call-sites stay shape-stable", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
// The merge contract: slim wins on overlapping fields, thick fills
// in `bpInTargetPct*` and `glucoseByContext`. The text anchors
// protect against a future refactor accidentally dropping one of
@@ -21,11 +21,17 @@
* `resolveChartRevealState` resolver, the markup through
* `renderToStaticMarkup`, and the page wiring through textual pins.
*/
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import type { ReactElement } from "react";
import { describe, it, expect, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import {
CHART_TILES,
revealChartIds,
type ChartTileContext,
} from "@/components/dashboard/tiles/chart-tiles";
import {
CHART_REVEAL_TIMEOUT_MS,
DashboardChartCell,
@@ -34,8 +40,6 @@ import {
import { TrendCardSkeleton } from "@/components/charts/trend-card-skeleton";
import { I18nProvider } from "@/lib/i18n/context";
const PAGE_PATH = join(process.cwd(), "src/app/page-client.tsx");
describe("resolveChartRevealState", () => {
it("stays hidden while the gate is not armed (no visible charts yet)", () => {
expect(
@@ -145,46 +149,65 @@ describe("TrendCardSkeleton", () => {
});
});
describe("dashboard chart-reveal wiring (page.tsx)", () => {
const src = readFileSync(PAGE_PATH, "utf8");
describe("dashboard chart-reveal wiring (the chart registry)", () => {
const GATED = [
"weight-chart",
"bmi-chart",
"bp-chart",
"pulse-chart",
"bodyFat-chart",
"mood-chart",
"sleep-chart",
"steps-chart",
"medications",
];
it("derives the gated id list from the chart visibility gates", () => {
expect(src).toMatch(/const\s+revealChartIds:\s*string\[\]\s*=\s*\[\];/);
expect(src).toMatch(/useDashboardChartReveal\(revealChartIds\)/);
it("derives the gated id list from the visible chart cards", () => {
expect(revealChartIds(CHART_TILES)).toEqual(GATED);
// A hidden card drops out of the list the reveal waits for.
expect(
revealChartIds(CHART_TILES.filter((tile) => tile.id !== "bp-chart")),
).toEqual(GATED.filter((id) => id !== "bp-chart"));
expect(dashboardSource()).toMatch(
/useDashboardChartReveal\(revealChartIds\(chartTiles\)\)/,
);
});
it("every data-backed chart reports through onDataReady", () => {
for (const id of [
"weight-chart",
"bmi-chart",
"bp-chart",
"pulse-chart",
"bodyFat-chart",
"mood-chart",
"sleep-chart",
"steps-chart",
"medications",
]) {
expect(src).toContain(`onDataReady={() => markChartReady("${id}")}`);
const markChartReady = vi.fn();
const ctx = {
t: (key: string) => key,
unitDisplay: {
unitFor: () => "kg",
transformFor: () => ({ factor: 1, offset: 0 }),
},
user: { heightCm: 180, timezone: "Europe/Berlin" },
summaries: {},
compareBaseline: "none",
preloadedSeries: undefined,
markChartReady,
} as unknown as ChartTileContext;
for (const tile of CHART_TILES.filter((t) => GATED.includes(t.id))) {
const node = tile.render(ctx) as ReactElement<{
onDataReady?: () => void;
}>;
node.props.onDataReady?.();
expect(markChartReady).toHaveBeenLastCalledWith(tile.id);
}
expect(markChartReady).toHaveBeenCalledTimes(GATED.length);
});
it("gated entries render inside DashboardChartCell", () => {
expect(src).toMatch(
expect(dashboardSource()).toMatch(
/entry\.revealGated\s*\?[\s\S]*?<DashboardChartCell revealed=\{chartsRevealed\}>/,
);
});
it("self-skeletoning cards (achievements / workouts) stay outside the gate", () => {
// Their entries never set `revealGated`, so the ungated branch
// renders them directly.
const achievements = src.match(
/charts\.push\(\{\s*id:\s*"achievements"[\s\S]*?\}\);/,
);
const workouts = src.match(
/charts\.push\(\{\s*id:\s*"recentWorkouts"[\s\S]*?\}\);/,
);
expect(achievements?.[0]).not.toContain("revealGated");
expect(workouts?.[0]).not.toContain("revealGated");
for (const id of ["achievements", "recentWorkouts", "vorsorge"]) {
const tile = CHART_TILES.find((t) => t.id === id);
expect(tile, id).toBeDefined();
expect(tile?.revealGated, id).toBeUndefined();
}
});
});
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -13,7 +14,6 @@ import { join } from "node:path";
* client mounts the checklist only without it.
*/
const PAGE_PATH = join(process.cwd(), "src/app/page.tsx");
const CLIENT_PATH = join(process.cwd(), "src/app/page-client.tsx");
describe("dashboard setup checklist on a demo instance", () => {
it("threads DEMO_MODE into every render of the dashboard client", () => {
@@ -27,7 +27,7 @@ describe("dashboard setup checklist on a demo instance", () => {
});
it("mounts the checklist only outside demo mode", () => {
const src = readFileSync(CLIENT_PATH, "utf8");
const src = dashboardSource();
const mounts = src.match(/<GettingStartedChecklist\b[^>]*\/>/g) ?? [];
expect(mounts).toHaveLength(1);
expect(src).toContain("{demoMode ? null : <GettingStartedChecklist />}");
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -16,14 +17,13 @@ import { join } from "node:path";
* once carried it — is gone), while the page itself derives no
* welcome text.
*/
const PAGE_PATH = join(process.cwd(), "src/app/page-client.tsx");
const HEADER_PATH = join(
process.cwd(),
"src/components/dashboard/dashboard-header.tsx",
);
describe("dashboard hero — page wiring", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
it("mounts the TodayHero above the tile strip", () => {
const heroIdx = src.indexOf("<TodayHero");
@@ -80,7 +80,7 @@ describe("dashboard hero — header greeting", () => {
});
it("the page mounts the header without a greeting prop", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toContain(
"<DashboardHeader onQuickEntry={setQuickEntryDialog} />",
);
@@ -1,3 +1,4 @@
import type { ReactElement } from "react";
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
@@ -19,7 +20,8 @@ import {
import { moduleForMeasurementType } from "@/lib/modules/measurement-scope";
import { locales } from "@/lib/i18n/config";
import type { DataSummary } from "@/lib/analytics/trends";
import { readSource } from "@/__tests__/helpers/source-files";
import { STRIP_TILES } from "@/components/dashboard/tiles/strip-tiles";
import type { DashboardTileContext } from "@/components/dashboard/tiles/tile-context";
/**
* The dashboard HRV tile must accept either HRV type.
@@ -245,20 +247,37 @@ describe("the tile the user actually sees", () => {
}
});
it("does not read freshness off a hardcoded SDNN type", () => {
// The one source-level check kept, and deliberately a NEGATIVE one: it
// names the exact expression the bug lived on rather than asserting the
// current formatting of the replacement, so reformatting cannot break
// it. Freshness is per-type and captioning a live RMSSD tile from the
// SDNN lookup is the failure it guards.
const page = readSource("src/app/page-client.tsx", [
"const tileStaleDays",
"HEART_RATE_VARIABILITY",
]);
expect(page).not.toContain('tileStaleDays("HEART_RATE_VARIABILITY")');
expect(page).not.toContain(
"const hrvSummary = data?.summaries?.HEART_RATE_VARIABILITY",
);
it("reads freshness off the series the tile shows", () => {
// Freshness is per type, and captioning a live RMSSD tile from the SDNN
// lookup marked it permanently stale. The registry's HRV tile is built
// with a context whose freshness differs per type, so the caption it
// asks for names the type it used.
const hrvTile = STRIP_TILES.find((tile) => tile.widget === "hrv");
expect(hrvTile).toBeDefined();
for (const [summaries, type, days] of [
[{ HRV_RMSSD: summary(30, 42) }, "HRV_RMSSD", 12],
[
{ HEART_RATE_VARIABILITY: summary(9, 55) },
"HEART_RATE_VARIABILITY",
20,
],
] as const) {
const ctx = {
t: (key: string) => key,
summaries,
hrv: pickHrvSummary(summaries),
compareBaseline: "none",
directionOf: () => "neutral",
tileCompareDelta: () => null,
tileStaleDays: (t: string | null | undefined) =>
t === "HRV_RMSSD" ? 12 : t === "HEART_RATE_VARIABILITY" ? 20 : null,
} as unknown as DashboardTileContext;
expect(hrvTile?.visible(ctx), type).toBe(true);
const [card] = hrvTile?.cards(ctx) ?? [];
const props = (card.node as ReactElement<{ staleDays: number | null }>)
.props;
expect(props.staleDays, type).toBe(days);
}
});
});
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import { readSource } from "@/__tests__/helpers/source-files";
/**
* v1.4.40 — dashboard Suspense boundaries.
@@ -22,22 +22,16 @@ import { join } from "node:path";
* a future refactor that drops the boundary lands a failing test
* rather than silently regressing the streaming-composition contract.
*/
const ROOT = join(__dirname, "../../..");
const PAGE_PATH = join(ROOT, "src/app/page-client.tsx");
function load(path: string): string {
return readFileSync(path, "utf8");
}
describe("v1.4.40 — dashboard per-cell Suspense boundaries", () => {
it("imports Suspense from React", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
expect(src).toMatch(/from\s+"react"/);
expect(src).toMatch(/\bSuspense\b/);
});
it("wraps the chart-row cell in a `<Suspense fallback={<ChartSkeleton />}>` boundary", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
// `<Suspense fallback={<ChartSkeleton />}>{entry.node}</Suspense>`
// exact contract: the chart row's per-cell fallback uses the same
// ChartSkeleton primitive the dynamic-loaded charts already paint
@@ -48,7 +42,7 @@ describe("v1.4.40 — dashboard per-cell Suspense boundaries", () => {
});
it("wraps each tile-strip cell in a `<Suspense>` boundary with a layout-stable placeholder", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
// v1.4.41 W-FRONTEND-FACTORY (UX M1) swapped the prior `null`
// fallback for an `aria-hidden` placeholder div; v1.16.0 upgraded
// it to the structured `<TrendCardSkeleton>` silhouette (the
@@ -64,18 +58,20 @@ describe("v1.4.40 — dashboard per-cell Suspense boundaries", () => {
});
it("hoists DASHBOARD_QUERY_OPTS to module scope (audit-M2)", () => {
const src = load(PAGE_PATH);
// Module-scope declaration — search outside the component body.
// Pre-fix the const was declared inside `DashboardPage` so every
// render created a fresh `{}` reference.
const moduleSliceEnd = src.indexOf("export default function DashboardPage");
const src = readSource(
"src/components/dashboard/tiles/use-dashboard-data.ts",
"export function useDashboardData",
);
// Module-scope declaration — search outside the hook body. Declared
// inside it, every render would create a fresh `{}` reference.
const moduleSliceEnd = src.indexOf("export function useDashboardData");
expect(moduleSliceEnd).toBeGreaterThan(0);
const moduleSlice = src.slice(0, moduleSliceEnd);
expect(moduleSlice).toMatch(/const\s+DASHBOARD_QUERY_OPTS\s*=\s*\{/);
});
it("keeps the per-render Intl hour walk off the page (audit-H4 successor)", () => {
const src = load(PAGE_PATH);
const src = dashboardSource();
// The audit-H4 `useMemo(getHourForTimeZone, [userTimezone])` pin
// moved off the page with the greeting itself: the greeting now
// lives in the header (`dashboard-header.tsx`), so the page no
@@ -1,12 +1,11 @@
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import {
resolveChartRowPlaceholderCount,
resolveConfiguredTileCount,
resolveDashboardFirstPaintGate,
} from "../page-client";
} from "@/components/dashboard/dashboard-gates";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import {
DEFAULT_DASHBOARD_LAYOUT,
type DashboardLayout,
@@ -33,7 +32,6 @@ import {
* snapshot fetch. The pure `resolveDashboardFirstPaintGate` carries the
* behaviour; textual pins keep the wiring honest.
*/
const PAGE_PATH = join(process.cwd(), "src/app/page-client.tsx");
describe("resolveDashboardFirstPaintGate", () => {
const base = {
@@ -173,14 +171,14 @@ describe("resolveChartRowPlaceholderCount (v1.16.8)", () => {
describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
it("derives `configuredTileCount` through the tile-capable resolver", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(
/const\s+configuredTileCount\s*=\s*resolveConfiguredTileCount\(layout\);/,
);
});
it("reserves the chart row while the primary query loads", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
// The placeholder count keys off the layout config minus the
// already-mounted (layout-gated) cells, and only while loading.
// `mounted &&` pins the hydration render to the SSR output — the
@@ -189,7 +187,7 @@ describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
expect(src).toMatch(
/const\s+chartRowPlaceholderCount\s*=\s*primaryLoading[\s\S]*?resolveChartRowPlaceholderCount\(layout,[\s\S]*?hasHeightCm:\s*mounted\s*&&\s*Boolean\(user\?\.heightCm\)/,
);
expect(src).toMatch(/-\s*charts\.length/);
expect(src).toMatch(/-\s*chartEntries\.length/);
// The reserved cells render as aria-hidden ChartSkeletons in their
// own slot.
const skeletonBlock = src.match(
@@ -201,7 +199,7 @@ describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
});
it("derives `primaryLoading` from the snapshot vs slim query", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
// v1.16.4 — `!mounted` pins SSR + the hydration render to the
// skeleton branch so a late-hydrating boundary can't disagree with
// the server HTML (React #418); see `useMounted`.
@@ -211,21 +209,21 @@ describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
});
it("routes the gate through `resolveDashboardFirstPaintGate`", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(
/resolveDashboardFirstPaintGate\(\{[\s\S]*?primaryLoading,[\s\S]*?\}\)/,
);
});
it("renders the skeleton with the same auto-fit grid track the real strip uses", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(
/showTileStripSkeleton\s*&&\s*\(\s*<div[\s\S]*?\[grid-template-columns:repeat\(auto-fit,minmax\(min\(100%,11rem\),1fr\)\)\]/,
);
});
it("keys the skeleton card count off configuredTileCount", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(
/Array\.from\(\{\s*length:\s*configuredTileCount\s*\}\)/,
);
@@ -237,7 +235,7 @@ describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
// Reduced motion moved into the component (the `<Skeleton>` primitive
// carries `motion-reduce:animate-none`); the per-component test in
// `dashboard-chart-reveal.test.tsx` pins that.
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
const skeletonBlock = src.match(
/showTileStripSkeleton\s*&&[\s\S]*?<\/div>\s*\)\}/,
);
@@ -248,12 +246,12 @@ describe("v1.4.43 W11 — dashboard tile-strip skeleton (wiring)", () => {
});
it("uses the structured silhouette as the per-tile Suspense fallback", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(/<Suspense fallback=\{<TrendCardSkeleton \/>\}>/);
});
it("gates the EmptyState on the resolved `showEmptyState` flag", () => {
const src = readFileSync(PAGE_PATH, "utf8");
const src = dashboardSource();
expect(src).toMatch(/if\s*\(showEmptyState\)\s*\{/);
});
});
+37 -12
View File
@@ -1,7 +1,12 @@
import type { ReactElement } from "react";
import { describe, it, expect } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import { STRIP_TILES } from "@/components/dashboard/tiles/strip-tiles";
import type { DashboardTileContext } from "@/components/dashboard/tiles/tile-context";
/**
* v1.4.19 — guards for the polish pass on `/insights` and the
* dashboard:
@@ -28,7 +33,6 @@ import { join } from "node:path";
*/
const ROOT = join(__dirname, "../../..");
const DASHBOARD_PATH = join(ROOT, "src/app/page-client.tsx");
const INSIGHTS_PATH = join(ROOT, "src/app/insights/page-client.tsx");
const INSIGHTS_LAYOUT_PATH = join(ROOT, "src/app/insights/layout.tsx");
@@ -38,7 +42,7 @@ function load(path: string): string {
describe("v1.4.19 A3 — dashboard polish", () => {
it("dashboard page does NOT render <CompareToggle />", () => {
const src = load(DASHBOARD_PATH);
const src = dashboardSource();
// The component import + JSX use are both gone. The toggle still
// lives on /insights via a separate import there.
expect(src).not.toMatch(/<CompareToggle\b/);
@@ -52,9 +56,9 @@ describe("v1.4.19 A3 — dashboard polish", () => {
// baseline plumbing along with the toggle, every chart on the
// dashboard would lose its comparison overlay silently. The
// resolved layout still carries the value to each chart.
const src = load(DASHBOARD_PATH);
expect(src).toContain("comparisonBaseline");
expect(src).toContain("compareBaseline");
const src = dashboardSource();
expect(src).toContain("layout.comparisonBaseline");
expect(src).toContain("compareBaseline={ctx.compareBaseline}");
});
});
@@ -203,13 +207,34 @@ describe("v1.4.22 W5 reconcile (Code-H2) — BD-Zielbereich tile compareDelta us
* window (priorMonth / priorYear) instead of all-time.
*/
it("subtracts bpInTargetPctPriorMonth when comparisonBaseline=lastMonth", () => {
const src = load(DASHBOARD_PATH);
// The fix introduces `bpComparePrior` keyed by `compareBaseline`.
expect(src).toContain("bpInTargetPctPriorMonth");
expect(src).toContain("bpInTargetPctPriorYear");
// The all-time shortcut from v1.4.22 A2 must not subtract `bpAll`
// for the comparison delta any more.
expect(src).not.toMatch(/bp30\s*-\s*bpAll/);
// The tile is built from the registry with a 30-day share of 80 % and
// prior periods of 70 % (month), 50 % (year) and 40 % (all time): the
// delta follows the chosen baseline and never the all-time share.
const tile = STRIP_TILES.find((t) => t.widget === "bpInTarget");
const deltaFor = (compareBaseline: string) => {
const ctx = {
t: (key: string) => key,
compareBaseline,
directionOf: () => "neutral",
data: {
bpInTargetPct: 75,
bpInTargetPct7d: 78,
bpInTargetPct30d: 80,
bpInTargetPctAllTime: 40,
bpInTargetPctPriorMonth: 70,
bpInTargetPctPriorYear: 50,
bpInTargetCount90: 200,
bpInTargetSpanDays90: 90,
},
} as unknown as DashboardTileContext;
expect(tile?.visible(ctx)).toBe(true);
const [card] = tile?.cards(ctx) ?? [];
return (card.node as ReactElement<{ compareDelta: number | null }>).props
.compareDelta;
};
expect(deltaFor("lastMonth")).toBe(10);
expect(deltaFor("lastYear")).toBe(30);
expect(deltaFor("none")).toBeNull();
});
it("ships priorMonth + priorYear pcts in the analytics envelope", () => {
@@ -1,3 +1,4 @@
import { dashboardSource } from "@/__tests__/helpers/dashboard-source";
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { readFileSync } from "node:fs";
@@ -86,10 +87,7 @@ describe("RootLoading — single skeleton source (wiring pins)", () => {
join(process.cwd(), "src/app/loading.tsx"),
"utf8",
);
const pageSrc = readFileSync(
join(process.cwd(), "src/app/page-client.tsx"),
"utf8",
);
const pageSrc = dashboardSource();
it("imports the same silhouette components the page's loading phase uses", () => {
expect(loadingSrc).toContain(
+96 -2231
View File
File diff suppressed because it is too large. Load diff