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,7 +1,7 @@
{
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 121,
"total": 143770,
"count": 120,
"total": 141446,
"entries": {
"app/api/dashboard/summary/route.ts": 1032,
"app/api/documents/inbound/route.ts": 811,
@@ -12,7 +12,6 @@
"app/api/medications/intake/bulk/route.ts": 1044,
"app/api/workouts/batch/route.ts": 958,
"app/medications/page-client.tsx": 839,
"app/page-client.tsx": 2324,
"components/admin/backups-section.tsx": 1462,
"components/charts/health-chart.tsx": 2517,
"components/charts/mood-chart.tsx": 1166,
@@ -1,7 +1,7 @@
{
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 410,
"total": 147795,
"count": 408,
"total": 144385,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 314,
@@ -76,8 +76,6 @@
"app/labs/page.tsx :: LabsPage": 228,
"app/medications/page-client.tsx :: MedicationsPageClient": 590,
"app/notifications/page.tsx :: NotificationsPage": 327,
"app/page-client.tsx :: DashboardPageClient": 2131,
"app/page-client.tsx :: DashboardPageClient > (anonymous)": 1279,
"components/activity/activity-calendar-card.tsx :: ActivityCalendarCard": 470,
"components/admin/admin-shell.tsx :: AdminShell": 254,
"components/admin/api-token-overview-section.tsx :: ApiTokenOverviewSection": 212,
@@ -1,7 +1,7 @@
{
"$comment": "tests that read a source file by path, per test file under src/. Maintained by src/__tests__/test-realism-ratchet.test.ts.",
"count": 367,
"total": 367,
"count": 361,
"total": 361,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 1,
"__tests__/admin-data-wipe-completeness.test.ts": 1,
@@ -143,18 +143,13 @@
"__tests__/utc-day-key-allowlist-guard.test.ts": 1,
"__tests__/v1341-locale-parity.test.ts": 1,
"__tests__/visit-link-guard.test.ts": 1,
"__tests__/weight-tile-direction-guard.test.ts": 1,
"__tests__/workout-canonical-identity-guard.test.ts": 1,
"__tests__/write-rate-limit-guard.test.ts": 1,
"__tests__/written-outcome-response-consumer-guard.test.ts": 1,
"__tests__/zod-refusal-issue-list-guard.test.ts": 1,
"app/__tests__/dashboard-analytics-split.test.ts": 1,
"app/__tests__/dashboard-chart-reveal.test.tsx": 1,
"app/__tests__/dashboard-demo-checklist.test.ts": 1,
"app/__tests__/dashboard-hero-wiring.test.ts": 1,
"app/__tests__/dashboard-hrv-rmssd-fallback.test.tsx": 1,
"app/__tests__/dashboard-suspense-boundaries.test.ts": 1,
"app/__tests__/dashboard-tile-strip-skeleton.test.ts": 1,
"app/__tests__/i18n-boot-script-strategy.test.ts": 1,
"app/__tests__/insights-b3-wiring.test.ts": 1,
"app/__tests__/insights-polish.test.ts": 1,
@@ -192,7 +187,6 @@
"components/charts/__tests__/touch-action-guard.test.ts": 1,
"components/cycle/__tests__/use-cycle-ring-has-dial.test.tsx": 1,
"components/dashboard/__tests__/medication-intake-quick-add.test.tsx": 1,
"components/dashboard/__tests__/tile-destinations.test.ts": 1,
"components/day/__tests__/day-door-coverage-guard.test.ts": 1,
"components/day/__tests__/day-not-here-guard.test.ts": 1,
"components/documents/__tests__/document-coach-launch-wiring.test.ts": 1,
@@ -1,7 +1,7 @@
{
"$comment": "Comment lines that open with a release version, per file under src/. Maintained by src/__tests__/version-stamp-ratchet.test.ts.",
"count": 2954,
"total": 10499,
"count": 2953,
"total": 10417,
"entries": {
"__tests__/account-payload-consumer-guard.test.ts": 2,
"__tests__/acting-account-boundary-guard.test.ts": 7,
@@ -678,7 +678,6 @@
"app/onboarding/[step]/page.tsx": 1,
"app/onboarding/handover/page.tsx": 1,
"app/onboarding/page.tsx": 2,
"app/page-client.tsx": 81,
"app/privacy/__tests__/page.test.tsx": 1,
"app/privacy/page.tsx": 1,
"app/settings/[section]/page.tsx": 1,
@@ -46,6 +46,7 @@ const WRITTEN_REASON = /tile-eligibility-exempt:\s*\S/;
const SURFACES = [
"src/app/page-client.tsx",
...listSourceFiles("src/components/dashboard"),
...listSourceFiles("src/components/dashboard/tiles"),
...listSourceFiles("src/lib/dashboard"),
];
@@ -59,7 +59,9 @@ const UNROUNDED_IMPORTERS = ["lib/targets/target-unit-display.ts"];
* screen unrounded.
*/
const RAW_SCALE_SURFACES = [
"app/page-client.tsx",
// The dashboard's chart cards; the values the dashboard renders itself
// convert in the tile context (see `CONVERTS_IN`).
"components/dashboard/tiles/chart-tiles.tsx",
// The insights trends row: a single transformed series hands its scale
// and offset to the mini chart, which formats every value itself.
"components/insights/trends-row.tsx",
@@ -68,6 +70,16 @@ const RAW_SCALE_SURFACES = [
"components/insights/device-score-tile.tsx",
];
/**
* A surface whose rendered values convert in a sibling module: the dashboard's
* chart cards read the preference through the tile context every dashboard
* tile is built from.
*/
const CONVERTS_IN: Readonly<Record<string, string>> = {
"components/dashboard/tiles/chart-tiles.tsx":
"components/dashboard/tiles/tile-context.ts",
};
/** Matches a `factor` / `offset` read off a display transform. */
const RAW_SCALE_READ =
/\b\w*[Tt]ransform(?:For\([^)]*\))?\??\.(factor|offset)\b/;
@@ -207,7 +219,10 @@ describe("display-transform rounding guard — the bypass freeze", () => {
// `useUnitDisplayOnceMounted()`, which is the same sugar with the
// preference withheld from the hydration render.
const offenders = RAW_SCALE_SURFACES.filter(
(rel) => !/\buseUnitDisplay(OnceMounted)?\(\)/.test(read(rel)),
(rel) =>
!/\buseUnitDisplay(OnceMounted)?\(\)/.test(
read(CONVERTS_IN[rel] ?? rel),
),
);
expect(offenders).toEqual([]);
});
+37
View File
@@ -0,0 +1,37 @@
/**
* The dashboard's source, for the guards that pin how it is wired.
*
* The dashboard is a composer (`src/app/page-client.tsx`) over a tile
* registry (`src/components/dashboard/tiles/`): the reads, the tile context,
* the strip and chart definitions and the rendering of both rows each live in
* their own module there. A guard that used to read the one page file reads
* all of them through here, so a rule about the dashboard holds wherever in
* the registry the code it watches sits, and moving code between the files
* cannot turn a negative assertion green. The folder read carries a floor,
* and the page read an anchor, so a rename fails loudly instead of returning
* less text.
*/
import { readSource, readSourceFolder } from "./source-files";
export const DASHBOARD_PAGE = "src/app/page-client.tsx";
export const DASHBOARD_TILES_DIR = "src/components/dashboard/tiles";
/** Each dashboard module as `[repo-relative path, text]`. */
export function dashboardSourceFiles(): Array<[string, string]> {
const page = readSource(DASHBOARD_PAGE, "DashboardPageClient");
const tiles = readSourceFolder(DASHBOARD_TILES_DIR, {
floor: 5,
include: (rel) => !rel.includes("__tests__"),
}).map(([rel, text]): [string, string] => [
`${DASHBOARD_TILES_DIR}/${rel}`,
text,
]);
return [[DASHBOARD_PAGE, page], ...tiles];
}
/** The dashboard modules' text, concatenated in a stable order. */
export function dashboardSource(): string {
return dashboardSourceFiles()
.map(([, text]) => text)
.join("\n");
}
@@ -346,7 +346,10 @@ const V143_FIELDS: ResolvedFieldEntry[] = [
field: "GET /api/dashboard/snapshot tiles.directions",
props: ["insights/schemas.ts#directions"],
readers: [
{ file: "src/app/page-client.tsx", pattern: /tiles\.directions/ },
{
file: "src/components/dashboard/tiles/tile-context.ts",
pattern: /tiles\.directions/,
},
],
},
{
@@ -85,6 +85,9 @@ const HEIGHT_CONTROL = join(
function sweptFiles(): string[] {
return [
join(SRC, "app", "page-client.tsx"),
...walkSourceFiles(join(SRC, "components", "dashboard", "tiles"), {
floor: 5,
}).map((rel) => join(SRC, "components", "dashboard", "tiles", rel)),
...walkSourceFiles(SRC, { floor: 700, extensions: [".tsx"] })
.filter(
(rel) => rel.startsWith("app/insights/") && rel.endsWith("/page.tsx"),
@@ -2,67 +2,54 @@
* The dashboard weight tile colours its trend by the resolved target
* direction, never by a literal (#1006).
*
* Every other tile on the strip passes a literal `directionSentiment`, because
* for resting pulse or steps the good direction is a property of the metric.
* For resting pulse or steps the good direction is a property of the metric.
* Weight is the exception: which way is progress depends on the person's own
* target, and it is resolved on the server (`tiles.weightTrend` on the
* snapshot, `src/lib/targets/weight-trend.ts`). A literal `"up-bad"` here is
* exactly the defect the issue reported — a person below their target saw
* every gain coloured as a setback — and it would type-check and render
* without complaint, so this pins the attribute rather than the pixels.
* snapshot, `src/lib/targets/weight-trend.ts`). A literal `"up-bad"` is
* exactly the defect the issue reported (a person below their target saw
* every gain coloured as a setback), and it would type-check and render
* without complaint.
*
* Structural rather than rendered because the dashboard page early-returns a
* loading gate under SSR, and the property is about the source: the weight
* `<TrendCard>` names `weightTrend.direction`, or it does not.
* The tile is built from the registry with each resolved direction in turn,
* and the card has to carry the one it was handed.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import ts from "typescript";
import type { ReactElement } from "react";
import { describe, expect, it } from "vitest";
const PAGE = join(process.cwd(), "src/app/page-client.tsx");
import { STRIP_TILES } from "@/components/dashboard/tiles/strip-tiles";
import type { DashboardTileContext } from "@/components/dashboard/tiles/tile-context";
function weightTileDirections(): string[] {
const text = readFileSync(PAGE, "utf8");
const file = ts.createSourceFile(
PAGE,
text,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const found: string[] = [];
const visit = (node: ts.Node) => {
if (
ts.isJsxSelfClosingElement(node) &&
node.tagName.getText(file) === "TrendCard"
) {
const attrs = node.attributes.properties.filter(ts.isJsxAttribute);
const key = attrs.find((a) => a.name.getText(file) === "key");
const isWeight =
key?.initializer &&
ts.isStringLiteral(key.initializer) &&
key.initializer.text === "weight";
if (isWeight) {
const direction = attrs.find(
(a) => a.name.getText(file) === "directionSentiment",
);
found.push(direction?.initializer?.getText(file) ?? "<absent>");
}
}
ts.forEachChild(node, visit);
};
visit(file);
return found;
function weightCards(direction: string) {
const ctx = {
t: (key: string) => key,
fmt: { number: (v: number) => String(v) },
td: (_type: string, v: number | null | undefined) => v ?? null,
tdd: (_type: string, v: number | null | undefined) => v ?? null,
unitDisplay: { unitFor: () => "kg" },
summaries: { WEIGHT: { count: 3, latest: 80, avg7: 80, avg30: 81 } },
weightRange: null,
weightHintRange: null,
weightTrend: { direction },
compareBaseline: "none",
tileCompareDelta: () => null,
tileStaleDays: () => null,
directionOf: () => "up-bad",
} as unknown as DashboardTileContext;
const tiles = STRIP_TILES.filter((tile) => tile.widget === "weight");
return tiles.flatMap((tile) => tile.cards(ctx));
}
describe("dashboard weight tile direction", () => {
it("finds exactly one weight tile, so an empty match cannot pass", () => {
expect(weightTileDirections()).toHaveLength(1);
expect(weightCards("down-good")).toHaveLength(1);
});
it("reads the resolved target direction rather than a literal", () => {
expect(weightTileDirections()).toEqual(["{weightTrend.direction}"]);
for (const direction of ["down-good", "up-good", "neutral"]) {
const [card] = weightCards(direction);
const props = (card.node as ReactElement<{ directionSentiment: string }>)
.props;
expect(props.directionSentiment).toBe(direction);
}
});
});