diff --git a/bundle-budget.json b/bundle-budget.json
index cb161380b..607b72b9a 100644
--- a/bundle-budget.json
+++ b/bundle-budget.json
@@ -1,5 +1,5 @@
{
- "$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.37.2: / 455, /insights 443, /measurements 441, /insights/mood 453, total 3328, baseline 130, lazy catalogs 849. Every per-route ceiling is unchanged. The /insights overview crept a kilobyte over its 445 ceiling when the ECG teaser began importing its overview cap from the classification module, dragging that module's label map and helpers into the eager page; the cap now lives in its own value-only module, and the Health Score's single provenance entry is split out of the full metric-provenance map, so the overview imports the bare number and citation it renders rather than every metric's label map behind them. Both are back under 445 with room to spare. The 42 KB aggregate rise from 3286 (v1.35.0) is all locale-catalog strings: v1.36 and v1.37 added the encounter, mood-context, mood-prognosis, practitioner, workout-batch and account-sharing surfaces, and their copy lands across the six locale catalogs the whole-build sum counts independently (804 to 849 KB). The non-catalog client chunks are flat against v1.35.0, so nothing a person downloads on a given route grew beyond its own ceiling. The aggregate cap therefore moves from 3310 to 3352 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged. v1.37.4's honest-error-state charge then added recoverable read-failure handling to thirteen surfaces (the shared QueryErrorCard and QueryErrorRow primitives plus an isError branch per surface) and rewrote the MCP scope note and the managed-record error copy across the six locales; the measured total rose to 3404 while every per-route ceiling stayed met (/page 457, /insights 445, /measurements 443, /insights/mood 455). The aggregate cap moves from 3352 to 3428, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.15's async-truth charge then added the refresh settling state with its two-locale-key copy, the index-outcome plain-words line (seven keys across the six catalogs) and the reindex-count wiring; the measured total rose to 3429 while every per-route ceiling stayed met (/page 456, /insights 445, /measurements 442, /insights/mood 455). The aggregate cap moves from 3428 to 3452, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.27 found /insights sitting a few hundred bytes under 445 on main and a few hundred over it on the release branch — the page had been at its ceiling for three releases and the release only had to breathe on it. The weight it was carrying was not its own: the authenticated shell imported one destination predicate from the `@/lib/record-settings` barrel, and the barrel also re-exports the managed settings-patch schemas, so Zod, the module registry and three validation modules rode into the eager bundle of every authenticated route for a function that reads a URL slug. The shell imports the `classification` leaf now. Measured across all 585 client-rendered routes: none grew by a byte, 100 fell, by 4.7 KB at the median and 8.1 KB at the most; /insights 444 to 437, /measurements 442 to 435, / 456 to 450, /insights/mood 455 to 450. The whole-build sum moved the other way, 3451 to 3476, and that direction is the metric rather than the change: the aggregate counts each emitted chunk once, so a graph that leaves the chunk group every route shares gets counted again wherever it lands — here inside the deferred settings chunks that actually use it. Bytes on disk rose 25 KB; bytes a reader downloads only ever fell. The aggregate cap moves from 3452 to 3500, the same 24 KB headroom as the four re-measurements before it. Per-route ceilings keep their old values rather than tightening to the new floor: the CI runner measures each route about 1.5 KB heavier than a local arm64 build does, and a ceiling set from a local number would fail on a build that had not regressed. The static-catalog guard and the one-Recharts-chunk guard remain unchanged. Raised to 3700 at v1.37.32 for the seventh interface language (Korean): the lazy message catalogs went 6->7 chunks (1026 KB gz measured), pushing the aggregate to 3631 against the old 3500. The raise is entirely the new catalog; no route budget moved, and the four eager route ceilings are unchanged and still passing. Most of the aggregate is the dynamic locale-switch and fallback path that a first paint never loads (see issue #253), so this ceiling guards bytes almost no visitor requests; 3700 leaves ~69 KB for ordinary drift until that double-count is cleaned up. v1.38.14 re-measures the four eager routes and changes what the number means. The ceilings had been re-stated but never re-based since v1.37.4, so /insights and /measurements sat within a kilobyte of theirs and / and /insights/mood within one of theirs; e2e run 34043772954 failed on `/insights/page: 445 KB gz exceeds the 445 KB budget` with the other two at 459 of 460, and none of it was a regression anyone had made. A ceiling a route is already touching does not measure the route, it measures whichever dependency bump landed that week. The file states the measured value per route now, plus one drift allowance over it: measured on a local arm64 build at d48bbff01 as / 447, /insights 434, /measurements 433, /insights/mood 447, with a 20 KB allowance, so the effective ceilings are 467 / 454 / 453 / 467 — a raise for all four. The allowance covers the runner delta (the CI runner measures each route a little heavier than a local arm64 build) and ordinary week-to-week drift, while the step change the gate exists for — a statically imported message catalog, a duplicated chart library — is several times larger and still fails. Every run now prints the delta against the baseline, so a route that has crept 15 KB is legible in the log long before it is red; the flat ceiling could only ever say pass or fail. Re-base by re-measuring on a build with nothing else in it and writing the new numbers here with the reason, exactly as a raised ceiling was written before. Raised to 3724 at v1.39.4 on a measured delta, not a feature. The release branch alone measured 3699 KB gz (3698.9) against the 3700 cap, so the ordinary drift room the v1.37.32 raise left had been used up by the releases since; the review fixes on top of it added 1.3 KB gz across the whole build (3700.2), almost all of it new copy in the seven lazy locale catalogs (the total and reused-table labels, the step and chip wording) plus the result-panel states. The four eager routes measured the same on both builds (/ 458, /insights/mood 456, /insights 445, /measurements 442), all inside their ceilings. The aggregate cap moves from 3700 to 3724, the same 24 KB headroom as the re-measurements before it. Raised to 3749 at v1.39.9 on a measured delta. Main measured 3718 KB gz after v1.39.7 and v1.39.8 (unit-aware copy, the phone layouts, the time-zone work and the account-settings restore labels, almost all of it new strings in the seven lazy locale catalogs), leaving 6 KB of the v1.39.4 headroom; the manual workout entry (#1085: the form, its sheet, the delete action and their copy in seven locales) adds about 7 KB and measured 3725. The four eager routes stay inside their drift allowances (/ +12.5, /insights +12.1, /insights/mood +10.2 KB of 20 on main). The aggregate cap moves from 3724 to 3749, the same 24 KB headroom as the re-measurements before it. Raised to 3790 at v1.40.0 on a measured delta. With the background document reads on main (#1103: the run polling hook, the still-reading states and their copy in seven locales), the key backup step and the plain-http sign-in notice (#1104) and the v1.40 fixes (#1106: the duration reader, the marker unit lock, the chart window) each branch measured 3752 KB gz on its own against the 3749 cap; together they add a few KB more. The four eager routes stay inside their drift allowances (/ +18.4, /insights +16.5, /measurements +14.9, /insights/mood +14.7 KB of 20). The aggregate cap moves from 3749 to 3790, about 24 KB above the combined build, the same headroom as the re-measurements before it. Re-based at v1.40.0 when the quick-entry forms began loading on demand. Custom symptoms added a fifth quick-entry form, and with all five forms bundled eagerly every one of the four eager routes measured over its ceiling (/ 472, /insights 457, /insights/mood 468, /measurements 454 KB gz, each 21 to 25 KB over the baseline). Loading the forms on demand brings them to / 429, /insights 368, /insights/mood 379, /measurements 411: 43 to 90 KB less on first load. The four route baselines move down to those measured values, so the gain is protected by the same 20 KB allowance rather than spent. The aggregate moves the other way, 3774 to 4077, for the reason described at v1.37.27: the aggregate counts each emitted chunk once per route group, and on-demand form chunks land in every route group that can open a quick-entry sheet. Bundling the five forms into one shared on-demand module measured the same (4078), so the split is not the cause. The aggregate cap moves from 3790 to 4100. Bytes on disk rose; bytes a reader downloads fell on every eager route. Raised to 4155 at v1.40.2 on a measured delta. The Coach redesign (the right conversation panel, its row menu and the quick-settings overlay, all loaded on demand), the answer action row, the dashboard's Today overview, the document procedure filter and their copy in seven locales took the whole-build sum from 4080 to 4129 KB gz; most of it is new strings in the seven lazy locale catalogs and the on-demand Coach chunks, which a first paint does not load. The four eager routes stay well inside their drift allowances (/ +1.9, /measurements +1.9, /insights/mood +1.4, /insights +1.0 KB of 20). The aggregate cap moves from 4100 to 4155, about 26 KB above the build, the same headroom as before; per-route baselines are unchanged. Raised to 4182 at v1.42.0 on a measured delta. Main measured 4146 KB gz (lazy catalogs 1177, other chunks 2969); the release branch's shared contract change measured 4158 (lazy catalogs 1188, other chunks 2969): the whole 12 KB is new strings in the seven lazy locale catalogs (the Health Connect import card, air quality and pollen, the managed-profile handover and claim, own vaccines, the lab conversion note, the per-type Apple Health list), and no eager route moved (/ +3.6, /measurements +1.5, /insights/mood +1.1, /insights +0.7 KB of 20). The aggregate cap moves from 4155 to 4182, about 24 KB above the build, the same headroom as before; per-route baselines are unchanged. Re-based at v1.42.0 when the settings sections and Zod left the shared bundles. The settings section route imported all twenty-one sections statically; each now loads on its own, and /settings/[section] measured 611 KB gz before and 403 after. The account-access parse that runs on every boot was the shell's only Zod import, about 63 KB gz on every route; it is plain TypeScript now, held to the published schema by an equivalence test, and the layout entry fell from 199 to 136 KB gz. The canonical unit table moved out of the measurement validation module, which took Zod off the routes whose only reason for it was the display transform: /insights 369 to 304, /medications 428 to 365, /labs 400 to 337. Across the 627 client routes 62 fell, none grew by more than 2 KB, and the per-route sum fell by 1844 KB gz. The /insights baseline moves down to 304 and /settings/[section] joins the watched routes at 403, so both gains are held by the same 20 KB allowance rather than spent. The aggregate moves the other way, 4167 to 4311, for the reason described at v1.37.27 and v1.40.0: the aggregate counts each emitted chunk once, and modules that used to sit in one shared chunk are now emitted into each route group that still needs them (the measurement validation module and the unit table into about twenty-five each, the settings sections into their own chunks). Bytes on disk rose; bytes a reader downloads fell on every route that moved. The aggregate cap moves from 4182 to 4335, about 24 KB above the build, the same headroom as before. Raised to 4400 at v1.42.0 on a measured delta. The release branch after its tickets merge measured 4365 KB gz (lazy catalogs 1206, other chunks 3159), already 30 KB over the 4335 cap; the day view and timeline contract adds 10 more (catalogs 1215, other 3160), almost all of it the base copy for the day, the timeline and life events in seven locales. The aggregate cap moves from 4335 to 4400, about 25 KB above the build, the same headroom as before; per-route baselines are unchanged.",
+ "$comment": "Client-bundle budgets, enforced by scripts/check-bundle-budget.mjs (--check) after `next build` in CI. Values are KB gzip and include every emitted lazy route and locale chunk, while route budgets include the shared rootMainFiles baseline. Re-measured at v1.37.2: / 455, /insights 443, /measurements 441, /insights/mood 453, total 3328, baseline 130, lazy catalogs 849. Every per-route ceiling is unchanged. The /insights overview crept a kilobyte over its 445 ceiling when the ECG teaser began importing its overview cap from the classification module, dragging that module's label map and helpers into the eager page; the cap now lives in its own value-only module, and the Health Score's single provenance entry is split out of the full metric-provenance map, so the overview imports the bare number and citation it renders rather than every metric's label map behind them. Both are back under 445 with room to spare. The 42 KB aggregate rise from 3286 (v1.35.0) is all locale-catalog strings: v1.36 and v1.37 added the encounter, mood-context, mood-prognosis, practitioner, workout-batch and account-sharing surfaces, and their copy lands across the six locale catalogs the whole-build sum counts independently (804 to 849 KB). The non-catalog client chunks are flat against v1.35.0, so nothing a person downloads on a given route grew beyond its own ceiling. The aggregate cap therefore moves from 3310 to 3352 (24 KB headroom, matching the previous margin); per-route ceilings, the static-catalog guard and the one-Recharts-chunk guard remain unchanged. v1.37.4's honest-error-state charge then added recoverable read-failure handling to thirteen surfaces (the shared QueryErrorCard and QueryErrorRow primitives plus an isError branch per surface) and rewrote the MCP scope note and the managed-record error copy across the six locales; the measured total rose to 3404 while every per-route ceiling stayed met (/page 457, /insights 445, /measurements 443, /insights/mood 455). The aggregate cap moves from 3352 to 3428, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.15's async-truth charge then added the refresh settling state with its two-locale-key copy, the index-outcome plain-words line (seven keys across the six catalogs) and the reindex-count wiring; the measured total rose to 3429 while every per-route ceiling stayed met (/page 456, /insights 445, /measurements 442, /insights/mood 455). The aggregate cap moves from 3428 to 3452, keeping the same margin; nothing a person downloads on a given route grew beyond its ceiling. v1.37.27 found /insights sitting a few hundred bytes under 445 on main and a few hundred over it on the release branch — the page had been at its ceiling for three releases and the release only had to breathe on it. The weight it was carrying was not its own: the authenticated shell imported one destination predicate from the `@/lib/record-settings` barrel, and the barrel also re-exports the managed settings-patch schemas, so Zod, the module registry and three validation modules rode into the eager bundle of every authenticated route for a function that reads a URL slug. The shell imports the `classification` leaf now. Measured across all 585 client-rendered routes: none grew by a byte, 100 fell, by 4.7 KB at the median and 8.1 KB at the most; /insights 444 to 437, /measurements 442 to 435, / 456 to 450, /insights/mood 455 to 450. The whole-build sum moved the other way, 3451 to 3476, and that direction is the metric rather than the change: the aggregate counts each emitted chunk once, so a graph that leaves the chunk group every route shares gets counted again wherever it lands — here inside the deferred settings chunks that actually use it. Bytes on disk rose 25 KB; bytes a reader downloads only ever fell. The aggregate cap moves from 3452 to 3500, the same 24 KB headroom as the four re-measurements before it. Per-route ceilings keep their old values rather than tightening to the new floor: the CI runner measures each route about 1.5 KB heavier than a local arm64 build does, and a ceiling set from a local number would fail on a build that had not regressed. The static-catalog guard and the one-Recharts-chunk guard remain unchanged. Raised to 3700 at v1.37.32 for the seventh interface language (Korean): the lazy message catalogs went 6->7 chunks (1026 KB gz measured), pushing the aggregate to 3631 against the old 3500. The raise is entirely the new catalog; no route budget moved, and the four eager route ceilings are unchanged and still passing. Most of the aggregate is the dynamic locale-switch and fallback path that a first paint never loads (see issue #253), so this ceiling guards bytes almost no visitor requests; 3700 leaves ~69 KB for ordinary drift until that double-count is cleaned up. v1.38.14 re-measures the four eager routes and changes what the number means. The ceilings had been re-stated but never re-based since v1.37.4, so /insights and /measurements sat within a kilobyte of theirs and / and /insights/mood within one of theirs; e2e run 34043772954 failed on `/insights/page: 445 KB gz exceeds the 445 KB budget` with the other two at 459 of 460, and none of it was a regression anyone had made. A ceiling a route is already touching does not measure the route, it measures whichever dependency bump landed that week. The file states the measured value per route now, plus one drift allowance over it: measured on a local arm64 build at d48bbff01 as / 447, /insights 434, /measurements 433, /insights/mood 447, with a 20 KB allowance, so the effective ceilings are 467 / 454 / 453 / 467 — a raise for all four. The allowance covers the runner delta (the CI runner measures each route a little heavier than a local arm64 build) and ordinary week-to-week drift, while the step change the gate exists for — a statically imported message catalog, a duplicated chart library — is several times larger and still fails. Every run now prints the delta against the baseline, so a route that has crept 15 KB is legible in the log long before it is red; the flat ceiling could only ever say pass or fail. Re-base by re-measuring on a build with nothing else in it and writing the new numbers here with the reason, exactly as a raised ceiling was written before. Raised to 3724 at v1.39.4 on a measured delta, not a feature. The release branch alone measured 3699 KB gz (3698.9) against the 3700 cap, so the ordinary drift room the v1.37.32 raise left had been used up by the releases since; the review fixes on top of it added 1.3 KB gz across the whole build (3700.2), almost all of it new copy in the seven lazy locale catalogs (the total and reused-table labels, the step and chip wording) plus the result-panel states. The four eager routes measured the same on both builds (/ 458, /insights/mood 456, /insights 445, /measurements 442), all inside their ceilings. The aggregate cap moves from 3700 to 3724, the same 24 KB headroom as the re-measurements before it. Raised to 3749 at v1.39.9 on a measured delta. Main measured 3718 KB gz after v1.39.7 and v1.39.8 (unit-aware copy, the phone layouts, the time-zone work and the account-settings restore labels, almost all of it new strings in the seven lazy locale catalogs), leaving 6 KB of the v1.39.4 headroom; the manual workout entry (#1085: the form, its sheet, the delete action and their copy in seven locales) adds about 7 KB and measured 3725. The four eager routes stay inside their drift allowances (/ +12.5, /insights +12.1, /insights/mood +10.2 KB of 20 on main). The aggregate cap moves from 3724 to 3749, the same 24 KB headroom as the re-measurements before it. Raised to 3790 at v1.40.0 on a measured delta. With the background document reads on main (#1103: the run polling hook, the still-reading states and their copy in seven locales), the key backup step and the plain-http sign-in notice (#1104) and the v1.40 fixes (#1106: the duration reader, the marker unit lock, the chart window) each branch measured 3752 KB gz on its own against the 3749 cap; together they add a few KB more. The four eager routes stay inside their drift allowances (/ +18.4, /insights +16.5, /measurements +14.9, /insights/mood +14.7 KB of 20). The aggregate cap moves from 3749 to 3790, about 24 KB above the combined build, the same headroom as the re-measurements before it. Re-based at v1.40.0 when the quick-entry forms began loading on demand. Custom symptoms added a fifth quick-entry form, and with all five forms bundled eagerly every one of the four eager routes measured over its ceiling (/ 472, /insights 457, /insights/mood 468, /measurements 454 KB gz, each 21 to 25 KB over the baseline). Loading the forms on demand brings them to / 429, /insights 368, /insights/mood 379, /measurements 411: 43 to 90 KB less on first load. The four route baselines move down to those measured values, so the gain is protected by the same 20 KB allowance rather than spent. The aggregate moves the other way, 3774 to 4077, for the reason described at v1.37.27: the aggregate counts each emitted chunk once per route group, and on-demand form chunks land in every route group that can open a quick-entry sheet. Bundling the five forms into one shared on-demand module measured the same (4078), so the split is not the cause. The aggregate cap moves from 3790 to 4100. Bytes on disk rose; bytes a reader downloads fell on every eager route. Raised to 4155 at v1.40.2 on a measured delta. The Coach redesign (the right conversation panel, its row menu and the quick-settings overlay, all loaded on demand), the answer action row, the dashboard's Today overview, the document procedure filter and their copy in seven locales took the whole-build sum from 4080 to 4129 KB gz; most of it is new strings in the seven lazy locale catalogs and the on-demand Coach chunks, which a first paint does not load. The four eager routes stay well inside their drift allowances (/ +1.9, /measurements +1.9, /insights/mood +1.4, /insights +1.0 KB of 20). The aggregate cap moves from 4100 to 4155, about 26 KB above the build, the same headroom as before; per-route baselines are unchanged. Raised to 4182 at v1.42.0 on a measured delta. Main measured 4146 KB gz (lazy catalogs 1177, other chunks 2969); the release branch's shared contract change measured 4158 (lazy catalogs 1188, other chunks 2969): the whole 12 KB is new strings in the seven lazy locale catalogs (the Health Connect import card, air quality and pollen, the managed-profile handover and claim, own vaccines, the lab conversion note, the per-type Apple Health list), and no eager route moved (/ +3.6, /measurements +1.5, /insights/mood +1.1, /insights +0.7 KB of 20). The aggregate cap moves from 4155 to 4182, about 24 KB above the build, the same headroom as before; per-route baselines are unchanged. Re-based at v1.42.0 when the settings sections and Zod left the shared bundles. The settings section route imported all twenty-one sections statically; each now loads on its own, and /settings/[section] measured 611 KB gz before and 403 after. The account-access parse that runs on every boot was the shell's only Zod import, about 63 KB gz on every route; it is plain TypeScript now, held to the published schema by an equivalence test, and the layout entry fell from 199 to 136 KB gz. The canonical unit table moved out of the measurement validation module, which took Zod off the routes whose only reason for it was the display transform: /insights 369 to 304, /medications 428 to 365, /labs 400 to 337. Across the 627 client routes 62 fell, none grew by more than 2 KB, and the per-route sum fell by 1844 KB gz. The /insights baseline moves down to 304 and /settings/[section] joins the watched routes at 403, so both gains are held by the same 20 KB allowance rather than spent. The aggregate moves the other way, 4167 to 4311, for the reason described at v1.37.27 and v1.40.0: the aggregate counts each emitted chunk once, and modules that used to sit in one shared chunk are now emitted into each route group that still needs them (the measurement validation module and the unit table into about twenty-five each, the settings sections into their own chunks). Bytes on disk rose; bytes a reader downloads fell on every route that moved. The aggregate cap moves from 4182 to 4335, about 24 KB above the build, the same headroom as before. Raised to 4400 at v1.42.0 on a measured delta. The release branch after its tickets merge measured 4365 KB gz (lazy catalogs 1206, other chunks 3159), already 30 KB over the 4335 cap; the day view and timeline contract adds 10 more (catalogs 1215, other 3160), almost all of it the base copy for the day, the timeline and life events in seven locales. The aggregate cap moves from 4335 to 4400, about 25 KB above the build, the same headroom as before; per-route baselines are unchanged. Raised to 4470 at v1.42.0 on a measured delta. The release branch with the day view, the timeline and their server measured 4386 KB gz (lazy catalogs 1228, other chunks 3158); giving every chart drawn in days the same doors to its day (one shared hook for the click, the touch tooltip's button, the open day's line, the row of day dots and the caption, a shared calendar adapter, a data table under each newly linked chart) measured 4446 (catalogs 1228, other chunks 3218). The 60 KB is the aggregate's double count again: the hook, the data table and the day link are emitted into each chart's own chunk group rather than once. The eager routes moved by a kilobyte or a few (/ +1.6, /measurements +1.7, /settings/[section] +0.8, /insights/mood +4.6, /insights +1.5 KB) and stay inside their allowances. The aggregate cap moves from 4400 to 4470, about 24 KB above the build, the same headroom as before; per-route baselines are unchanged.",
"routeBaselineKbGz": {
"/page": 429,
"/insights/page": 304,
@@ -8,6 +8,6 @@
"/settings/[section]/page": 403
},
"routeDriftAllowanceKbGz": 20,
- "totalClientKbGz": 4400,
+ "totalClientKbGz": 4470,
"maxRechartsChunks": 1
}
diff --git a/e2e/day-doors.spec.ts b/e2e/day-doors.spec.ts
new file mode 100644
index 000000000..357e2773c
--- /dev/null
+++ b/e2e/day-doors.spec.ts
@@ -0,0 +1,315 @@
+import type { Locator, Page, TestInfo } from "@playwright/test";
+
+import { aiBlockAvailable, serveAiBlock } from "./setup/ai-capabilities";
+import { DAY_DOORS_ANALYTE } from "./setup/day-doors-fixture";
+import { mockDay } from "./setup/day-mock";
+import {
+ DAY_DOORS_STORAGE_STATE_PATH,
+ MOBILE_ROUTES_STORAGE_STATE_PATH,
+} from "./setup/global-setup";
+import { expect, test } from "./setup/test";
+
+/**
+ * v1.42 — every chart drawn in days opens its days, the same way.
+ *
+ * The day view first reached six metric pages; the recovery page beside them
+ * offered no day at all. These journeys walk the surfaces that came after,
+ * each through the same doors: on a fine pointer a click on a point (or a
+ * calendar cell) opens the day beside the page; on a touch screen the first
+ * tap shows the value and the tooltip's "View the whole day" opens it as a
+ * bottom sheet, the tapped value on top. A date in a list opens in one tap.
+ * The dashed line (or outline) marks the open day, the row of dots and the
+ * caption sit under every chart, and the data table's dates are the
+ * keyboard way to the same days.
+ *
+ * - recovery (the page the beta reported), sleep, a lab marker, a chart
+ * with its comparison period on and a dashboard chart: line charts;
+ * - the mood calendar: a heatmap;
+ * - a metric's "all values" list: a date in a row.
+ *
+ * The day itself is a route mock in the contract's shape, as in
+ * `day-view.spec.ts`: these journeys pin the client's doors, not the day.
+ * Stable data attributes only.
+ */
+
+const panel = (page: Page) => page.locator('[data-slot="day-panel"]');
+const isPhone = (testInfo: TestInfo) =>
+ testInfo.project.name === "chromium-mobile";
+
+/** Open the day of the point at 80 % across a day-linked plot. */
+async function openFromPlot(page: Page, plot: Locator, testInfo: TestInfo) {
+ await plot.scrollIntoViewIfNeeded();
+ await expect(plot).toHaveAttribute("data-day-links", "true");
+ const box = (await plot.boundingBox())!;
+ const x = box.x + box.width * 0.8;
+ const y = box.y + box.height / 2;
+ if (isPhone(testInfo)) {
+ await page.touchscreen.tap(x, y);
+ const open = page.locator('[data-slot="chart-tooltip-open-day"]:visible');
+ await expect(open).toBeVisible();
+ // A tap alone never opens a sheet: a point is a small target.
+ await expect(panel(page)).toHaveCount(0);
+ // The button is a calm, full 44 px row.
+ expect((await open.boundingBox())!.height).toBeGreaterThanOrEqual(44);
+ await open.tap();
+ await expect(panel(page)).toHaveAttribute("data-shell", "bottom");
+ } else {
+ await page.mouse.move(x, y);
+ await page.mouse.click(x, y);
+ await expect(panel(page)).toHaveAttribute("data-shell", "docked");
+ }
+ await expect(page).toHaveURL(/[?&]day=\d{4}-\d{2}-\d{2}/);
+ await expect(page.locator('[data-slot="day-view"]')).toBeVisible();
+}
+
+test.describe("every chart drawn in days opens its days", () => {
+ test.use({ storageState: DAY_DOORS_STORAGE_STATE_PATH });
+
+ test.beforeEach(async ({ page, context }, testInfo) => {
+ const baseURL = testInfo.project.use.baseURL ?? "http://localhost:3000";
+ await context.addCookies([
+ { name: "healthlog-locale", value: "en", url: baseURL },
+ ]);
+ await mockDay(page, { index: "full" });
+ });
+
+ test("recovery: a point opens its day, and the open day is marked", async ({
+ page,
+ }, testInfo) => {
+ if (!isPhone(testInfo)) {
+ await page.setViewportSize({ width: 1440, height: 900 });
+ }
+ await page.goto("/insights/recovery");
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await expect(plot).toBeVisible();
+ // Under the chart: the caption and the row of day dots, which draws the
+ // days the index names, one of them ringed as notable.
+ const rug = page.locator('[data-slot="day-rug"]').first();
+ await expect(
+ page.locator('[data-slot="chart-day-caption"]').first(),
+ ).toBeVisible();
+ await expect(rug.locator("[data-day]").first()).toBeAttached();
+ await expect(rug.locator('[data-notable="true"]')).toHaveCount(1);
+
+ await openFromPlot(page, plot, testInfo);
+ const day = await page
+ .locator('[data-slot="day-view"]')
+ .getAttribute("data-day");
+ // The value the person came from heads the day.
+ await expect(page.locator('[data-slot="day-focus"]')).toBeVisible();
+ // The open day's dot is the filled one.
+ await expect(rug.locator(`[data-day="${day}"]`)).toHaveAttribute(
+ "data-open",
+ "true",
+ );
+ });
+
+ test("recovery: the data table's dates are the keyboard way to a day", async ({
+ page,
+ }, testInfo) => {
+ test.skip(isPhone(testInfo), "keyboard path");
+ await page.goto("/insights/recovery");
+ const toggle = page
+ .locator('[data-slot="chart-data-table-toggle"]')
+ .first();
+ await toggle.scrollIntoViewIfNeeded();
+ await toggle.focus();
+ await page.keyboard.press("Enter");
+ const link = page
+ .locator('[data-slot="chart-data-table-region"] [data-slot="day-link"]')
+ .first();
+ await link.focus();
+ const day = await link.getAttribute("data-day");
+ await page.keyboard.press("Enter");
+ await expect(page.locator('[data-slot="day-view"]')).toHaveAttribute(
+ "data-day",
+ day!,
+ );
+ // Escape closes the day and gives the keyboard back to the date.
+ await page.keyboard.press("Escape");
+ await expect(panel(page)).toHaveCount(0);
+ });
+
+ test("sleep: a night's point opens its day", async ({ page }, testInfo) => {
+ await page.goto("/insights/sleep");
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await expect(plot).toBeVisible();
+ await openFromPlot(page, plot, testInfo);
+ });
+
+ test("the mood calendar: a logged day's cell opens it", async ({
+ page,
+ }, testInfo) => {
+ await page.goto("/insights/mood");
+ // A logged, openable cell: it carries the pointer cursor.
+ const cell = page.locator("rect.cursor-pointer[data-day]").last();
+ await cell.scrollIntoViewIfNeeded();
+ await expect(cell).toBeVisible();
+ const day = await cell.getAttribute("data-day");
+ if (isPhone(testInfo)) {
+ await cell.tap();
+ const open = page.locator(
+ '[data-slot="heatmap-tooltip"] [data-slot="chart-tooltip-open-day"]',
+ );
+ await expect(open).toBeVisible();
+ await expect(panel(page)).toHaveCount(0);
+ await open.tap();
+ await expect(panel(page)).toHaveAttribute("data-shell", "bottom");
+ } else {
+ await cell.click();
+ }
+ await expect(page.locator('[data-slot="day-view"]')).toHaveAttribute(
+ "data-day",
+ day!,
+ );
+ // The open day's cell is outlined.
+ await expect(page.locator('[data-slot="heatmap-open-day"]')).toHaveCount(1);
+ });
+
+ test("a lab marker's reading opens the day it was taken", async ({
+ page,
+ }, testInfo) => {
+ await page.goto("/labs");
+ await page
+ .locator('[data-slot="lab-list-analyte"]')
+ .filter({ hasText: DAY_DOORS_ANALYTE })
+ .first()
+ .click();
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await expect(plot).toBeVisible();
+ await openFromPlot(page, plot, testInfo);
+ // The reading on top, with the one before it beside it.
+ await expect(page.locator('[data-slot="day-focus"]')).toBeVisible();
+ });
+
+ test("a chart with its comparison period on still opens its days", async ({
+ page,
+ }, testInfo) => {
+ await page.goto("/insights/weight");
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await expect(plot).toBeVisible();
+ await page
+ .locator('[data-slot="chart-overlay-controls-trigger"]')
+ .first()
+ .click();
+ await page
+ .locator('[data-slot="chart-overlay-comparison-lastMonth"]')
+ .click();
+ await page.keyboard.press("Escape");
+ // The overlay menu is closed before the chart is touched, so the tap
+ // lands on the chart and not on the menu's outside-dismiss.
+ await expect(
+ page.locator('[data-slot="chart-overlay-controls-content"]'),
+ ).toHaveCount(0);
+ await expect(
+ page.locator('[data-slot="chart-compare-caption"]').first(),
+ ).toBeAttached();
+ await openFromPlot(page, plot, testInfo);
+ await expect(page.locator('[data-slot="day-focus"]')).toBeVisible();
+ });
+});
+
+test.describe("the dashboard and the list of all values", () => {
+ test.use({ storageState: DAY_DOORS_STORAGE_STATE_PATH });
+
+ test.beforeEach(async ({ page, context }, testInfo) => {
+ const baseURL = testInfo.project.use.baseURL ?? "http://localhost:3000";
+ await context.addCookies([
+ { name: "healthlog-locale", value: "en", url: baseURL },
+ ]);
+ await mockDay(page, { index: "full" });
+ });
+
+ test("a dashboard chart opens its day; the today hero offers none", async ({
+ page,
+ }, testInfo) => {
+ if (!isPhone(testInfo)) {
+ await page.setViewportSize({ width: 1440, height: 900 });
+ }
+ await page.goto("/");
+ await expect(
+ page.locator(
+ '[data-slot^="today-hero"] [data-slot="day-link"], [data-slot^="today-hero"] [data-day-links="true"]',
+ ),
+ ).toHaveCount(0);
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await expect(plot).toBeVisible({ timeout: 20_000 });
+ await openFromPlot(page, plot, testInfo);
+ // Closing leaves the dashboard on today.
+ await page.locator('[data-slot="day-close"]').click();
+ await expect(panel(page)).toHaveCount(0);
+ await expect(page).toHaveURL(/\/$/);
+ });
+
+ test("a date in a metric's list of all values opens its day", async ({
+ page,
+ }, testInfo) => {
+ await page.goto("/insights/values/WEIGHT");
+ const link = page.locator('[data-slot="day-link"]:visible').first();
+ await expect(link).toBeVisible();
+ const day = await link.getAttribute("data-day");
+ if (isPhone(testInfo)) await link.tap();
+ else await link.click();
+ await expect(page.locator('[data-slot="day-view"]')).toHaveAttribute(
+ "data-day",
+ day!,
+ );
+ });
+
+ test("the docked day moves the Coach button off its footer", async ({
+ page,
+ }, testInfo) => {
+ test.skip(isPhone(testInfo), "docked from 1280 px");
+ await page.setViewportSize({ width: 1440, height: 900 });
+ // The launcher follows the `coach` capability, which needs a provider
+ // the suite cannot reach, so the capability reads available here; this
+ // journey is about where the button sits, not what it opens.
+ await serveAiBlock(page, aiBlockAvailable());
+ await page.goto("/insights/weight");
+ const fab = page.locator('[data-slot="coach-fab"]');
+ await expect(fab).toBeVisible();
+ const plot = page
+ .locator('[data-slot="chart-plot"][data-day-links="true"]')
+ .first();
+ await openFromPlot(page, plot, testInfo);
+ const panelBox = (await panel(page).boundingBox())!;
+ // Wait out the 150 ms move, then the launcher sits left of the column.
+ await expect
+ .poll(async () => {
+ const b = (await fab.boundingBox())!;
+ return b.x + b.width;
+ })
+ .toBeLessThanOrEqual(panelBox.x);
+ });
+});
+
+test.describe("the readiness link into a medication's edit form", () => {
+ test.use({ storageState: MOBILE_ROUTES_STORAGE_STATE_PATH });
+
+ test("?edit=1 opens the medication's edit form and leaves the URL", async ({
+ page,
+ }) => {
+ const res = await page.request.get("/api/medications");
+ const body = (await res.json()) as {
+ data: Array<{ id: string }> | { medications?: Array<{ id: string }> };
+ };
+ const list = Array.isArray(body.data)
+ ? body.data
+ : (body.data.medications ?? []);
+ expect(list.length).toBeGreaterThan(0);
+ await page.goto(`/medications/${list[0]!.id}?edit=1`);
+ await expect(page.getByRole("dialog")).toBeVisible();
+ // A reload after closing the form must not open it again.
+ await expect(page).not.toHaveURL(/[?&]edit=1/);
+ });
+});
diff --git a/e2e/day-view.spec.ts b/e2e/day-view.spec.ts
index b0439aec8..6a04b16f0 100644
--- a/e2e/day-view.spec.ts
+++ b/e2e/day-view.spec.ts
@@ -1,5 +1,6 @@
-import type { Page, Route } from "@playwright/test";
+import type { Page } from "@playwright/test";
+import { mockDay } from "./setup/day-mock";
import { expect, test } from "./setup/test";
import { MOBILE_ROUTES_STORAGE_STATE_PATH } from "./setup/global-setup";
import { MOBILE_ROUTES_ANALYTE } from "./setup/mobile-routes-fixture";
@@ -20,97 +21,13 @@ import { MOBILE_ROUTES_ANALYTE } from "./setup/mobile-routes-fixture";
* - `?day=` opens the layer on any page, Back and Escape close it, a date in
* the future is dropped;
* - stepping to the neighbouring days never adds history entries;
- * - the dashboard's today area offers no door.
+ * - the dashboard's today area offers no door; its charts below do.
*
* Stable data attributes only: `day-panel` (+ `data-shell`), `day-link`,
* `chart-plot[data-day-links]`, `chart-tooltip-open-day`, `day-prev` /
* `day-next` / `day-close`.
*/
-function dayFixture(date: string) {
- return {
- date,
- tz: "Europe/Berlin",
- counts: { values: 2, entries: 1 },
- running: [
- {
- kind: "illness",
- section: "illness",
- id: "ep1",
- title: "Common cold",
- sub: null,
- since: date,
- until: null,
- dayIndex: 1,
- dayCount: null,
- href: "/illness",
- },
- ],
- values: [
- {
- type: "BLOOD_PRESSURE_SYS",
- value: 124,
- unit: "mmHg",
- at: `${date}T07:00:00.000Z`,
- source: "MANUAL",
- band: { lo: 118, hi: 128, n: 20 },
- },
- {
- type: "BLOOD_PRESSURE_DIA",
- value: 79,
- unit: "mmHg",
- at: `${date}T07:00:00.000Z`,
- source: "MANUAL",
- band: { lo: 76, hi: 82, n: 20 },
- },
- ],
- events: [
- {
- at: `${date}T07:00:00.000Z`,
- kind: "mood",
- section: "mood",
- id: "m1",
- title: "Mood: good",
- meta: null,
- note: null,
- docs: [],
- href: "/mood",
- },
- ],
- notable: [],
- sections: {},
- };
-}
-
-async function mockDay(page: Page) {
- await page.route("**/api/day/**", async (route: Route) => {
- const url = new URL(route.request().url());
- if (url.pathname === "/api/day/index") {
- const from = url.searchParams.get("from") ?? "";
- await route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify({
- data: {
- from,
- to: url.searchParams.get("to") ?? "",
- days: {},
- notable: [],
- },
- error: null,
- }),
- });
- return;
- }
- const date = url.pathname.split("/").pop() ?? "";
- await route.fulfill({
- status: 200,
- contentType: "application/json",
- body: JSON.stringify({ data: dayFixture(date), error: null }),
- });
- });
-}
-
const panel = (page: Page) => page.locator('[data-slot="day-panel"]');
function isoDaysAgo(days: number): string {
@@ -252,6 +169,8 @@ test.describe("the day view", () => {
await open.tap();
await expect(panel(page)).toBeVisible();
await expect(panel(page)).toHaveAttribute("data-shell", "bottom");
+ // The tapped value heads the day.
+ await expect(page.locator('[data-slot="day-focus"]')).toBeVisible();
});
test("the dashboard's today area offers no day door", async ({ page }) => {
@@ -259,8 +178,15 @@ test.describe("the day view", () => {
await expect(
page.locator('[data-slot="main-content-wrapper"]'),
).toBeVisible();
+ // The hero is today: nothing in it opens another day. (The charts
+ // further down do; `day-doors.spec.ts` walks one.)
await expect(
- page.locator('[data-slot="chart-plot"][data-day-links="true"]'),
+ page.locator('[data-slot^="today-hero"]').first(),
+ ).toBeVisible();
+ await expect(
+ page.locator(
+ '[data-slot^="today-hero"] [data-slot="day-link"], [data-slot^="today-hero"] [data-day-links="true"]',
+ ),
).toHaveCount(0);
});
});
diff --git a/e2e/setup/day-doors-fixture.ts b/e2e/setup/day-doors-fixture.ts
new file mode 100644
index 000000000..ddc7b5382
--- /dev/null
+++ b/e2e/setup/day-doors-fixture.ts
@@ -0,0 +1,90 @@
+/**
+ * The record `day-doors.spec.ts` opens days from.
+ *
+ * Every chart the journey clicks needs points to click: ten days of the
+ * autonomic charge (the recovery page), of sleep and of mood (the sleep
+ * chart, the mood line and the mood calendar), weight over the last ten days
+ * and the same ten days a month earlier (the comparison chart draws a prior
+ * period only where one exists), and two readings of one lab marker.
+ *
+ * Written through the app's own routes, once, from `globalSetup`. An account
+ * that already holds the lab marker is taken as seeded, so a local re-run
+ * against a reused database does not double every row.
+ */
+import { request as playwrightRequest } from "@playwright/test";
+
+export const DAY_DOORS_ANALYTE = "Ferritin";
+
+export async function seedDayDoorsRecord(
+ baseURL: string,
+ storageStatePath: string,
+): Promise {
+ const ctx = await playwrightRequest.newContext({
+ baseURL,
+ storageState: storageStatePath,
+ });
+ try {
+ const labs = await ctx.get("/api/labs");
+ const body = (await labs.json()) as { data: unknown };
+ if (JSON.stringify(body.data ?? null).includes(DAY_DOORS_ANALYTE)) return;
+
+ const post = async (path: string, data: unknown): Promise => {
+ const res = await ctx.post(path, { data });
+ if (res.status() === 409 || res.ok()) return;
+ throw new Error(
+ `[day-doors-fixture] ${path} answered ${res.status()}: ${(await res.text()).slice(0, 200)}`,
+ );
+ };
+ const daysAgo = (days: number, hour = 8) => {
+ const at = new Date(Date.now() - days * 86_400_000);
+ at.setUTCHours(hour, 0, 0, 0);
+ return at.toISOString();
+ };
+
+ for (let day = 1; day <= 10; day += 1) {
+ await post("/api/measurements", {
+ type: "ANS_CHARGE",
+ value: 5 + day,
+ measuredAt: daysAgo(day, 5),
+ });
+ await post("/api/measurements", {
+ type: "SLEEP_DURATION",
+ value: 400 + day * 4,
+ measuredAt: daysAgo(day, 6),
+ });
+ await post("/api/measurements", {
+ type: "WEIGHT",
+ value: 72 + day / 10,
+ measuredAt: daysAgo(day, 7),
+ });
+ // The same ten days, a month before: the prior period the comparison
+ // draws beside them.
+ await post("/api/measurements", {
+ type: "WEIGHT",
+ value: 73 + day / 10,
+ measuredAt: daysAgo(day + 30, 7),
+ });
+ await post("/api/mood-entries", {
+ mood: day % 2 ? "GUT" : "OKAY",
+ moodLoggedAt: daysAgo(day, 19),
+ });
+ }
+
+ for (const [days, value] of [
+ [60, 41],
+ [4, 58],
+ ] as const) {
+ await post("/api/labs", {
+ analyte: DAY_DOORS_ANALYTE,
+ panel: "Eisenstoffwechsel",
+ value,
+ unit: "ng/mL",
+ referenceLow: 30,
+ referenceHigh: 300,
+ takenAt: daysAgo(days),
+ });
+ }
+ } finally {
+ await ctx.dispose();
+ }
+}
diff --git a/e2e/setup/day-mock.ts b/e2e/setup/day-mock.ts
new file mode 100644
index 000000000..cde790c4d
--- /dev/null
+++ b/e2e/setup/day-mock.ts
@@ -0,0 +1,115 @@
+/**
+ * The day routes, answered in the contract's shape.
+ *
+ * The day itself (`GET /api/day/{date}`) and the index (`GET /api/day/index`)
+ * are route mocks, so a journey pins the client: which door opens which day,
+ * what the history does, where no door is. The server's own answers are
+ * pinned by the integration suite.
+ */
+import type { Page, Route } from "@playwright/test";
+
+function dayFixture(date: string) {
+ return {
+ date,
+ tz: "Europe/Berlin",
+ counts: { values: 2, entries: 1 },
+ running: [
+ {
+ kind: "illness",
+ section: "illness",
+ id: "ep1",
+ title: "Common cold",
+ sub: null,
+ since: date,
+ until: null,
+ dayIndex: 1,
+ dayCount: null,
+ href: "/illness",
+ },
+ ],
+ values: [
+ {
+ type: "BLOOD_PRESSURE_SYS",
+ value: 124,
+ unit: "mmHg",
+ at: `${date}T07:00:00.000Z`,
+ source: "MANUAL",
+ band: { lo: 118, hi: 128, n: 20 },
+ },
+ {
+ type: "BLOOD_PRESSURE_DIA",
+ value: 79,
+ unit: "mmHg",
+ at: `${date}T07:00:00.000Z`,
+ source: "MANUAL",
+ band: { lo: 76, hi: 82, n: 20 },
+ },
+ ],
+ events: [
+ {
+ at: `${date}T07:00:00.000Z`,
+ kind: "mood",
+ section: "mood",
+ id: "m1",
+ title: "Mood: good",
+ meta: null,
+ note: null,
+ docs: [],
+ href: "/mood",
+ },
+ ],
+ notable: [],
+ sections: {},
+ };
+}
+
+/**
+ * Every day from `from` to `to`, each holding values: what the row of day
+ * dots under a chart reads when the whole window has entries.
+ */
+function everyDay(from: string, to: string): Record {
+ const days: Record = {};
+ if (!from || !to) return days;
+ const at = new Date(`${from}T12:00:00.000Z`);
+ const end = new Date(`${to}T12:00:00.000Z`);
+ while (at <= end) {
+ days[at.toISOString().slice(0, 10)] = ["values"];
+ at.setUTCDate(at.getUTCDate() + 1);
+ }
+ return days;
+}
+
+export async function mockDay(
+ page: Page,
+ options: { index?: "empty" | "full" } = {},
+) {
+ await page.route("**/api/day/**", async (route: Route) => {
+ const url = new URL(route.request().url());
+ if (url.pathname === "/api/day/index") {
+ const from = url.searchParams.get("from") ?? "";
+ const to = url.searchParams.get("to") ?? "";
+ const days = options.index === "full" ? everyDay(from, to) : {};
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ data: {
+ from,
+ to,
+ days,
+ // The first day of the window stands out: the rug draws a ring.
+ notable: Object.keys(days).slice(0, 1),
+ },
+ error: null,
+ }),
+ });
+ return;
+ }
+ const date = url.pathname.split("/").pop() ?? "";
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ data: dayFixture(date), error: null }),
+ });
+ });
+}
diff --git a/e2e/setup/global-setup.ts b/e2e/setup/global-setup.ts
index 2b0b6d675..f3ed47952 100644
--- a/e2e/setup/global-setup.ts
+++ b/e2e/setup/global-setup.ts
@@ -33,6 +33,7 @@ import {
} from "@playwright/test";
import pg from "pg";
+import { seedDayDoorsRecord } from "./day-doors-fixture";
import { seedMobileRoutesRecord } from "./mobile-routes-fixture";
// Resolve relative to the project root rather than __dirname/import.meta.url —
@@ -249,6 +250,26 @@ export const TIMELINE_STORAGE_STATE_PATH = resolve(
"e2e/setup/storageStateTimeline.json",
);
+/**
+ * The day-doors journey's own account (`day-doors.spec.ts`).
+ *
+ * It turns a chart's comparison overlay on, which is a per-account
+ * preference; on a shared account a parallel spec would find its chart
+ * drawing a prior period it never asked for. Its record carries the series
+ * the journey clicks (recovery, sleep, mood, weight, a lab marker).
+ */
+export const E2E_DAY_DOORS = {
+ email: "e2e-day-doors@healthlog.test",
+ username: "e2e-day-doors",
+ password: "Dy4!Rk8wQm2vTz6P",
+ role: "USER",
+} as const;
+
+export const DAY_DOORS_STORAGE_STATE_PATH = resolve(
+ process.cwd(),
+ "e2e/setup/storageStateDayDoors.json",
+);
+
export const AI_OPTIONAL_STORAGE_STATE_PATH = resolve(
process.cwd(),
"e2e/setup/storageStateAiOptional.json",
@@ -950,6 +971,30 @@ export default async function globalSetup(config: FullConfig): Promise {
],
);
+ // The day-doors journey's account. Every module the journey reaches is
+ // on; its record is written after the login capture.
+ await pool.query(
+ `INSERT INTO users
+ (id, username, email, password_hash, role, created_at, updated_at,
+ onboarding_completed_at, onboarding_tour_completed,
+ module_preferences_json)
+ VALUES ($1, $2, $3, $4, 'USER', $5, $5, $5, true, NULL)
+ ON CONFLICT (username) DO UPDATE SET
+ email = EXCLUDED.email,
+ password_hash = EXCLUDED.password_hash,
+ updated_at = EXCLUDED.updated_at,
+ onboarding_completed_at = EXCLUDED.onboarding_completed_at,
+ onboarding_tour_completed = EXCLUDED.onboarding_tour_completed,
+ module_preferences_json = NULL`,
+ [
+ cuid(),
+ E2E_DAY_DOORS.username,
+ E2E_DAY_DOORS.email,
+ await hashPassword(E2E_DAY_DOORS.password),
+ now,
+ ],
+ );
+
// The notification-dispatch journey's account. Seeded like the others;
// its channels, devices, ledger rows and preferences are reset by
// `e2e/setup/notification-fixture.ts` before every test, because the
@@ -1556,6 +1601,10 @@ export default async function globalSetup(config: FullConfig): Promise {
// The timeline journey's jar — see `E2E_TIMELINE`.
await capture(E2E_TIMELINE, TIMELINE_STORAGE_STATE_PATH);
+ // The day-doors journey's jar, then its record — see `E2E_DAY_DOORS`.
+ await capture(E2E_DAY_DOORS, DAY_DOORS_STORAGE_STATE_PATH);
+ await seedDayDoorsRecord(baseURL, DAY_DOORS_STORAGE_STATE_PATH);
+
await capture(E2E_SCOPE_DELEGATE, SCOPE_DELEGATE_STORAGE_STATE_PATH);
await capture(E2E_SCOPE_DELEGATE, SCOPE_A11Y_STORAGE_STATE_PATH);
await capture(E2E_SCOPE_DELEGATE, SCOPE_CAPABILITIES_STORAGE_STATE_PATH);
diff --git a/messages/de.json b/messages/de.json
index 625afb001..b9b9399de 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Zeitleiste",
"askCoachPrompt": "Was war am {date}?",
"chartHintTouch": "Antippen zeigt den Wert.",
+ "chartHintBar": "Klick auf einen Balken öffnet den Tag.",
+ "chartHintTouchBar": "Antippen zeigt die Werte.",
+ "chartHintCell": "Klick auf einen Tag öffnet ihn.",
+ "chartHintTouchCell": "Antippen zeigt den Wert des Tages.",
"coachChips": "Tage in dieser Antwort",
"description": "Alles, was deine Einträge für diesen Tag enthalten.",
"openDocument": "Dokument öffnen",
diff --git a/messages/en.json b/messages/en.json
index c8a52c09a..7efb7a78b 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Timeline",
"askCoachPrompt": "What happened on {date}?",
"chartHintTouch": "Tap a point to see its value.",
+ "chartHintBar": "Click a bar to open its day.",
+ "chartHintTouchBar": "Tap a bar to see its values.",
+ "chartHintCell": "Click a day to open it.",
+ "chartHintTouchCell": "Tap a day to see its value.",
"coachChips": "Days in this answer",
"description": "Everything your records hold for this day.",
"openDocument": "Open document",
diff --git a/messages/es.json b/messages/es.json
index 238bb72f4..e38b9e1a8 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Cronología",
"askCoachPrompt": "¿Qué pasó el {date}?",
"chartHintTouch": "Toca un punto para ver su valor.",
+ "chartHintBar": "Haz clic en una barra para abrir su día.",
+ "chartHintTouchBar": "Toca una barra para ver sus valores.",
+ "chartHintCell": "Haz clic en un día para abrirlo.",
+ "chartHintTouchCell": "Toca un día para ver su valor.",
"coachChips": "Días en esta respuesta",
"description": "Todo lo que tus registros contienen para este día.",
"openDocument": "Abrir documento",
diff --git a/messages/fr.json b/messages/fr.json
index 0fd018599..9070b5fdc 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Chronologie",
"askCoachPrompt": "Que s’est-il passé le {date} ?",
"chartHintTouch": "Touchez un point pour voir sa valeur.",
+ "chartHintBar": "Cliquez sur une barre pour ouvrir son jour.",
+ "chartHintTouchBar": "Touchez une barre pour voir ses valeurs.",
+ "chartHintCell": "Cliquez sur un jour pour l’ouvrir.",
+ "chartHintTouchCell": "Touchez un jour pour voir sa valeur.",
"coachChips": "Jours dans cette réponse",
"description": "Tout ce que vos entrées contiennent pour ce jour.",
"openDocument": "Ouvrir le document",
diff --git a/messages/it.json b/messages/it.json
index 582cd2e10..7da2126a2 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Cronologia",
"askCoachPrompt": "Cosa è successo il {date}?",
"chartHintTouch": "Tocca un punto per vederne il valore.",
+ "chartHintBar": "Fai clic su una barra per aprire il suo giorno.",
+ "chartHintTouchBar": "Tocca una barra per vederne i valori.",
+ "chartHintCell": "Fai clic su un giorno per aprirlo.",
+ "chartHintTouchCell": "Tocca un giorno per vederne il valore.",
"coachChips": "Giorni in questa risposta",
"description": "Tutto ciò che le tue voci contengono per questo giorno.",
"openDocument": "Apri documento",
diff --git a/messages/ko.json b/messages/ko.json
index 3fc16b737..ccd0eb935 100644
--- a/messages/ko.json
+++ b/messages/ko.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "타임라인",
"askCoachPrompt": "{date}에 무슨 일이 있었나요?",
"chartHintTouch": "점을 탭하면 값이 보여요.",
+ "chartHintBar": "막대를 클릭하면 그날이 열려요.",
+ "chartHintTouchBar": "막대를 탭하면 값이 보여요.",
+ "chartHintCell": "날짜 칸을 클릭하면 그날이 열려요.",
+ "chartHintTouchCell": "날짜 칸을 탭하면 값이 보여요.",
"coachChips": "이 답변에 쓰인 날",
"description": "이 날에 대한 모든 기록이에요.",
"openDocument": "문서 열기",
diff --git a/messages/pl.json b/messages/pl.json
index f9487fb8f..032c99b02 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -12202,6 +12202,10 @@
"inTimelineShort": "Oś czasu",
"askCoachPrompt": "Co się działo {date}?",
"chartHintTouch": "Dotknij punktu, aby zobaczyć wartość.",
+ "chartHintBar": "Kliknij słupek, aby otworzyć jego dzień.",
+ "chartHintTouchBar": "Dotknij słupka, aby zobaczyć wartości.",
+ "chartHintCell": "Kliknij dzień, aby go otworzyć.",
+ "chartHintTouchCell": "Dotknij dnia, aby zobaczyć jego wartość.",
"coachChips": "Dni w tej odpowiedzi",
"description": "Wszystko, co Twoje wpisy zawierają dla tego dnia.",
"openDocument": "Otwórz dokument",
diff --git a/src/app/insights/mood/page.tsx b/src/app/insights/mood/page.tsx
index 50886b099..f6af7cf94 100644
--- a/src/app/insights/mood/page.tsx
+++ b/src/app/insights/mood/page.tsx
@@ -148,7 +148,7 @@ export default function InsightsStimmungPage() {
MeasurementType series, so the period-over-period range read
(`/api/analytics/range`, keyed on a MeasurementType enum) has
nothing to aggregate. */}
-
+
diff --git a/src/app/page-client.tsx b/src/app/page-client.tsx
index dbc186d1a..615e5214c 100644
--- a/src/app/page-client.tsx
+++ b/src/app/page-client.tsx
@@ -1693,6 +1693,7 @@ export default function DashboardPageClient({
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
valueScale={unitDisplay.transformFor("WEIGHT").factor}
+ dayLinks
/>
),
});
@@ -1746,6 +1747,7 @@ export default function DashboardPageClient({
},
]}
compareBaseline={compareBaseline}
+ dayLinks
/>
),
});
@@ -1772,6 +1774,7 @@ export default function DashboardPageClient({
targetZones={bpTargetZones}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
@@ -1800,6 +1803,7 @@ export default function DashboardPageClient({
valueBands={hasRestingHr ? pulseBands : undefined}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
@@ -1824,6 +1828,7 @@ export default function DashboardPageClient({
valueBands={bodyFatBands}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
@@ -1840,6 +1845,7 @@ export default function DashboardPageClient({
onDataReady={() => markChartReady("mood-chart")}
compareBaseline={compareBaseline}
chartKey="mood"
+ dayLinks
/>
),
});
@@ -1861,6 +1867,7 @@ export default function DashboardPageClient({
unit="h"
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
@@ -1883,6 +1890,7 @@ export default function DashboardPageClient({
colors={["var(--success)"]}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
@@ -1903,6 +1911,7 @@ export default function DashboardPageClient({
onDataReady={() => markChartReady("medications")}
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
+ dayLinks
/>
),
});
diff --git a/src/components/charts/__tests__/compliance-heatmap-a11y.test.tsx b/src/components/charts/__tests__/compliance-heatmap-a11y.test.tsx
index 28ea8a862..bf5459336 100644
--- a/src/components/charts/__tests__/compliance-heatmap-a11y.test.tsx
+++ b/src/components/charts/__tests__/compliance-heatmap-a11y.test.tsx
@@ -7,11 +7,13 @@ import { ComplianceHeatmap } from "../compliance-heatmap";
/**
* 2026-07-17 a11y audit (M2) — medication-compliance heatmap day cells are
* pointer-only SVG ``s. The keyboard/screen-reader path to the
- * per-day values is a visually-hidden day list beside the grid, not
- * focusable rects (a cell subtree nested under the SVG's `role="img"` is
- * pruned from the a11y tree, and per-cell tab stops would flood the
- * keyboard order). This pins that list plus the aggregate `role="img"`
- * summary, and that the rects stay a pure pointer affordance.
+ * per-day values is the data table under the grid (v1.42: the same
+ * `ChartDataTable` every day-linked chart carries, collapsed until asked
+ * for), not focusable rects (a cell subtree nested under the SVG's
+ * `role="img"` is pruned from the a11y tree, and per-cell tab stops would
+ * flood the keyboard order). This pins that table, each row's date as a link
+ * to its day, the aggregate `role="img"` summary, and that the rects stay a
+ * pure pointer affordance.
*/
// The grid window is the last `days` days ending today, so seed relative
// dates (UTC-sliced, matching the component) rather than fixed ones that
@@ -50,18 +52,19 @@ describe(" — keyboard-reachable day values", () => {
}
});
- it("exposes each active day through a visually-hidden day list", () => {
+ it("exposes each active day, and its day, through the data table", () => {
const html = render();
- // The sr-only list carries one entry per day that had a scheduled or
- // taken dose — here the two seeded days.
- const listMatch = html.match(
- /
]*>/g) ?? [];
- expect(items.length).toBe(2);
- // Each entry pairs the day with its taken/expected + rate string.
- expect(listMatch![1]).toContain("2/2 (100%)");
- expect(listMatch![1]).toContain("1/2 (50%)");
+ expect(table).not.toBeNull();
+ // One row per day that had a scheduled or taken dose — the two seeded.
+ const rows = table![1].match(/data-slot="chart-data-table-row"/g) ?? [];
+ expect(rows.length).toBe(2);
+ // Taken, expected and the rate, per day.
+ expect(table![1]).toContain("100 %");
+ expect(table![1]).toContain("50 %");
+ expect(table![1]).toContain(`data-day="${D0}"`);
+ expect(table![1]).toContain(`data-day="${D1}"`);
});
});
diff --git a/src/components/charts/__tests__/mood-heatmap-a11y.test.tsx b/src/components/charts/__tests__/mood-heatmap-a11y.test.tsx
index 938254e8c..2ae560edd 100644
--- a/src/components/charts/__tests__/mood-heatmap-a11y.test.tsx
+++ b/src/components/charts/__tests__/mood-heatmap-a11y.test.tsx
@@ -7,11 +7,12 @@ import { MoodHeatmap } from "../mood-heatmap";
/**
* 2026-07-17 a11y audit (M2) — mood heatmap day cells are pointer-only SVG
* ``s. The keyboard/screen-reader path to the per-day values is a
- * visually-hidden day list beside the grid, not focusable rects (a cell
- * subtree nested under the SVG's `role="img"` is pruned from the a11y
- * tree, and per-cell tab stops would flood the keyboard order). This pins
- * that list plus the aggregate `role="img"` summary, and that the rects
- * stay a pure pointer affordance.
+ * the data table under the grid (v1.42: the same `ChartDataTable` every
+ * day-linked chart carries, collapsed until asked for), not focusable rects
+ * (a cell subtree nested under the SVG's `role="img"` is pruned from the
+ * a11y tree, and per-cell tab stops would flood the keyboard order). This
+ * pins that table, each row's date as a link to its day, the aggregate
+ * `role="img"` summary, and that the rects stay a pure pointer affordance.
*/
// The grid window is the last `days` days ending today, so seed relative
// dates (UTC-sliced, matching the component) rather than fixed ones that
@@ -50,16 +51,20 @@ describe(" — keyboard-reachable day values", () => {
}
});
- it("exposes each logged day through a visually-hidden day list", () => {
+ it("exposes each logged day, and its day, through the data table", () => {
const html = render();
- const listMatch = html.match(
- /
]*>/g) ?? [];
- // One entry per logged day — the two seeded days, not every cell.
- expect(items.length).toBe(2);
- expect(listMatch![1]).toContain("4.2");
- expect(listMatch![1]).toContain("2.0");
+ expect(table).not.toBeNull();
+ const rows = table![1].match(/data-slot="chart-data-table-row"/g) ?? [];
+ // One row per logged day — the two seeded days, not every cell.
+ expect(rows.length).toBe(2);
+ expect(table![1]).toContain("4.2");
+ expect(table![1]).toContain("2.0");
+ // Each date opens its day: the keyboard way to the day a click opens.
+ expect(table![1]).toContain(`data-day="${D0}"`);
+ expect(table![1]).toContain(`data-day="${D1}"`);
+ expect(table![1]).toMatch(/data-slot="day-link"/);
});
});
diff --git a/src/components/charts/chart-data-table.tsx b/src/components/charts/chart-data-table.tsx
index 185d00dae..57cf248a5 100644
--- a/src/components/charts/chart-data-table.tsx
+++ b/src/components/charts/chart-data-table.tsx
@@ -63,6 +63,11 @@ export interface ChartDataTableColumn {
key: string;
/** Resolved column label, from the chart's own series-label helper. */
label: string;
+ /**
+ * The column's own formatter, where its values are not the chart's (a
+ * count beside a rate). Defaults to the table's `formatValue`.
+ */
+ format?: (value: number) => string;
}
export interface ChartDataTableProps {
@@ -186,8 +191,13 @@ export function ChartDataTable({
- {rows.map((point) => (
-
+ {rows.map((point, index) => (
+ // Two readings can share a day (a list of entries, not of
+ // days), so the timestamp alone is not a key.
+
{/* The date is the row's header, so a screen reader reads
"12 July, systolic 128" rather than a bare number. */}
>
) : (
- formatValue(numeric)
+ (column.format ?? formatValue)(numeric)
)}
);
diff --git a/src/components/charts/compliance-heatmap.tsx b/src/components/charts/compliance-heatmap.tsx
index fa9ad89af..67bad9159 100644
--- a/src/components/charts/compliance-heatmap.tsx
+++ b/src/components/charts/compliance-heatmap.tsx
@@ -1,9 +1,11 @@
"use client";
-import { openDay } from "@/components/day/day-layer-controller";
-import { isOpenableDay } from "@/components/day/day-url";
-import { useTodayKey } from "@/components/day/use-today-key";
+import { ChartDayCaption } from "@/components/day/chart-day";
+import { dayAnchor } from "@/components/day/chart-day-links";
+import { OPEN_DAY_CELL, useHeatmapDay } from "@/components/day/heatmap-day";
import { useCalendarDate } from "@/hooks/use-calendar-date";
+import { dateOnlyKey } from "@/lib/tz/date-only";
+import { ChartDataTable } from "./chart-data-table";
import { useState, useMemo, useEffect, useRef } from "react";
import { useDisplayTimezone, useTranslations } from "@/lib/i18n/context";
import { heatmapDays } from "@/lib/charts/heatmap-days";
@@ -90,59 +92,10 @@ export function ComplianceHeatmap({
const formatDay = useCalendarDate();
const containerRef = useRef(null);
const [containerWidth, setContainerWidth] = useState(0);
- const [tooltip, setTooltip] = useState<{
- x: number;
- y: number;
- text: string;
- /**
- * v1.4.27 MB7 / CF-10 — when `pinned` the tooltip stays mounted
- * across `onPointerLeave` so a touch user sees the per-cell
- * breakdown after lifting their finger. Mouse + pen users get the
- * existing hover-only experience because their interactions never
- * set `pinned`. A second tap on a different cell repositions the
- * tooltip; a tap outside any cell clears it (wired below).
- */
- pinned?: boolean;
- /** v1.42 — the day a pinned (touch) tooltip offers to open. */
- day?: string;
- } | null>(null);
- // v1.42 — a click opens the day on a fine pointer; a tap pins the tooltip,
- // which then offers the day. The pointer type of the press decides.
- const lastPointer = useRef("mouse");
- const today = useTodayKey();
-
- // v1.4.27 MB7 / CF-10 — outside-click dismisses a pinned tooltip so a
- // touch user can clear the per-cell detail without scrolling the
- // pinned label off-screen. The listener is gated on `tooltip?.pinned`
- // so the non-touch hover flow never pays the indirection cost.
- useEffect(() => {
- if (!tooltip?.pinned) return;
- const handlePointer = (event: PointerEvent) => {
- const container = containerRef.current;
- if (!container) return;
- if (!container.contains(event.target as Node)) {
- setTooltip(null);
- }
- };
- document.addEventListener("pointerdown", handlePointer, true);
- return () => {
- document.removeEventListener("pointerdown", handlePointer, true);
- };
- }, [tooltip?.pinned]);
-
- // 2026-07-17 a11y audit (M2) — Escape dismisses any open tooltip
- // (pinned touch tooltip or keyboard-focus tooltip), matching 1.4.13's
- // "dismissible" requirement.
- useEffect(() => {
- if (!tooltip) return;
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === "Escape") setTooltip(null);
- };
- document.addEventListener("keydown", handleKeyDown);
- return () => {
- document.removeEventListener("keydown", handleKeyDown);
- };
- }, [tooltip]);
+ // v1.42 — the cells are doors to their days, the same doors every chart
+ // has: a click (fine pointer), the pinned tooltip's button (touch), a
+ // dashed outline on the open day, and the data table for the keyboard.
+ const heatmapDay = useHeatmapDay(containerRef);
const WEEKDAY_LABELS = [
t("charts.weekdays.mon"),
@@ -262,9 +215,8 @@ export function ComplianceHeatmap({
const svgWidth = labelWidth + weeks * cellSize + Math.max(0, weeks - 1) * GAP;
const svgHeight = headerHeight + 7 * cellSize + 6 * GAP;
- // Per-day text alternative, shared by the pointer tooltip and the
- // visually-hidden day list below the grid (M2). One source of truth so
- // the sr-only list never drifts from what a pointer user reads.
+ // Per-day text for the pointer tooltip; the data table below the grid
+ // carries each active day's rate (M2).
const describeCell = (cell: (typeof cells)[number]): string => {
const rate =
cell.data.expected > 0
@@ -282,8 +234,8 @@ export function ComplianceHeatmap({
: "";
return `${formatDay(cell.dateKey)}: ${cell.data.taken}/${cell.data.expected} (${rate}%)${timingInfo}`;
};
- // Only days that carried a scheduled or taken dose go into the sr-only
- // list; empty days are covered by the aggregate summary on the SVG.
+ // Only days that carried a scheduled or taken dose go into the data
+ // table; empty days are covered by the aggregate summary on the SVG.
const activeCells = cells.filter(
(cell) => cell.data.expected > 0 || cell.data.taken > 0,
);
@@ -313,9 +265,7 @@ export function ComplianceHeatmap({
// off `containerWidth`, so a full window still fills the row) rather
// than CSS-stretching ~5 columns of capped cells into wide rectangles.
className={stretch ? "block max-w-full" : "block"}
- onMouseLeave={() =>
- setTooltip((prev) => (prev?.pinned ? prev : null))
- }
+ {...heatmapDay.svgProps}
>
{/* Month labels */}
{monthMarkers.map((m, i) => (
@@ -354,114 +304,47 @@ export function ComplianceHeatmap({
users tap the cell to pin and tap outside (or another
cell) to move/clear. `pointerType === "touch"` discriminates
so a hover dismiss never wipes a pinned tooltip. */}
- {cells.map((cell) => {
- const buildText = (): string => describeCell(cell);
- return (
+ {cells.map((cell) => (
+ 0 || cell.data.taken > 0,
+ describe: () => describeCell(cell),
+ })}
+ />
+ ))}
+ {cells
+ .filter((cell) => cell.dateKey === heatmapDay.openKey)
+ .map((cell) => (
{
- // Touch enter fires synthetically immediately before
- // `pointerdown`; skip it so the pinned tooltip below
- // takes precedence with its real coordinates.
- if (e.pointerType === "touch") return;
- setTooltip({
- x: e.clientX,
- y: e.clientY,
- text: buildText(),
- });
- }}
- onPointerLeave={(e) => {
- if (e.pointerType === "touch") return;
- setTooltip((prev) => (prev?.pinned ? prev : null));
- }}
- onPointerDown={(e) => {
- lastPointer.current = e.pointerType;
- if (e.pointerType !== "touch") return;
- setTooltip({
- x: e.clientX,
- y: e.clientY,
- text: buildText(),
- pinned: true,
- day:
- cell.data.expected > 0 &&
- isOpenableDay(cell.dateKey, today)
- ? cell.dateKey
- : undefined,
- });
- }}
- onClick={() => {
- if (lastPointer.current === "touch") return;
- if (cell.data.expected === 0) return;
- if (!isOpenableDay(cell.dateKey, today)) return;
- setTooltip(null);
- openDay(cell.dateKey, { trigger: containerRef.current });
- }}
+ key={`open-${cell.dateKey}`}
+ data-slot="heatmap-open-day"
+ x={labelWidth + cell.col * step - 1.5}
+ y={headerHeight + cell.row * step - 1.5}
+ width={cellSize + 3}
+ height={cellSize + 3}
+ rx={3}
+ pointerEvents="none"
+ {...OPEN_DAY_CELL}
/>
- );
- })}
+ ))}
- {/* 2026-07-17 a11y audit (M2) — visually-hidden per-day list. The SVG
- carries an aggregate `role="img"` summary; this list is the
- keyboard/screen-reader path to the same granular values the pointer
- tooltip shows, without adding a tab stop per cell. */}
- {activeCells.length > 0 && (
-
+ ({ timestamp: p.t }))}
+ axis="time"
+ // The margin (4) + the y axis (40) on the left, the margin (14)
+ // on the right.
+ insetLeft={4 + 40}
+ insetRight={14}
+ />
+ ({
+ date: dateOnlyKey(new Date(p.t)),
+ timestamp: p.t,
+ temp: p.temp,
+ }))}
+ columns={[{ key: "temp", label: t("cycle.bbt.title") }]}
+ unit={unitDisplay.unitFor("BODY_TEMPERATURE")}
+ formatValue={(value) => fmt.number(value)}
+ formatDate={(date) => fmt.dateShortSmartCalendar(date)}
+ bucket="day"
+ metricLabel={t("cycle.bbt.title")}
+ dayLinks
+ />
>
)}
@@ -317,6 +387,8 @@ function PhaseDot(props: { cx?: number; cy?: number; payload?: BbtPoint }) {
export function BbtTooltip(props: {
active?: boolean;
payload?: { payload: BbtPoint }[];
+ /** v1.42 — the tooltip's way to the day on a touch screen. */
+ action?: ReactNode;
}) {
const { t } = useTranslations();
const fmt = useFormatters();
@@ -350,6 +422,7 @@ export function BbtTooltip(props: {
{t(`cycle.ovulationTest.${p.ovulationTest}`)}
) : null}
+ {props.action ?? null}
);
}
diff --git a/src/components/dashboard/environment-chip.tsx b/src/components/dashboard/environment-chip.tsx
index 81323ed0c..61383b8f5 100644
--- a/src/components/dashboard/environment-chip.tsx
+++ b/src/components/dashboard/environment-chip.tsx
@@ -20,6 +20,11 @@ import { useQuery } from "@tanstack/react-query";
import { CloudSun } from "lucide-react";
import { TagChip } from "@/components/ui/tag-chip";
+import {
+ DAY_LINK_SLOT,
+ DayLink,
+ withDayLinkSlot,
+} from "@/components/day/day-link";
import { useAuth } from "@/hooks/use-auth";
import { apiGet } from "@/lib/api/api-fetch";
import {
@@ -91,7 +96,14 @@ export function EnvironmentChip() {
>
- {t("environment.chip.day", { date })}
+ {/* v1.42 — the date opens the day it names, the one thing every
+ date in the app does. */}
+ {withDayLinkSlot(
+ t("environment.chip.day", { date: DAY_LINK_SLOT }),
+
+ {date}
+ ,
+ )}
{flags.map((flag) => (
diff --git a/src/components/day/__tests__/chart-day.test.ts b/src/components/day/__tests__/chart-day.test.ts
index b19380d7d..127921512 100644
--- a/src/components/day/__tests__/chart-day.test.ts
+++ b/src/components/day/__tests__/chart-day.test.ts
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vitest";
-import { chartPointDayKey, rugPosition } from "../chart-day";
+import { chartPointDayKey, rugFraction, rugPosition } from "../chart-day";
import { daysFromCoachSteps } from "../coach-day-chips";
-import { pickPreparationDays } from "../since-last-visit";
+import { preparationRows } from "../since-last-visit";
import type { CoachStep } from "@/lib/ai/coach/types";
const noon = (key: string) => Date.parse(`${key}T12:00:00.000Z`);
@@ -74,20 +74,81 @@ describe("Coach day chips", () => {
});
describe("visit preparation", () => {
- it("reads notable days first, then context days, newest kept, in date order", () => {
- const days = pickPreparationDays(
+ const spell = {
+ notableTitle: () => "Blood pressure",
+ notableText: () => "Highest daily value since March",
+ countMeta: (count: number) => (count > 1 ? `${count} entries` : null),
+ };
+
+ it("lists every change the server names, a dose change on a quiet day included", () => {
+ const rows = preparationRows(
{
- days: {
- "2026-08-03": ["medications", "values"],
- "2026-08-19": ["illness", "values"],
- "2026-09-14": ["labs"],
- "2026-09-20": ["values", "mood"],
- },
- notable: ["2026-09-02"],
+ changes: [
+ {
+ date: "2026-08-03",
+ kind: "doseChange",
+ section: "medications",
+ id: "d1",
+ title: "Ramipril 5 mg",
+ count: 1,
+ href: null,
+ },
+ {
+ date: "2026-09-14",
+ kind: "labResult",
+ section: "labs",
+ id: "l1",
+ title: "Lab results",
+ count: 4,
+ href: null,
+ },
+ ],
+ observations: [
+ {
+ date: "2026-09-02",
+ kind: "extremeHigh",
+ type: "BLOOD_PRESSURE_SYS",
+ params: { value: 152 },
+ },
+ // A first reading says nothing about the stretch since the visit.
+ {
+ date: "2026-08-20",
+ kind: "firstValue",
+ type: "WEIGHT",
+ params: {},
+ },
+ ],
},
- 3,
+ spell,
+ );
+ expect(rows.map((row) => [row.date, row.title, row.meta])).toEqual([
+ ["2026-08-03", "Ramipril 5 mg", null],
+ ["2026-09-02", "Blood pressure", "Highest daily value since March"],
+ ["2026-09-14", "Lab results", "4 entries"],
+ ]);
+ });
+});
+
+describe("rug placement per axis", () => {
+ const points = [
+ { timestamp: noon("2026-01-01") },
+ { timestamp: noon("2026-01-02") },
+ { timestamp: noon("2026-01-05") },
+ ];
+
+ it("spreads an index axis edge to edge, a band axis at band centres", () => {
+ expect(rugFraction("2026-01-01", points, "index")).toBe(0);
+ expect(rugFraction("2026-01-05", points, "index")).toBe(1);
+ expect(rugFraction("2026-01-01", points, "band")).toBeCloseTo(1 / 6);
+ expect(rugFraction("2026-01-05", points, "band")).toBeCloseTo(5 / 6);
+ });
+
+ it("places a day on a time axis by its date, not by its neighbours", () => {
+ // Day 3 of a 4-day span: three quarters along, although it sits between
+ // the second and third point by index.
+ expect(rugFraction("2026-01-04", points, "time")).toBeCloseTo(0.75);
+ expect(rugFraction("2026-01-04", points, "index")).toBeCloseTo(
+ (1 + 2 / 3) / 2,
);
- // A day with only values and mood is not a context change.
- expect(days).toEqual(["2026-08-19", "2026-09-02", "2026-09-14"]);
});
});
diff --git a/src/components/day/__tests__/day-door-coverage-guard.test.ts b/src/components/day/__tests__/day-door-coverage-guard.test.ts
new file mode 100644
index 000000000..68dd8f2ac
--- /dev/null
+++ b/src/components/day/__tests__/day-door-coverage-guard.test.ts
@@ -0,0 +1,271 @@
+import { readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+/**
+ * Every chart drawn in days is a door to its days, or it says why not.
+ *
+ * The day view arrived on six metric pages and nowhere else, and the recovery
+ * page beside them offered no day at all: nothing noticed, because every check
+ * proved one chart. This guard walks `src/app` and `src/components` and holds
+ * three kinds of surface to the same doors (a click opens the day, on touch
+ * the tooltip's "View the whole day", the dashed line through the open day,
+ * the row of day dots, the caption):
+ *
+ * A. a mount of a chart whose doors are a prop (`HealthChart`, its dynamic
+ * wrapper, `MoodChart`, the adherence chart, the nutrient bar chart)
+ * passes `dayLinks`, or is
+ * a tile's `mini` chart (never a door, by the primitive's contract), or
+ * forwards its props unchanged (a lazy wrapper);
+ * B. a file that draws its own Recharts chart over a date axis (an
+ * `` keyed on a date-shaped field, or `scale="time"`) calls
+ * `useChartDayLinks` and renders its parts (`ChartDayFooter`,
+ * `OPEN_DAY_LINE`, the tooltip's props and its touch action);
+ * C. a calendar heatmap (anything laid out by `heatmapDays`) calls
+ * `useHeatmapDay`.
+ *
+ * A surface that must not open a day stands on `NOT_HERE` with its reason,
+ * the integration plan's §1.2 list made concrete. An entry that no longer
+ * names a chart fails, so the list cannot rot into a silent allowlist.
+ *
+ * The matcher's limits, stated so nobody mistakes green for complete:
+ * - a hand-rolled SVG chart that does not use `heatmapDays` (the cycle
+ * history bars, the lab list's sparkline, the timeline) is invisible;
+ * - a date carried on an axis under another key (`label`, `x`) slips rule
+ * B; `DATE_AXIS_KEYS` is the closed set it knows;
+ * - a new component that wraps `HealthChart` under another name slips rule
+ * A until it is added to `PROP_GATED`;
+ * - `dayLinks={someFlag}` counts as on: the guard reads the source, not
+ * the value at run time.
+ * The floors at the bottom fail an empty match set, so a matcher that stops
+ * matching cannot pass by finding nothing.
+ */
+
+const ROOT = join(__dirname, "..", "..", "..", "..");
+const SCAN = ["src/app", "src/components"];
+
+/** Charts whose doors are switched on per mount. */
+const PROP_GATED = [
+ "HealthChart",
+ "HealthChartDynamic",
+ "MoodChart",
+ "MedicationComplianceChart",
+ "NutrientDailyBarChart",
+ "NutrientDailyBarChartDynamic",
+] as const;
+
+/** `` values that mean the axis runs over days or instants. */
+const DATE_AXIS_KEYS = [
+ "date",
+ "day",
+ "dayKey",
+ "dayOffset",
+ "timestamp",
+ "t",
+ "pointIndex",
+] as const;
+
+/**
+ * Where a chart deliberately opens no day. Path (a file) → why.
+ * The integration plan's §1.2 and its table are the source of each reason.
+ */
+const NOT_HERE: Record = {
+ "src/components/insights/coach-panel/chat-bubble.tsx":
+ "A Coach answer reaches its days through the chips built from the tool calls (`CoachDayChips`), never from what the answer draws or writes.",
+ "src/components/insights/coach-panel/result-chart.tsx":
+ "Same as the Coach answer: the result table's days arrive as tool-derived chips, and a period row may be a month with no single day.",
+ "src/components/medications/drug-level-chart.tsx":
+ "A modelled estimate, not a record: every point is computed, none was measured. The doses it is drawn from open their days in the intake history.",
+ "src/components/charts/scatter-correlation-chart.tsx":
+ "A pairing of two values per day with no date axis; the pairs carry no date to open.",
+ "src/components/admin/host-metrics-chart.tsx":
+ "The server's own resource use, not a health record.",
+};
+
+function walk(path: string): string[] {
+ const abs = join(ROOT, path);
+ if (statSync(abs).isFile()) return [abs];
+ return readdirSync(abs).flatMap((name) => {
+ if (name === "__tests__" || name === "ui") return [];
+ return walk(join(path, name));
+ });
+}
+
+const files = SCAN.flatMap(walk).filter((f) => /\.tsx?$/.test(f));
+const rel = (abs: string) => relative(ROOT, abs);
+/**
+ * The code without its comments: a docblock that names `` is
+ * not a mount. Block comments (JSX ones included) go whole; a line comment
+ * goes from `//` to the line end unless the slashes follow a colon (a URL).
+ */
+export function stripComments(text: string): string {
+ return text
+ .replace(/\/\*[\s\S]*?\*\//g, "")
+ .replace(/(^|[^:"'`])\/\/.*$/gm, "$1");
+}
+
+const source = new Map(
+ files.map((f) => [rel(f), stripComments(readFileSync(f, "utf8"))]),
+);
+
+/**
+ * The text of every JSX opening tag named `name` in `text`: from `` that closes it at brace depth zero, so an arrow function or a
+ * comparison inside a prop does not end the tag early.
+ */
+export function jsxTags(text: string, name: string): string[] {
+ const out: string[] = [];
+ const opener = new RegExp(`<${name}(?=[\\s/>])`, "g");
+ let match: RegExpExecArray | null;
+ while ((match = opener.exec(text)) !== null) {
+ let depth = 0;
+ let quote: string | null = null;
+ let i = match.index + match[0].length;
+ for (; i < text.length; i += 1) {
+ const c = text[i]!;
+ if (quote) {
+ if (c === quote && text[i - 1] !== "\\") quote = null;
+ continue;
+ }
+ if (c === '"' || c === "'" || c === "`") quote = c;
+ else if (c === "{") depth += 1;
+ else if (c === "}") depth -= 1;
+ else if (c === ">" && depth === 0) break;
+ }
+ out.push(text.slice(match.index, i + 1));
+ }
+ return out;
+}
+
+/** True when a prop-gated mount opens its days. */
+function mountOpensDays(tag: string): boolean {
+ return /\bdayLinks\b(?!\s*=\s*\{\s*false\s*\})/.test(tag);
+}
+
+function isDateAxis(tag: string): boolean {
+ if (/scale="time"/.test(tag)) return true;
+ const key = tag.match(/dataKey="([^"]+)"/)?.[1];
+ return (
+ key !== undefined && (DATE_AXIS_KEYS as readonly string[]).includes(key)
+ );
+}
+
+interface Finding {
+ file: string;
+ why: string;
+}
+
+function findMissingDoors(): {
+ missing: Finding[];
+ doors: {
+ mounts: number;
+ charts: number;
+ chartFiles: string[];
+ heatmaps: number;
+ };
+} {
+ const missing: Finding[] = [];
+ const doors = {
+ mounts: 0,
+ charts: 0,
+ chartFiles: [] as string[],
+ heatmaps: 0,
+ };
+ for (const [file, text] of source) {
+ const listed = file in NOT_HERE;
+
+ // A. prop-gated mounts.
+ for (const name of PROP_GATED) {
+ for (const tag of jsxTags(text, name)) {
+ if (/\{\s*\.\.\.props\s*\}/.test(tag)) continue; // a lazy wrapper
+ if (/\bmini\b/.test(tag)) continue; // a tile's sparkline
+ if (mountOpensDays(tag)) {
+ doors.mounts += 1;
+ continue;
+ }
+ if (!listed) missing.push({ file, why: `<${name}> without dayLinks` });
+ }
+ }
+
+ // B. a Recharts chart over a date axis, drawn in this file.
+ if (/from\s+["']recharts["']/.test(text)) {
+ const dated = jsxTags(text, "XAxis").some(isDateAxis);
+ if (dated) {
+ const wired =
+ /\buseChartDayLinks\(/.test(text) &&
+ /\bChartDayFooter\b/.test(text) &&
+ /\bOPEN_DAY_LINE\b/.test(text) &&
+ /\.tooltipProps\b/.test(text) &&
+ /\.tooltipAction\(/.test(text);
+ if (wired) {
+ doors.charts += 1;
+ doors.chartFiles.push(file);
+ } else if (!listed) {
+ missing.push({
+ file,
+ why: "a date-axis chart without the shared day doors (useChartDayLinks, ChartDayFooter, OPEN_DAY_LINE, tooltip props and touch action)",
+ });
+ }
+ }
+ }
+
+ // C. a calendar heatmap.
+ if (/\bheatmapDays\(/.test(text) && !file.startsWith("src/lib/")) {
+ if (/\buseHeatmapDay\(/.test(text)) doors.heatmaps += 1;
+ else if (!listed) {
+ missing.push({ file, why: "a calendar heatmap without useHeatmapDay" });
+ }
+ }
+ }
+ return { missing, doors };
+}
+
+describe("every chart drawn in days opens its days, or says why not", () => {
+ const { missing, doors } = findMissingDoors();
+
+ it("finds no date-axis chart, heatmap or chart mount without the day doors", () => {
+ expect(missing).toEqual([]);
+ });
+
+ it("still finds the doors it is meant to find (an empty match set fails)", () => {
+ // HealthChart on the metric pages (two mounts in the HealthKit page),
+ // blood pressure, weight, pulse, BMI, recovery, sleep, the mood line,
+ // water and caffeine; on the dashboard its seven charts, the mood line
+ // and the adherence chart.
+ expect(doors.mounts).toBeGreaterThanOrEqual(20);
+ // HealthChart, the mood line and the nutrient bars themselves, sleep
+ // stages, mood dimensions, lab marker, custom metric, questionnaire,
+ // basal temperature, dose strength, efficacy, the adherence chart:
+ // twelve.
+ expect(
+ doors.chartFiles.length,
+ doors.chartFiles.join("\n"),
+ ).toBeGreaterThanOrEqual(12);
+ // The mood and the intake calendars.
+ expect(doors.heatmaps).toBeGreaterThanOrEqual(2);
+ });
+
+ it("every NOT_HERE entry names an existing chart and gives a reason", () => {
+ for (const [file, reason] of Object.entries(NOT_HERE)) {
+ const text = source.get(file);
+ expect(text, `${file} is listed but does not exist`).toBeDefined();
+ const charts =
+ /from\s+["']recharts["']/.test(text!) ||
+ PROP_GATED.some((name) => jsxTags(text!, name).length > 0);
+ expect(charts, `${file} is listed but draws no chart`).toBe(true);
+ expect(reason.length).toBeGreaterThan(30);
+ }
+ });
+
+ it("reads a JSX tag to its real end, past arrow functions in its props", () => {
+ const [tag] = jsxTags(
+ ` s > 1} dayLinks />`,
+ "HealthChart",
+ );
+ expect(tag).toContain("dayLinks");
+ expect(mountOpensDays("")).toBe(false);
+ expect(isDateAxis('')).toBe(true);
+ expect(isDateAxis('')).toBe(false);
+ });
+});
diff --git a/src/components/day/__tests__/day-not-here-guard.test.ts b/src/components/day/__tests__/day-not-here-guard.test.ts
index 3b42f1a4c..bb4037924 100644
--- a/src/components/day/__tests__/day-not-here-guard.test.ts
+++ b/src/components/day/__tests__/day-not-here-guard.test.ts
@@ -7,9 +7,12 @@ import { describe, expect, it } from "vitest";
* Where a date must NOT open the day (integration plan §1.2), frozen.
*
* - the dashboard's today area: the dashboard is today; past days open as
- * a layer over it, never as date navigation inside it;
- * - a tile's mini chart: too small a target, and the tile has its own
- * destination (the chart side is pinned in `health-chart-day-links`);
+ * a layer over it, never as date navigation inside it. The dashboard's
+ * charts below it do open their days (the maintainer's call on the
+ * beta), like every chart drawn in days (`day-door-coverage-guard`);
+ * - a trend card: it shows the latest value and a direction, no day, and
+ * the whole tile leads to its metric page (the mini-chart side is
+ * pinned in `health-chart-day-links`);
* - the cycle calendar: a tap there has meant "log this day" for years;
* - model-written text (the briefing, the Coach's prose): never parsed for
* dates; the Coach's days come from its tool calls as chips;
@@ -64,11 +67,14 @@ describe("the day view stays out of the surfaces it must not reach", () => {
expect(offenders.map((f) => relative(ROOT, f))).toEqual([]);
});
- it("the dashboard's charts never ask for day links", () => {
+ it("the dashboard's today area hands no day door to its hero", () => {
+ // The charts below the hero open their days; the hero itself is today
+ // and stays on the list above. Pinned from the other side: the hero is
+ // still mounted by the dashboard, so the list entry is not stale.
const dashboard = readFileSync(
join(ROOT, "src/app/page-client.tsx"),
"utf8",
);
- expect(dashboard).not.toMatch(/\bdayLinks\b/);
+ expect(dashboard).toMatch(/ ({
useDay: () => ({ ...dayQuery, refetch: () => undefined }),
+ usePrefetchDay: () => () => undefined,
}));
vi.mock("next/navigation", () => ({ usePathname: () => pathname }));
vi.mock("@/hooks/use-auth", () => ({
diff --git a/src/components/day/__tests__/use-day-value-format.test.tsx b/src/components/day/__tests__/use-day-value-format.test.tsx
new file mode 100644
index 000000000..7fbca9381
--- /dev/null
+++ b/src/components/day/__tests__/use-day-value-format.test.tsx
@@ -0,0 +1,77 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import deMessages from "../../../../messages/de.json";
+import enMessages from "../../../../messages/en.json";
+
+/**
+ * A day's values read as their charts read them. The day route sends a
+ * night's length in "min" and a device score in "score"; the first read as a
+ * bare 412 and the second as an untranslated "score" before both were
+ * spelled the way the sleep and recovery charts spell them.
+ */
+
+vi.mock("@/hooks/use-unit-display", async () => {
+ const { unitDisplayFor } =
+ await import("@/__tests__/helpers/unit-display-mock");
+ return { useUnitDisplay: () => unitDisplayFor("metric") };
+});
+
+import { I18nProvider } from "@/lib/i18n/context";
+
+import { useDayValueFormat } from "../use-day-value-format";
+
+function Probe({
+ type,
+ value,
+ unit,
+}: {
+ type: string;
+ value: number;
+ unit: string;
+}) {
+ const { formatTile } = useDayValueFormat();
+ const shown = formatTile({
+ key: type,
+ values: [{ type, value, unit, at: "", source: "", band: null }],
+ });
+ return (
+
+ {shown.value}|{shown.unit}
+
+ );
+}
+
+function read(
+ type: string,
+ value: number,
+ unit: string,
+ locale: "en" | "de" = "en",
+) {
+ return renderToStaticMarkup(
+
+
+ ,
+ )
+ .replace(/<[^>]+>/g, "")
+ .replace(//g, "");
+}
+
+describe("a day's values in their charts' spelling", () => {
+ it("reads a night sent in min as a duration", () => {
+ const [value, unit] = read("SLEEP_DURATION", 412, "min").split("|");
+ expect(value).toMatch(/6\s*h/);
+ expect(value).toMatch(/52/);
+ expect(unit).toBe("");
+ });
+
+ it("reads a device score in the reader's word for points", () => {
+ // German, where the wire's "score" and the chart's "Punkte" differ.
+ const [value, unit] = read("ANS_CHARGE", 8, "score", "de").split("|");
+ expect(value).toBe("8");
+ expect(unit).toBe("Punkte");
+ });
+});
diff --git a/src/components/day/chart-day-links.tsx b/src/components/day/chart-day-links.tsx
new file mode 100644
index 000000000..7e645b155
--- /dev/null
+++ b/src/components/day/chart-day-links.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { useCallback, useMemo, useRef, type ReactNode } from "react";
+
+import type { DateKey } from "@/lib/day/contract";
+import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
+
+import {
+ ChartDayCaption,
+ DayRug,
+ TooltipDayAction,
+ useCoarsePointer,
+ type ChartDayAxis,
+ type ChartDayMark,
+} from "./chart-day";
+import { openDay, useOpenDay, type DayFocus } from "./day-layer-controller";
+import { isOpenableDay } from "./day-url";
+import { useTodayKey } from "./use-today-key";
+
+/**
+ * The day view's doors on any Recharts chart drawn in days, in one place.
+ *
+ * `HealthChart` was the first chart to open its days; every other chart with
+ * a date axis (the sleep stages, a lab marker, the mood line, a bar per day)
+ * takes the same doors through this hook, so a click, a tap, the tooltip's
+ * button, the dashed line through the open day and the row of dots under the
+ * axis behave the same on every page:
+ *
+ * - fine pointer: a click on the plot opens the day of the point under the
+ * cursor; hovering shows the tooltip as before;
+ * - touch: a tap shows the value and pins the tooltip, whose button
+ * ("View the whole day", a calm 44 px row) opens the day. Two steps on
+ * purpose (the maintainer's call, after trying one on the beta): a
+ * point is a small target, and one tap that opened a sheet would open
+ * days by accident;
+ * - the open day is marked with `OPEN_DAY_LINE` (a dashed vertical line)
+ * at `openIndex`;
+ * - `ChartDayFooter` draws the row of day dots and the one-line caption.
+ *
+ * The caller says, per drawn point and in data order, which calendar day the
+ * point stands for, or `null` when it stands for none (a week or month
+ * average, a synthetic "now" point, a day with nothing on it). A day in the
+ * future never opens.
+ */
+
+/** The props of the dashed line through the open day, for ``. */
+export const OPEN_DAY_LINE = {
+ stroke: "var(--muted-foreground)",
+ strokeDasharray: "3 3",
+ strokeOpacity: 0.7,
+ ifOverflow: "discard",
+} as const;
+
+/** What a chart's click handler receives from Recharts. */
+interface ChartClickState {
+ activeTooltipIndex?: unknown;
+ activeLabel?: unknown;
+}
+
+export interface ChartDayLinksOptions {
+ /** Off for a mini chart, a coarse bucket, or a surface on the NOT-here list. */
+ enabled: boolean;
+ /** Per drawn point, in data order: its calendar day, or null. */
+ days: ReadonlyArray;
+ /** What the day shows at its top when opened from point `index`. */
+ focusFor?: (index: number) => Omit | null;
+ /**
+ * For a chart whose plotted series are not the chart's `data` (several
+ * `` arrays on one time axis): the point index of the click's
+ * x value. Defaults to Recharts' `activeTooltipIndex`.
+ */
+ indexOfClick?: (state: ChartClickState) => number | null;
+}
+
+export interface ChartDayLinks {
+ active: boolean;
+ coarse: boolean;
+ /** Index of the open day's point, for the dashed line. */
+ openIndex: number | undefined;
+ /** The open day itself, for charts that mark it by value. */
+ openDay: DateKey | null;
+ /** Open the day of point `index` (no-op without a day). */
+ open: (index: number) => void;
+ /** True when point `index` has a day that opens. */
+ canOpen: (index: number) => boolean;
+ /** Spread on the element around ``. */
+ plotProps: {
+ ref: React.RefObject;
+ "data-day-links"?: "true";
+ };
+ /** Class for the same element: a pointer cursor on a fine pointer. */
+ plotClassName: string;
+ /** Pass as the Recharts chart's `onClick`. */
+ onChartClick:
+ ((state: ChartClickState | null | undefined) => void) | undefined;
+ /**
+ * Spread on ``: on touch it stays where the tap put it and takes
+ * taps. It does not glide there either: Recharts slides the tooltip from
+ * where it last was for 400 ms, which turned "View the whole day" into a
+ * moving target under the finger. Reduced motion stops the glide on every
+ * pointer.
+ */
+ tooltipProps: {
+ trigger: "click" | "hover";
+ wrapperStyle?: React.CSSProperties;
+ isAnimationActive?: boolean;
+ };
+ /** The tooltip's button for point `index`, on a touch screen only. */
+ tooltipAction: (index: number | undefined) => ReactNode | undefined;
+}
+
+export function useChartDayLinks({
+ enabled,
+ days,
+ focusFor,
+ indexOfClick,
+}: ChartDayLinksOptions): ChartDayLinks {
+ const coarse = useCoarsePointer();
+ const openKey = useOpenDay();
+ const today = useTodayKey();
+ const plotRef = useRef(null);
+
+ const canOpen = useCallback(
+ (index: number) => enabled && isOpenableDay(days[index] ?? null, today),
+ [enabled, days, today],
+ );
+
+ const open = useCallback(
+ (index: number) => {
+ if (!canOpen(index)) return;
+ const date = days[index] as DateKey;
+ const focus = focusFor?.(index) ?? null;
+ openDay(date, {
+ focus: focus ? { ...focus, date } : null,
+ trigger: plotRef.current,
+ });
+ },
+ [canOpen, days, focusFor],
+ );
+
+ const openIndex = useMemo(() => {
+ if (!enabled || openKey === null) return undefined;
+ const at = days.lastIndexOf(openKey);
+ return at === -1 ? undefined : at;
+ }, [enabled, openKey, days]);
+
+ const onChartClick =
+ enabled && !coarse
+ ? (state: ChartClickState | null | undefined) => {
+ if (!state) return;
+ const index = indexOfClick
+ ? indexOfClick(state)
+ : Number(state.activeTooltipIndex);
+ if (index === null || !Number.isInteger(index)) return;
+ open(index);
+ }
+ : undefined;
+
+ return {
+ active: enabled,
+ coarse,
+ openIndex,
+ openDay: enabled ? openKey : null,
+ open,
+ canOpen,
+ plotProps: {
+ ref: plotRef,
+ "data-day-links": enabled ? "true" : undefined,
+ },
+ plotClassName: enabled && !coarse ? "cursor-pointer" : "",
+ onChartClick,
+ tooltipProps:
+ enabled && coarse
+ ? {
+ trigger: "click",
+ wrapperStyle: { pointerEvents: "auto", zIndex: 20 },
+ isAnimationActive: false,
+ }
+ : prefersReducedMotion()
+ ? { trigger: "hover", isAnimationActive: false }
+ : { trigger: "hover" },
+ tooltipAction: (index) =>
+ enabled && coarse && index !== undefined && canOpen(index) ? (
+ open(index)} />
+ ) : undefined,
+ };
+}
+
+/**
+ * The row of day dots and the caption under a day-linked chart. Nothing when
+ * the chart is not day-linked or draws no points.
+ */
+export function ChartDayFooter({
+ links,
+ points,
+ axis = "index",
+ insetLeft,
+ insetRight,
+ mark = "point",
+}: {
+ links: Pick;
+ /** The drawn points' noon-UTC day anchors (or instants), in data order. */
+ points: ReadonlyArray<{ timestamp: number }>;
+ axis?: ChartDayAxis;
+ insetLeft: number;
+ insetRight: number;
+ mark?: ChartDayMark;
+}) {
+ if (!links.active || points.length === 0) return null;
+ return (
+ <>
+
+
+ >
+ );
+}
+
+/** A day key's noon-UTC anchor, the timestamp a daily point is drawn at. */
+export function dayAnchor(day: DateKey): number {
+ return Date.parse(`${day}T12:00:00.000Z`);
+}
diff --git a/src/components/day/chart-day.tsx b/src/components/day/chart-day.tsx
index 7983a6604..460d3e746 100644
--- a/src/components/day/chart-day.tsx
+++ b/src/components/day/chart-day.tsx
@@ -8,7 +8,7 @@ import { dateOnlyKey } from "@/lib/tz/date-only";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
-import { openDay, useOpenDay, type DayFocus } from "./day-layer-controller";
+import { useOpenDay } from "./day-layer-controller";
import { isOpenableDay } from "./day-url";
import { useDayIndex } from "./use-day";
import { useTodayKey } from "./use-today-key";
@@ -19,8 +19,9 @@ import { useTodayKey } from "./use-today-key";
* - On a fine pointer, a click on the plot opens the day of the point under
* the cursor; hovering keeps showing the tooltip as before.
* - On a touch screen a tap shows the value, as it always did, and the
- * tooltip carries "View the whole day". Two steps on purpose: one tap
- * that opened a sheet would fire on every scroll that grazed the chart.
+ * tooltip carries "View the whole day". Two steps on purpose: a point is
+ * a small target, and one tap that opened a sheet would open days by
+ * accident. A date in a list is a bigger target and opens in one tap.
* - Under the axis, a quiet row of dots marks the days that hold anything,
* a ring the days with a notable observation. Decoration for the eye; the
* keyboard and screen-reader way to a day is the chart's data table.
@@ -59,19 +60,6 @@ export function chartPointDayKey(timestamp: number): DateKey {
return dateOnlyKey(new Date(timestamp));
}
-/** Open the day of a chart point, carrying the value as the day's focus. */
-export function openChartDay(
- timestamp: number,
- focus: Omit | null,
- trigger?: HTMLElement | null,
-): void {
- const date = chartPointDayKey(timestamp);
- openDay(date, {
- focus: focus ? { ...focus, date } : null,
- trigger: trigger ?? null,
- });
-}
-
/** The tooltip's way to the day on a touch screen. */
export function TooltipDayAction({ onOpen }: { onOpen: () => void }) {
const { t } = useTranslations();
@@ -119,19 +107,62 @@ export function rugPosition(
return points.length - 1;
}
+/**
+ * How a chart spreads its points along the x axis, which decides where a
+ * day's dot sits under it:
+ *
+ * - `index`: the axis is the point index, the first point at the left edge
+ * of the plot and the last at the right (`HealthChart`, the mood line, a
+ * category line chart);
+ * - `band`: one band per point, the point at the band's centre (a bar
+ * chart);
+ * - `time`: the axis is the timestamp itself, from the first point to the
+ * last (a lab chart, any `scale="time"` axis).
+ */
+export type ChartDayAxis = "index" | "band" | "time";
+
+/**
+ * Where along the plot (0 at the left edge, 1 at the right) a day's dot
+ * belongs, or null outside the drawn span.
+ */
+export function rugFraction(
+ day: DateKey,
+ points: readonly RugPoint[],
+ axis: ChartDayAxis,
+): number | null {
+ const at = rugPosition(day, points);
+ if (at === null) return null;
+ const n = points.length;
+ if (axis === "band") return (at + 0.5) / n;
+ if (n === 1) return 0.5;
+ if (axis === "time") {
+ const first = points[0]!.timestamp;
+ const last = points[n - 1]!.timestamp;
+ const t = Date.parse(`${day}T12:00:00.000Z`);
+ return last === first ? 0.5 : (t - first) / (last - first);
+ }
+ return at / (n - 1);
+}
+
/**
* The row of day dots under a daily chart. `insetLeft` / `insetRight` are the
* pixels between the chart box and the first and last point (margin, axis,
* padding), so a dot lands under its day.
+ *
+ * The row is always drawn at its full height, dots or not: the index that
+ * fills it arrives after the chart, and a row that appeared then would push
+ * everything under the chart down by its height.
*/
export function DayRug({
points,
insetLeft,
insetRight,
+ axis = "index",
}: {
points: readonly RugPoint[];
insetLeft: number;
insetRight: number;
+ axis?: ChartDayAxis;
}) {
const today = useTodayKey();
const open = useOpenDay();
@@ -141,18 +172,16 @@ export function DayRug({
const to = last ? chartPointDayKey(last.timestamp) : null;
const index = useDayIndex(from, to);
const data = index.data;
- if (!data?.days || points.length === 0) return null;
- const notable = new Set(data.notable ?? []);
- const maxIndex = Math.max(points.length - 1, 1);
- const days = Object.keys(data.days)
+ const notable = new Set(data?.notable ?? []);
+ const days = Object.keys(data?.days ?? {})
.filter((day) => isOpenableDay(day, today))
- .map((day) => ({ day, at: rugPosition(day, points) }))
+ .map((day) => ({ day, at: rugFraction(day, points, axis) }))
.filter((entry): entry is { day: string; at: number } => entry.at !== null);
- if (days.length === 0) return null;
return (
@@ -173,9 +202,7 @@ export function DayRug({
? "border-muted-foreground size-[7px] border-[1.5px]"
: "bg-muted-foreground/55 size-1",
)}
- style={{
- left: `${(points.length === 1 ? 0.5 : at / maxIndex) * 100}%`,
- }}
+ style={{ left: `${at * 100}%` }}
/>
);
})}
@@ -183,16 +210,40 @@ export function DayRug({
);
}
-/** The one line under a day-linked chart: what the dots mean, and the click. */
-export function ChartDayCaption({ coarse }: { coarse: boolean }) {
+/**
+ * What a day-linked surface is made of, which names the thing to click in
+ * the caption: a point on a line, a bar, or a cell of a calendar.
+ */
+export type ChartDayMark = "point" | "bar" | "cell";
+
+const HINT_KEYS: Record = {
+ point: { fine: "day.chartHint", coarse: "day.chartHintTouch" },
+ bar: { fine: "day.chartHintBar", coarse: "day.chartHintTouchBar" },
+ cell: { fine: "day.chartHintCell", coarse: "day.chartHintTouchCell" },
+};
+
+/**
+ * The one line under a day-linked chart: what the dots mean (when the chart
+ * has the row of dots), and the click.
+ */
+export function ChartDayCaption({
+ coarse,
+ mark = "point",
+ rug = true,
+}: {
+ coarse: boolean;
+ mark?: ChartDayMark;
+ rug?: boolean;
+}) {
const { t } = useTranslations();
+ const hint = HINT_KEYS[mark];
return (
);
}
diff --git a/src/components/day/day-layer-controller.ts b/src/components/day/day-layer-controller.ts
index d91ba729e..bb12eca77 100644
--- a/src/components/day/day-layer-controller.ts
+++ b/src/components/day/day-layer-controller.ts
@@ -51,9 +51,16 @@ interface LayerMemory {
trigger: HTMLElement | null;
/** The day the layer shows, as the mounted layer resolved it. */
open: DateKey | null;
+ /** The trigger's top edge on screen when it opened the layer. */
+ triggerTop: number | null;
}
-const memory: LayerMemory = { focus: null, trigger: null, open: null };
+const memory: LayerMemory = {
+ focus: null,
+ trigger: null,
+ open: null,
+ triggerTop: null,
+};
const listeners = new Set<() => void>();
function emit() {
@@ -95,6 +102,17 @@ export function publishOpenDay(date: DateKey | null): void {
emit();
}
+/**
+ * The element that opened the layer and where it stood on screen at that
+ * moment, without handing it over: the docked column keeps it there while
+ * the page beside it reflows.
+ */
+export function peekDayTriggerAt(): { el: HTMLElement; top: number } | null {
+ return memory.trigger && memory.triggerTop !== null
+ ? { el: memory.trigger, top: memory.triggerTop }
+ : null;
+}
+
/** The element focus returns to when the layer closes. */
export function takeDayTrigger(): HTMLElement | null {
const trigger = memory.trigger;
@@ -124,6 +142,9 @@ export function openDay(date: DateKey, options: OpenDayOptions = {}): void {
? active
: null;
memory.trigger = options.trigger ?? focused ?? memory.trigger;
+ memory.triggerTop = memory.trigger
+ ? memory.trigger.getBoundingClientRect().top
+ : null;
emit();
const { pathname, search } = currentLocation();
const href = withDayHref(pathname, search, date);
diff --git a/src/components/day/day-layer.tsx b/src/components/day/day-layer.tsx
index bb19ae540..7d6f39751 100644
--- a/src/components/day/day-layer.tsx
+++ b/src/components/day/day-layer.tsx
@@ -6,6 +6,7 @@ import {
useCallback,
useEffect,
useId,
+ useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
@@ -26,13 +27,15 @@ import { cn } from "@/lib/utils";
import {
closeDay,
+ peekDayTriggerAt,
publishOpenDay,
stepDay,
takeDayTrigger,
useDayFocus,
} from "./day-layer-controller";
-import { parseDayParam, withDayHref } from "./day-url";
+import { parseDayParam, shiftDateKey, withDayHref } from "./day-url";
import { DayView, useLongDayLabel } from "./day-view";
+import { usePrefetchDay } from "./use-day";
import { useTodayKey } from "./use-today-key";
/**
@@ -125,6 +128,12 @@ function DayLayer() {
? "docked"
: "sheet";
+ // The docked column narrows the page beside it, and the page reflows. Keep
+ // what opened the day where it was on screen, through the open and the
+ // close, so the chart under the pointer does not jump away from it.
+ useKeepAnchorInView(date !== null && shell === "docked");
+
+ const prefetchDay = usePrefetchDay();
const focus = useDayFocus(date);
const longLabel = useLongDayLabel();
const titleId = useId();
@@ -163,6 +172,13 @@ function DayLayer() {
if (date === null) return;
const onKey = (event: KeyboardEvent) => {
if (event.defaultPrevented) return;
+ // Alt is the first half of the step shortcut: read both neighbours
+ // while the arrow is still on its way, so the step paints a day.
+ if (event.key === "Alt") {
+ prefetchDay(shiftDateKey(date, -1));
+ if (date < today) prefetchDay(shiftDateKey(date, 1));
+ return;
+ }
const inside =
panelRef.current?.contains(event.target as Node | null) ?? false;
if (event.key === "Escape" && shell === "docked") {
@@ -184,7 +200,7 @@ function DayLayer() {
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
- }, [date, shell, onStep]);
+ }, [date, shell, onStep, prefetchDay, today]);
const live = (
{view(DockedTitle, {
headerClassName: cn(
@@ -254,6 +273,55 @@ function DayLayer() {
);
}
+/**
+ * Keep the element that opened the day at the same place on screen while the
+ * page beside the docked column reflows (the column taking or giving back its
+ * width). Chromium does this itself (CSS scroll anchoring); Safari does not,
+ * and there the chart the person clicked slid away under the pointer by the
+ * height the reflow added above it. Measured after layout, so where the
+ * browser already anchored, the correction is zero and nothing moves twice.
+ */
+function useKeepAnchorInView(active: boolean) {
+ const anchor = useRef<{ el: HTMLElement; top: number } | null>(null);
+ const wasActive = useRef(false);
+
+ // Before paint, so the corrected position is the first one drawn.
+ useLayoutEffect(() => {
+ if (active === wasActive.current) return;
+ wasActive.current = active;
+ const main = document.getElementById("main-content");
+ if (!main) return;
+ if (active) {
+ // Where the opener was when it was clicked, before the column came.
+ const opened = peekDayTriggerAt();
+ anchor.current =
+ opened && main.contains(opened.el)
+ ? { el: opened.el, top: opened.top }
+ : null;
+ }
+ const a = anchor.current;
+ if (a && a.el.isConnected) {
+ const delta = a.el.getBoundingClientRect().top - a.top;
+ if (Math.abs(delta) > 1) main.scrollTop += delta;
+ a.top = a.el.getBoundingClientRect().top;
+ }
+ if (!active) anchor.current = null;
+ }, [active]);
+
+ // While the column is open, the page may scroll; the anchor follows.
+ useEffect(() => {
+ if (!active) return;
+ const main = document.getElementById("main-content");
+ if (!main) return;
+ const record = () => {
+ const a = anchor.current;
+ if (a && a.el.isConnected) a.top = a.el.getBoundingClientRect().top;
+ };
+ main.addEventListener("scroll", record, { passive: true });
+ return () => main.removeEventListener("scroll", record);
+ }, [active]);
+}
+
function DockedTitle({
ref,
...props
@@ -362,7 +430,9 @@ function DaySheet({
returnFocus();
}}
className={cn(
- "bg-card gap-0 p-0",
+ // Quicker than the primitive's 500 ms, which read as lag on a
+ // layer opened from a tap; no slide at all under reduced motion.
+ "bg-card gap-0 p-0 data-[state=closed]:duration-200 data-[state=open]:duration-300 motion-reduce:animate-none",
bottom
? cn(
"rounded-t-2xl transition-[height] duration-200 motion-reduce:transition-none",
diff --git a/src/components/day/day-view.tsx b/src/components/day/day-view.tsx
index b92fd2830..55e317a23 100644
--- a/src/components/day/day-view.tsx
+++ b/src/components/day/day-view.tsx
@@ -8,8 +8,9 @@ import {
ChevronRight,
History,
MessageCircle,
+ PanelBottomClose,
+ PanelRightClose,
Plus,
- X,
} from "lucide-react";
import {
@@ -38,7 +39,8 @@ import {
DayValues,
} from "./day-sections";
import { curateDayValues, tileKeyOf } from "./day-values-model";
-import { useDay } from "./use-day";
+import { shiftDateKey } from "./day-url";
+import { useDay, usePrefetchDay } from "./use-day";
import { useDayValueFormat } from "./use-day-value-format";
/**
@@ -52,14 +54,16 @@ import { useDayValueFormat } from "./use-day-value-format";
*/
/** "Saturday, 3 January 2026", for the header and the spoken name. */
-export function useLongDayLabel(): (date: DateKey) => string {
+export function useLongDayLabel(
+ length: "long" | "short" = "long",
+): (date: DateKey) => string {
const { locale } = useTranslations();
const intl = resolveIntlLocale(locale);
return (date: DateKey) =>
new Intl.DateTimeFormat(intl, {
- weekday: "long",
+ weekday: length,
day: "numeric",
- month: "long",
+ month: length,
year: "numeric",
timeZone: "UTC",
}).format(new Date(`${date}T12:00:00.000Z`));
@@ -91,6 +95,16 @@ export interface DayViewProps {
const ICON_BUTTON =
"text-muted-foreground hover:text-foreground size-11 shrink-0 pointer-fine:size-9";
+/**
+ * The close control is the Coach panel's own toggle, in the same place: the
+ * panel's top-left corner, the panel icon mirrored so it points the way the
+ * panel goes. Same size and glyph as `PANEL_HEADER_BUTTON` there (kept as a
+ * copy so the day layer does not pull the Coach's panel into the shell).
+ */
+const PANEL_TOGGLE =
+ "text-muted-foreground hover:text-foreground size-11 shrink-0 pointer-fine:size-7";
+const PANEL_TOGGLE_ICON = "size-5 pointer-fine:size-4";
+
export function DayView({
date,
today,
@@ -106,6 +120,10 @@ export function DayView({
}: DayViewProps) {
const { t, tCount } = useTranslations();
const longLabel = useLongDayLabel();
+ // "Mo., 5. Okt. 2026" in the phone sheet's header: a September Thursday
+ // spelled out in full does not fit beside the arrows at 360 px, and a
+ // date cut off before its year reads as the wrong day.
+ const shortLabel = useLongDayLabel("short");
const pathname = usePathname();
const day = useDay(date);
const { labelFor, formatTile } = useDayValueFormat();
@@ -114,6 +132,15 @@ export function DayView({
const capabilities = useRecordCapabilities();
const { user } = useAuth();
const [captureOpen, setCaptureOpen] = useState(false);
+ // The neighbouring day is read while the pointer rests on its arrow (or
+ // the keyboard reaches it, or a finger lands on it), so the step paints a
+ // day, not a skeleton.
+ const prefetchDay = usePrefetchDay();
+ const warm = (delta: number) => () => {
+ const next = shiftDateKey(date, delta);
+ if (delta > 0 && next > today) return;
+ prefetchDay(next);
+ };
const canCapture =
visibleCaptureKinds(capabilities, CAPTURE_KIND_ORDER, user?.modules)
@@ -163,28 +190,49 @@ export function DayView({
data-slot="day-header"
className={cn(
"flex shrink-0 items-center gap-1",
- compact
- ? "pt-1.5 pr-2 pb-2.5 pl-4"
- : "border-border border-b pr-3 pl-6",
+ compact ? "pt-0.5 pr-2 pb-2 pl-2" : "border-border border-b px-3",
headerClassName,
)}
>
-
-
- {longLabel(date)}
-
-
- {meta ?? ·}
-
-
+ {/* Top left, where the Coach panel keeps its toggle: the way out. */}
+
+ {/* One line, centred in the band: the date and nothing under it. */}
+
+ {compact ? (
+ <>
+ {shortLabel(date)}
+ {longLabel(date)}
+ >
+ ) : (
+ longLabel(date)
+ )}
+
-
+ {/* What the day holds, as meta under the header. The line keeps its
+ height while the day loads, so nothing below it moves. */}
+
+ {meta ?? ·}
+
{focus ? (
string;
+}
+
+export function useHeatmapDay(containerRef: RefObject) {
+ const [tooltip, setTooltip] = useState(null);
+ // The pointer type of the last press decides whether the click that
+ // follows opens the day (mouse, pen) or only pinned the tooltip (touch).
+ const lastPointer = useRef("mouse");
+ const today = useTodayKey();
+ const openKey = useOpenDay();
+ const coarse = useCoarsePointer();
+
+ // A tap outside the heatmap clears a pinned tooltip.
+ useEffect(() => {
+ if (!tooltip?.pinned) return;
+ const handlePointer = (event: PointerEvent) => {
+ const container = containerRef.current;
+ if (!container) return;
+ if (!container.contains(event.target as Node)) setTooltip(null);
+ };
+ document.addEventListener("pointerdown", handlePointer, true);
+ return () =>
+ document.removeEventListener("pointerdown", handlePointer, true);
+ }, [tooltip?.pinned, containerRef]);
+
+ // Escape dismisses any open tooltip.
+ useEffect(() => {
+ if (!tooltip) return;
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") setTooltip(null);
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [tooltip]);
+
+ const canOpen = (cell: HeatmapCellInput): boolean =>
+ cell.hasEntry && isOpenableDay(cell.dateKey, today);
+
+ const open = (day: DateKey) => {
+ setTooltip(null);
+ openDay(day, { trigger: containerRef.current as HTMLElement | null });
+ };
+
+ /** Spread on a cell's ``. */
+ const cellProps = (cell: HeatmapCellInput) => {
+ const openable = canOpen(cell);
+ return {
+ "data-day": cell.dateKey,
+ "data-open": openable && openKey === cell.dateKey ? "true" : undefined,
+ className: openable ? "cursor-pointer" : undefined,
+ onPointerEnter: (e: React.PointerEvent) => {
+ // A touch enter fires just before `pointerdown`; the pinned
+ // tooltip below takes over with its real coordinates.
+ if (e.pointerType === "touch") return;
+ setTooltip({ x: e.clientX, y: e.clientY, text: cell.describe() });
+ },
+ onPointerLeave: (e: React.PointerEvent) => {
+ if (e.pointerType === "touch") return;
+ setTooltip((prev) => (prev?.pinned ? prev : null));
+ },
+ onPointerDown: (e: React.PointerEvent) => {
+ lastPointer.current = e.pointerType;
+ if (e.pointerType !== "touch") return;
+ setTooltip({
+ x: e.clientX,
+ y: e.clientY,
+ text: cell.describe(),
+ pinned: true,
+ day: openable ? cell.dateKey : undefined,
+ });
+ },
+ onClick: () => {
+ if (lastPointer.current === "touch") return;
+ if (!openable) return;
+ open(cell.dateKey);
+ },
+ };
+ };
+
+ /** Spread on the heatmap's `
diff --git a/src/components/insights/sleep-duration-chart.tsx b/src/components/insights/sleep-duration-chart.tsx
index 47b5a75bc..15a00a960 100644
--- a/src/components/insights/sleep-duration-chart.tsx
+++ b/src/components/insights/sleep-duration-chart.tsx
@@ -47,6 +47,9 @@ export function SleepDurationChart({
yAxisUnit="h"
compareBaseline={compareBaseline}
userTimezone={userTimezone}
+ // v1.42 — the same doors to the day every metric page's chart has.
+ showDataTable
+ dayLinks
/>
);
}
diff --git a/src/components/insights/sleep-stage-stacked-bar.tsx b/src/components/insights/sleep-stage-stacked-bar.tsx
index b5b6ae800..ccf2e94c0 100644
--- a/src/components/insights/sleep-stage-stacked-bar.tsx
+++ b/src/components/insights/sleep-stage-stacked-bar.tsx
@@ -7,6 +7,7 @@ import {
CartesianGrid,
Cell,
Legend,
+ ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
@@ -14,9 +15,18 @@ import {
} from "recharts";
import { Button } from "@/components/ui/button";
+import { ChartDataTable } from "@/components/charts/chart-data-table";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ dayAnchor,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { TileHeader } from "@/components/insights/tile-header";
import { useTranslations } from "@/lib/i18n/context";
+import { useCalendarDate } from "@/hooks/use-calendar-date";
+import { dateOnlyKey } from "@/lib/tz/date-only";
import { formatDurationMinutes } from "@/lib/i18n/duration";
import { resolveIntlLocale } from "@/lib/format-locale";
import type { Locale } from "@/lib/i18n/config";
@@ -260,6 +270,8 @@ export function compositionTotals(row: CompositionRow | undefined): {
export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
const { t, locale } = useTranslations();
+ const formatCalendar = useCalendarDate();
+ const fmtDay = (date: Date) => formatCalendar(dateOnlyKey(date));
// v1.4.25 W3f — window toggle (7 / 14 / 30). Default 7d so the user
// sees their most recent week with maximal per-bar resolution.
@@ -313,6 +325,36 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
),
);
+ // v1.42 — each night's column opens the day it ended on (the day the
+ // per-night key names, as `/api/sleep/night` does), through the same doors
+ // every day-linked chart has.
+ const nightDays = data.map((row) =>
+ typeof row.dayKey === "string" && row.dayKey !== "aggregate"
+ ? row.dayKey
+ : null,
+ );
+ const chartDays = useChartDayLinks({
+ enabled: hasData && nightDays.some((day) => day !== null),
+ days: nightDays,
+ focusFor: (index) => {
+ const totals = compositionTotals(data[index]);
+ return totals.nightMinutes > 0
+ ? {
+ label: t("insights.sleep.mainSleep"),
+ value: formatDurationMinutes(totals.nightMinutes, t),
+ types: ["SLEEP_DURATION"],
+ }
+ : null;
+ },
+ });
+ const tableColumns = [...STAGE_ORDER, ...(hasNap ? [NAP_KEY] : [])]
+ .filter((stage) =>
+ data.some(
+ (row) => typeof row[stage] === "number" && (row[stage] as number) > 0,
+ ),
+ )
+ .map((stage) => ({ key: stage, label: stageLabels[stage] ?? stage }));
+
const ariaLabel = t("insights.sleep.compositionAriaLabel", {
nights: breakdown.nights,
});
@@ -369,157 +411,228 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
{t("insights.sleep.stages.unavailable")}
) : (
-
-
-
-
-
- {
- // Render the y-axis as hours so 480 min reads as 8h.
- if (v <= 0) return "0";
- return `${Math.round(v / 60)}h`;
- }}
- />
- {
- if (!active || !payload || payload.length === 0)
- return null;
- const row = payload[0]?.payload as
- Record | undefined;
- const napCount =
- typeof row?.napCount === "number" ? row.napCount : 0;
- // The footer's first line is the NIGHT. The nap is listed
- // above it as its own line and stays out of that sum, so
- // the per-stage percentages keep meaning "of this night".
- // On a day with a nap a second line carries the whole
- // column — main sleep plus naps — the Main sleep / Naps /
- // Total split issue #611 asked for.
- const totals = compositionTotals(row);
- return (
-
-
-
- {label}
-
-
- {/* The nap is not part of the night, so it
+ <>
+
+
+
+
+
+ dayKey === "aggregate"
+ ? t("insights.sleep.compositionTitle")
+ : formatDayTick(dayKey, windowDays, locale)
+ }
+ stroke="var(--muted-foreground)"
+ fontSize={10}
+ interval="preserveStartEnd"
+ />
+ {
+ // Render the y-axis as hours so 480 min reads as 8h.
+ if (v <= 0) return "0";
+ return `${Math.round(v / 60)}h`;
+ }}
+ />
+ {chartDays.openIndex !== undefined ? (
+
+ ) : null}
+ {
+ if (!active || !payload || payload.length === 0)
+ return null;
+ const row = payload[0]?.payload as
+ Record | undefined;
+ const label = row?.label;
+ const rowIndex = row ? data.indexOf(row) : -1;
+ const napCount =
+ typeof row?.napCount === "number" ? row.napCount : 0;
+ // The footer's first line is the NIGHT. The nap is listed
+ // above it as its own line and stays out of that sum, so
+ // the per-stage percentages keep meaning "of this night".
+ // On a day with a nap a second line carries the whole
+ // column — main sleep plus naps — the Main sleep / Naps /
+ // Total split issue #611 asked for.
+ const totals = compositionTotals(row);
+ return (
+
+
+
+ {label}
+
+
+ {/* The nap is not part of the night, so it
gets no share-of-night percentage. */}
- {isNap
- ? formatDurationMinutes(minutes, t)
- : `${formatDurationMinutes(minutes, t)} · ${pct}%`}
-
-