From 7fbde1bc83439176cdc45b3c97cc4cb0bf829066 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?=
Date: Thu, 8 Oct 2026 15:19:09 +0200
Subject: [PATCH 1/6] feat: open the day from every chart drawn in days
Move the chart's doors to the day (click, the touch tooltip's button, the
dashed line through the open day, the row of day dots, the caption) into
one hook and give it to every chart with a date axis: recovery, sleep
duration and stages, the mood line and calendar, the intake calendar,
water and caffeine, lab markers, custom metrics, questionnaires and basal
temperature. Heatmaps share one adapter; every chart's keyboard way to a
day is its data table or the dated list beside it.
---
src/app/insights/mood/page.tsx | 2 +-
src/components/charts/chart-data-table.tsx | 9 +-
src/components/charts/compliance-heatmap.tsx | 243 ++++------
src/components/charts/health-chart.tsx | 107 ++---
src/components/charts/mood-chart.tsx | 91 +++-
src/components/charts/mood-heatmap.tsx | 231 ++++------
.../charts/nutrient-daily-bar-chart.tsx | 193 +++++---
.../custom-metrics/custom-metric-chart.tsx | 245 ++++++----
.../custom-metrics/custom-metric-detail.tsx | 1 +
src/components/cycle/bbt-chart.tsx | 79 +++-
src/components/day/chart-day-links.tsx | 213 +++++++++
src/components/day/chart-day.tsx | 89 +++-
src/components/day/heatmap-day.tsx | 159 +++++++
.../insights/nutrients/caffeine-card.tsx | 1 +
.../insights/nutrients/hydration-card.tsx | 1 +
.../recovery/recovery-metric-block.tsx | 3 +
.../insights/sleep-duration-chart.tsx | 3 +
.../insights/sleep-stage-stacked-bar.tsx | 403 ++++++++++------
src/components/labs/lab-biomarker-chart.tsx | 429 +++++++++---------
.../assessment-history-chart.tsx | 215 +++++----
.../mental-health/assessment-history.tsx | 8 +-
21 files changed, 1725 insertions(+), 1000 deletions(-)
create mode 100644 src/components/day/chart-day-links.tsx
create mode 100644 src/components/day/heatmap-day.tsx
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/components/charts/chart-data-table.tsx b/src/components/charts/chart-data-table.tsx
index 185d00dae..98e1aee0d 100644
--- a/src/components/charts/chart-data-table.tsx
+++ b/src/components/charts/chart-data-table.tsx
@@ -186,8 +186,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. */}
(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 && (
-
- {activeCells.map((cell) => (
- {describeCell(cell)}
- ))}
-
- )}
-
- {/* Tooltip */}
- {tooltip && (
-
- {tooltip.text}
- {tooltip.day ? (
- {
- const day = tooltip.day;
- setTooltip(null);
- if (day) openDay(day, { trigger: containerRef.current });
- }}
- className="bg-muted hover:bg-muted/80 focus-visible:ring-ring/50 mt-1.5 flex min-h-11 w-full items-center justify-center rounded-md px-3 text-sm font-medium focus-visible:ring-[3px] focus-visible:outline-none"
- >
- {t("day.openDay")}
-
- ) : null}
-
- )}
+ {heatmapDay.tooltipNode}
{/* Legend */}
))}
+ {activeCells.length > 0 ? (
+ <>
+
+ {/* The keyboard and screen-reader way to each active day's doses,
+ and to the day itself. */}
+ ({
+ date: cell.dateKey,
+ timestamp: dayAnchor(cell.dateKey),
+ rate:
+ cell.data.expected > 0
+ ? Math.min(
+ 100,
+ Math.round((cell.data.taken / cell.data.expected) * 100),
+ )
+ : undefined,
+ }))}
+ columns={[{ key: "rate", label: t("medications.compliance") }]}
+ formatValue={(value) => `${value} %`}
+ formatDate={(date) => formatDay(dateOnlyKey(date))}
+ bucket="day"
+ metricLabel={t("insights.medicationCompliance")}
+ dayLinks
+ />
+ >
+ ) : null}
);
}
diff --git a/src/components/charts/health-chart.tsx b/src/components/charts/health-chart.tsx
index 06d7050fd..2d74f3c89 100644
--- a/src/components/charts/health-chart.tsx
+++ b/src/components/charts/health-chart.tsx
@@ -77,15 +77,12 @@ import {
} from "@/lib/charts/window-stats";
import { shouldFireDataReady } from "@/lib/charts/data-ready-latch";
import { axisUnitSuffix } from "@/lib/charts/axis-unit";
+import { chartPointDayKey } from "@/components/day/chart-day";
import {
- ChartDayCaption,
- DayRug,
- TooltipDayAction,
- chartPointDayKey,
- openChartDay,
- useCoarsePointer,
-} from "@/components/day/chart-day";
-import { useOpenDay } from "@/components/day/day-layer-controller";
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
import { isWholeNumberType } from "@/components/day/use-day-value-format";
// The range tabs select a CALENDAR-DAY window ending now — `days: 7` is
@@ -1732,19 +1729,10 @@ export function HealthChart({
// v1.42 — the chart as a door to its days (`dayLinks`). Daily points only:
// a week or month point averages many days and has no one day to open.
const dayLinksActive = dayLinks && !mini && activeBucket === "day";
- const openDayKey = useOpenDay();
- const coarsePointer = useCoarsePointer();
- const plotRef = useRef(null);
- const openDayIndex =
- dayLinksActive && openDayKey
- ? resolveVerticalMarkerPositions([{ date: openDayKey }], chartData)[0]
- ?.pointIndex
- : undefined;
- const openDayPoint =
- openDayIndex !== undefined ? chartData?.[openDayIndex] : undefined;
// What the day shows at its top when it is opened from a point: the
// chart's own name and the point's value as the tooltip reads it.
- const dayFocusFor = (point: ChartDataPoint) => {
+ const dayFocusFor = (point: ChartDataPoint | undefined) => {
+ if (!point) return null;
const parts = types
.map((type) => ({ type, v: point[type] }))
.filter((p): p is { type: string; v: number } => typeof p.v === "number");
@@ -1764,10 +1752,18 @@ export function HealthChart({
types: valueMode === "raw" ? types : [],
};
};
- const openPointDay = (point: ChartDataPoint | undefined) => {
- if (!point) return;
- openChartDay(point.timestamp, dayFocusFor(point), plotRef.current);
- };
+ const dayLinkSource = chartDataWithCompare ?? chartData;
+ const chartDays = useChartDayLinks({
+ enabled: dayLinksActive,
+ days: dayLinksActive
+ ? (dayLinkSource ?? []).map((point) => chartPointDayKey(point.timestamp))
+ : [],
+ focusFor: (index) => dayFocusFor(dayLinkSource?.[index]),
+ });
+ const coarsePointer = chartDays.coarse;
+ const openDayIndex = chartDays.openIndex;
+ const openDayPoint =
+ openDayIndex !== undefined ? chartData?.[openDayIndex] : undefined;
const showContextDetails = showMA || showTrend || showBands;
const animationsEnabled = !prefersReducedMotion();
@@ -2025,11 +2021,8 @@ export function HealthChart({
// gate on; this slot is rendered by the data branch only, so it
// says the same thing without depending on Recharts' markup.
data-slot="chart-plot"
- data-day-links={dayLinksActive ? "true" : undefined}
- ref={plotRef}
- className={`relative z-10 h-full touch-pan-y ${
- dayLinksActive && !coarsePointer ? "cursor-pointer" : ""
- }`}
+ {...chartDays.plotProps}
+ className={`relative z-10 h-full touch-pan-y ${chartDays.plotClassName}`}
role="img"
aria-label={chartAriaLabel}
>
@@ -2038,17 +2031,7 @@ export function HealthChart({
data={chartDataWithCompare ?? chartData}
margin={{ top: 10, right: 8, bottom: 8, left: 8 }}
accessibilityLayer
- onClick={
- dayLinksActive && !coarsePointer
- ? (state) => {
- const index = Number(state?.activeTooltipIndex);
- if (!Number.isInteger(index)) return;
- openPointDay(
- (chartDataWithCompare ?? chartData)?.[index],
- );
- }
- : undefined
- }
+ onClick={chartDays.onChartClick}
>
) : null}
{openDayIndex !== undefined && openDayPoint
@@ -2281,14 +2261,7 @@ export function HealthChart({
filterNull={false}
// v1.42 — on a touch screen the tooltip is the way to the
// day: it stays where the tap put it and takes taps.
- trigger={
- dayLinksActive && coarsePointer ? "click" : "hover"
- }
- wrapperStyle={
- dayLinksActive && coarsePointer
- ? { pointerEvents: "auto", zIndex: 20 }
- : undefined
- }
+ {...chartDays.tooltipProps}
cursor={{
stroke: "var(--muted-foreground)",
strokeOpacity: 0.3,
@@ -2432,13 +2405,11 @@ export function HealthChart({
: dateLabel
}
rows={rows}
- action={
- dayLinksActive && coarsePointer && hoverPoint ? (
- openPointDay(hoverPoint)}
- />
- ) : undefined
- }
+ action={chartDays.tooltipAction(
+ hoverPoint
+ ? dayLinkSource?.indexOf(hoverPoint)
+ : undefined,
+ )}
/>
);
}}
@@ -2574,17 +2545,15 @@ export function HealthChart({
) : null}
- {dayLinksActive && chartData && chartData.length > 0 ? (
- <>
-
-
- >
+ {chartData ? (
+
) : null}
{/* The points the chart just drew, as a table. Reads the SAME
expression `` is handed above, so the two
diff --git a/src/components/charts/mood-chart.tsx b/src/components/charts/mood-chart.tsx
index 269bfed78..eeb46aec8 100644
--- a/src/components/charts/mood-chart.tsx
+++ b/src/components/charts/mood-chart.tsx
@@ -31,6 +31,13 @@ import {
type ChartBucketType,
} from "@/lib/charts/bucket-time-series";
import { RichChartTooltip, type RichTooltipRow } from "./chart-tooltip";
+import { ChartDataTable } from "./chart-data-table";
+import { chartPointDayKey } from "@/components/day/chart-day";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
import { ChartEmptyState } from "./chart-empty-state";
import { ChartErrorState } from "./chart-error-state";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
@@ -102,6 +109,14 @@ interface MoodChartProps {
* visibly before its measurement siblings. Optional and repeat-safe.
*/
onDataReady?: () => void;
+ /**
+ * v1.42 — the chart is a door to its days, exactly as `HealthChart`'s
+ * `dayLinks`: a click on a point (the tooltip's button on touch) opens the
+ * day, the open day carries a dashed line, a row of dots marks the days
+ * with entries, and the data table under the chart links each date. Daily
+ * points only, never in `mini` mode.
+ */
+ dayLinks?: boolean;
}
// --- Constants ---
@@ -317,6 +332,7 @@ export function MoodChart({
compareBaseline = "none",
chartKey,
onDataReady,
+ dayLinks = false,
}: MoodChartProps) {
const { isAuthenticated } = useAuth();
const { t, locale } = useTranslations();
@@ -654,6 +670,27 @@ export function MoodChart({
: sorted[mid];
}, [chartData]);
+ // v1.42 — the chart as a door to its days (`dayLinks`), through the same
+ // hook every day-linked chart uses.
+ const dayLinksActive = dayLinks && !mini && activeBucket === "day";
+ const dayLinkSource = chartDataWithCompare ?? chartData;
+ const chartDays = useChartDayLinks({
+ enabled: dayLinksActive,
+ days: dayLinksActive
+ ? (dayLinkSource ?? []).map((point) => chartPointDayKey(point.timestamp))
+ : [],
+ focusFor: (index) => {
+ const point = dayLinkSource?.[index];
+ return point
+ ? {
+ label: displayTitle,
+ value: formatTooltipValue(point.score),
+ types: ["MOOD"],
+ }
+ : null;
+ },
+ });
+
const animationsEnabled = !prefersReducedMotion();
// v1.16.8 — only an EMPTY success hides the card (the dashboard gates
@@ -766,7 +803,8 @@ export function MoodChart({
mini
? "h-[var(--chart-height,140px)]"
: "h-[var(--chart-height,200px)] md:h-[var(--chart-height-md,220px)]"
- } touch-pan-y`}
+ } touch-pan-y ${chartDays.plotClassName}`}
+ {...chartDays.plotProps}
// Same stable hook as the measurement chart: rendered by the data
// branch only, so the browser suite can gate on it instead of on
// Recharts' own class names.
@@ -779,6 +817,7 @@ export function MoodChart({
data={chartDataWithCompare ?? chartData}
margin={{ top: 10, right: 8, bottom: 8, left: 8 }}
accessibilityLayer
+ onClick={chartDays.onChartClick}
>
{/* v1.4.25 W3 — the mood chart's YAxis is pinned to
five mood-score ticks ([1,2,3,4,5]), which Recharts
@@ -868,7 +907,15 @@ export function MoodChart({
tickMargin={10}
tickFormatter={formatMoodTick}
/>
+ {chartDays.openIndex !== undefined ? (
+
+ ) : null}
;
+ return (
+
+ );
}}
/>
- {chartBody}
+
+ {chartBody}
+ {!isLoading && !isError && chartData && chartData.length >= 3 ? (
+ <>
+
+ {dayLinksActive ? (
+ ({
+ date: point.date,
+ timestamp: point.timestamp,
+ score: point.score,
+ }))}
+ columns={[{ key: "score", label: t("charts.moodScore") }]}
+ formatValue={formatTooltipValue}
+ formatDate={tzFmt.date}
+ bucket="day"
+ metricLabel={displayTitle}
+ dayLinks
+ />
+ ) : null}
+ >
+ ) : null}
+
);
}
diff --git a/src/components/charts/mood-heatmap.tsx b/src/components/charts/mood-heatmap.tsx
index 39841e476..de1c082a2 100644
--- a/src/components/charts/mood-heatmap.tsx
+++ b/src/components/charts/mood-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";
@@ -73,47 +75,10 @@ export function MoodHeatmap({
const formatDay = useCalendarDate();
const containerRef = useRef(null);
const [containerWidth, setContainerWidth] = useState(0);
- const [tooltip, setTooltip] = useState<{
- x: number;
- y: number;
- text: string;
- 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();
-
- 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"),
@@ -225,9 +190,8 @@ export function MoodHeatmap({
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
+ // prints the same score with the same label (M2).
const describeCell = (cell: (typeof cells)[number]): string => {
if (!cell.cell) {
return `${formatDay(cell.dateKey)}: ${t("insights.mood.heatmapNoEntry")}`;
@@ -236,7 +200,7 @@ export function MoodHeatmap({
const moodLabel = labelKey ? t(labelKey) : "";
return `${formatDay(cell.dateKey)}: ${cell.cell.score.toFixed(1)}${moodLabel ? ` · ${moodLabel}` : ""}`;
};
- // Only the logged days go into the sr-only list; the empty-tinted cells
+ // Only the logged days go into the data table; the empty-tinted cells
// are already covered by the aggregate summary on the SVG, so a rotor
// user hears the days that carry a value rather than a wall of "no entry".
const loggedCells = cells.filter((cell) => cell.cell !== null);
@@ -259,9 +223,7 @@ export function MoodHeatmap({
// natural, square, left-aligned grid rather than CSS-stretching a few
// capped columns into wide rectangles. Mirrors `compliance-heatmap`.
className={stretch ? "block max-w-full" : "block"}
- onMouseLeave={() =>
- setTooltip((prev) => (prev?.pinned ? prev : null))
- }
+ {...heatmapDay.svgProps}
>
{monthMarkers.map((m, i) => (
{
- const buildText = (): string => describeCell(cell);
- return (
+ {cells.map((cell) => (
+ describeCell(cell),
+ })}
+ />
+ ))}
+ {cells
+ .filter((cell) => cell.dateKey === heatmapDay.openKey)
+ .map((cell) => (
{
- 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.cell !== null && isOpenableDay(cell.dateKey, today)
- ? cell.dateKey
- : undefined,
- });
- }}
- onClick={() => {
- if (lastPointer.current === "touch") return;
- if (cell.cell === null) 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. */}
- {loggedCells.length > 0 && (
-
- {loggedCells.map((cell) => (
- {describeCell(cell)}
- ))}
-
- )}
-
- {tooltip && (
-
- {tooltip.text}
- {tooltip.day ? (
- {
- const day = tooltip.day;
- setTooltip(null);
- if (day) openDay(day, { trigger: containerRef.current });
- }}
- className="bg-muted hover:bg-muted/80 focus-visible:ring-ring/50 mt-1.5 flex min-h-11 w-full items-center justify-center rounded-md px-3 text-sm font-medium focus-visible:ring-[3px] focus-visible:outline-none"
- >
- {t("day.openDay")}
-
- ) : null}
-
- )}
+ {heatmapDay.tooltipNode}
))}
+ {loggedCells.length > 0 ? (
+ <>
+
+ {/* The keyboard and screen-reader way to each logged day's value,
+ and to the day itself. */}
+ ({
+ date: cell.dateKey,
+ timestamp: dayAnchor(cell.dateKey),
+ score: cell.cell?.score,
+ }))}
+ columns={[{ key: "score", label: t("charts.moodScore") }]}
+ formatValue={(value) => {
+ const labelKey = moodLabelKeyForScore(Math.round(value));
+ return labelKey
+ ? `${value.toFixed(1)} · ${t(labelKey)}`
+ : value.toFixed(1);
+ }}
+ formatDate={(date) => formatDay(dateOnlyKey(date))}
+ bucket="day"
+ metricLabel={t("insights.mood.heatmapTitle")}
+ dayLinks
+ />
+ >
+ ) : null}
);
}
diff --git a/src/components/charts/nutrient-daily-bar-chart.tsx b/src/components/charts/nutrient-daily-bar-chart.tsx
index f66395121..749f3d988 100644
--- a/src/components/charts/nutrient-daily-bar-chart.tsx
+++ b/src/components/charts/nutrient-daily-bar-chart.tsx
@@ -12,10 +12,17 @@ import {
YAxis,
} from "recharts";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ dayAnchor,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import { useFormatters } from "@/lib/i18n/context";
+import { ChartDataTable } from "./chart-data-table";
import { RichChartTooltip, type RichTooltipRow } from "./chart-tooltip";
/**
@@ -36,6 +43,13 @@ interface NutrientDailyBarChartProps {
valueLabel: string;
/** Optional dashed reference line value (EFSA target / ceiling). */
referenceValue?: number | null;
+ /**
+ * v1.42 — each bar opens its day, through the doors every day-linked
+ * chart has (click, the tooltip's button on touch, the dashed line, the
+ * row of dots, the data table). A day logged as nothing has no bar to
+ * open.
+ */
+ dayLinks?: boolean;
}
export function NutrientDailyBarChart({
@@ -43,6 +57,7 @@ export function NutrientDailyBarChart({
unit,
valueLabel,
referenceValue,
+ dayLinks = false,
}: NutrientDailyBarChartProps) {
const fmt = useFormatters();
const points = useMemo(
@@ -60,71 +75,125 @@ export function NutrientDailyBarChart({
const animate = !prefersReducedMotion();
const barColor = "var(--info)";
+ const chartDays = useChartDayLinks({
+ enabled: dayLinks,
+ days: points.map((p) => (p.amount > 0 ? p.day : null)),
+ focusFor: (index) => {
+ const point = points[index];
+ return point
+ ? { label: valueLabel, value: fmt.integer(point.amount), unit }
+ : null;
+ },
+ });
+ const logged = points.filter((p) => p.amount > 0);
+
return (
-
-
+
-
- fmt.dateShortSmartCalendar(day)}
- tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
- stroke="var(--border)"
- minTickGap={24}
- />
-
- {referenceValue != null ? (
-
- ) : null}
- {
- const active = props.active ?? false;
- const payload = props.payload as
- | ReadonlyArray<{ payload?: { day: string; amount: number } }>
- | undefined;
- const point = payload?.[0]?.payload;
- if (!active || !point) {
- return ;
- }
- const rows: RichTooltipRow[] = [
- {
- name: valueLabel,
- value: `${point.amount} ${unit}`,
- color: barColor,
- },
- ];
- return (
-
+
+
+ fmt.dateShortSmartCalendar(day)}
+ tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
+ stroke="var(--border)"
+ minTickGap={24}
+ />
+
+ {referenceValue != null ? (
+
- );
- }}
+ ) : null}
+ {chartDays.openIndex !== undefined ? (
+
+ ) : null}
+ {
+ const active = props.active ?? false;
+ const payload = props.payload as
+ | ReadonlyArray<{ payload?: { day: string; amount: number } }>
+ | undefined;
+ const point = payload?.[0]?.payload;
+ if (!active || !point) {
+ return ;
+ }
+ const rows: RichTooltipRow[] = [
+ {
+ name: valueLabel,
+ value: `${point.amount} ${unit}`,
+ color: barColor,
+ },
+ ];
+ return (
+
+ );
+ }}
+ />
+
+
+
+
+ ({ timestamp: dayAnchor(p.day) }))}
+ axis="band"
+ mark="bar"
+ // The y axis (44) on the left, the margin (12) on the right.
+ insetLeft={44}
+ insetRight={12}
+ />
+ {chartDays.active && logged.length > 0 ? (
+ ({
+ date: p.day,
+ timestamp: dayAnchor(p.day),
+ amount: p.amount,
+ }))}
+ columns={[{ key: "amount", label: valueLabel }]}
+ unit={unit}
+ formatValue={(value) => fmt.integer(value)}
+ formatDate={(date) => fmt.dateShortSmartCalendar(date)}
+ bucket="day"
+ metricLabel={valueLabel}
+ dayLinks
/>
-
-
-
+ ) : null}
+ >
);
}
diff --git a/src/components/custom-metrics/custom-metric-chart.tsx b/src/components/custom-metrics/custom-metric-chart.tsx
index 9cfadde5e..e35a77dc8 100644
--- a/src/components/custom-metrics/custom-metric-chart.tsx
+++ b/src/components/custom-metrics/custom-metric-chart.tsx
@@ -16,9 +16,20 @@ import {
import { Button } from "@/components/ui/button";
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
-import { useTranslations, useFormatters } from "@/lib/i18n/context";
-
+import {
+ useDisplayTimezone,
+ useTranslations,
+ useFormatters,
+} from "@/lib/i18n/context";
+import { ChartDataTable } from "../charts/chart-data-table";
import { RichChartTooltip, type RichTooltipRow } from "../charts/chart-tooltip";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ dayAnchor,
+ useChartDayLinks,
+} from "../day/chart-day-links";
+import { dateKeyOfInstant } from "../day/day-url";
import { formatMetricValue } from "./format-value";
import type { CustomMetricEntryDto } from "./types";
@@ -48,11 +59,14 @@ interface ChartPoint {
export function CustomMetricChart({
entries,
+ name,
unit,
targetLow,
targetHigh,
decimals,
}: {
+ /** The metric's name: the day's focus label and the data table's caption. */
+ name: string;
/** Entries for this metric, any order (sorted internally). */
entries: CustomMetricEntryDto[];
unit: string;
@@ -95,6 +109,25 @@ export function CustomMetricChart({
return [min - pad, max + pad];
}, [points, targetLow, targetHigh]);
+ // v1.42 — each value opens its day (the calendar day of its instant in
+ // the record's zone) through the doors every day-linked chart has.
+ const timeZone = useDisplayTimezone();
+ const pointDays = points.map((point) =>
+ dateKeyOfInstant(point.timestamp, timeZone),
+ );
+ const chartDays = useChartDayLinks({
+ enabled: true,
+ days: pointDays,
+ focusFor: (index) => {
+ const point = points[index];
+ return point
+ ? { label: name, value: formatMetricValue(point.value, decimals), unit }
+ : null;
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined ? points[chartDays.openIndex] : undefined;
+
const animate = !prefersReducedMotion();
const primary = "var(--primary)";
@@ -121,94 +154,130 @@ export function CustomMetricChart({
) : (
-
-
-
- fmt.dateShortSmart(new Date(ts))}
- tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
- stroke="var(--border)"
- minTickGap={32}
- />
- formatMetricValue(v, decimals)}
- />
- {targetLow != null && targetHigh != null ? (
-
+
+
+
- ) : null}
- {targetLow != null ? (
-
- ) : null}
- {targetHigh != null ? (
-
- ) : null}
- {
- const active = props.active ?? false;
- const payload = props.payload as
- ReadonlyArray<{ payload?: ChartPoint }> | undefined;
- const point = payload?.[0]?.payload;
- if (!active || !point) {
- return ;
+
+ fmt.dateShortSmart(new Date(ts))
}
- const rows: RichTooltipRow[] = [
- {
- name: t("customMetrics.chart.valueLabel"),
- value: `${formatMetricValue(point.value, decimals)} ${unit}`,
- color: primary,
- },
- ];
- return (
-
- );
- }}
- />
-
-
-
+ tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
+ stroke="var(--border)"
+ minTickGap={32}
+ />
+ formatMetricValue(v, decimals)}
+ />
+ {targetLow != null && targetHigh != null ? (
+
+ ) : null}
+ {targetLow != null ? (
+
+ ) : null}
+ {targetHigh != null ? (
+
+ ) : null}
+ {openPoint ? (
+
+ ) : null}
+ {
+ const active = props.active ?? false;
+ const payload = props.payload as
+ ReadonlyArray<{ payload?: ChartPoint }> | undefined;
+ const point = payload?.[0]?.payload;
+ if (!active || !point) {
+ return ;
+ }
+ const rows: RichTooltipRow[] = [
+ {
+ name: t("customMetrics.chart.valueLabel"),
+ value: `${formatMetricValue(point.value, decimals)} ${unit}`,
+ color: primary,
+ },
+ ];
+ return (
+
+ );
+ }}
+ />
+
+
+
+
+
+ ({
+ date: pointDays[index]!,
+ timestamp: dayAnchor(pointDays[index]!),
+ value: point.value,
+ }))}
+ columns={[{ key: "value", label: name }]}
+ unit={unit}
+ formatValue={(value) => formatMetricValue(value, decimals)}
+ formatDate={(date) => fmt.dateShortSmartCalendar(date)}
+ bucket="day"
+ metricLabel={name}
+ dayLinks
+ />
)}
diff --git a/src/components/custom-metrics/custom-metric-detail.tsx b/src/components/custom-metrics/custom-metric-detail.tsx
index 894366eac..485f4dde3 100644
--- a/src/components/custom-metrics/custom-metric-detail.tsx
+++ b/src/components/custom-metrics/custom-metric-detail.tsx
@@ -287,6 +287,7 @@ export function CustomMetricDetail({
= 2;
+ // v1.42 — each logged temperature opens its day through the doors every
+ // day-linked chart has. Tapping a cycle-calendar cell still logs the day;
+ // the chart is where a day is read.
+ const chartDays = useChartDayLinks({
+ enabled: hasCurve,
+ days: points.map((p) => dateOnlyKey(new Date(p.t))),
+ focusFor: (index) => {
+ const p = points[index];
+ return p
+ ? {
+ label: t("cycle.bbt.title"),
+ value: fmt.number(p.temp),
+ unit: unitDisplay.unitFor("BODY_TEMPERATURE"),
+ types: ["BODY_TEMPERATURE"],
+ }
+ : null;
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined ? points[chartDays.openIndex] : undefined;
+
return (
@@ -213,14 +241,16 @@ export function BbtChart({
{t("cycle.bbt.caption")}
`${fmt.number(v as number)}°`}
/>
+ {openPoint ? (
+
+ ) : null}
}
+ content={(props) => {
+ const payload = props.payload as unknown as
+ { payload: BbtPoint }[] | undefined;
+ const point = payload?.[0]?.payload;
+ return (
+
+ );
+ }}
/>
{ovulationMs != null ? (
+ ({ 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/day/chart-day-links.tsx b/src/components/day/chart-day-links.tsx
new file mode 100644
index 000000000..12f8c70d5
--- /dev/null
+++ b/src/components/day/chart-day-links.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { useCallback, useMemo, useRef, type ReactNode } from "react";
+
+import type { DateKey } from "@/lib/day/contract";
+
+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") opens the day. Two steps, so a scroll that
+ * grazes the chart never opens a sheet;
+ * - 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 put and takes taps. */
+ tooltipProps: {
+ trigger: "click" | "hover";
+ wrapperStyle?: React.CSSProperties;
+ };
+ /** 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 },
+ }
+ : { 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..34b5ec77c 100644
--- a/src/components/day/chart-day.tsx
+++ b/src/components/day/chart-day.tsx
@@ -119,19 +119,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 +184,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 +214,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 +222,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 (
- {t("day.rugLegend")}
- {coarse ? t("day.chartHintTouch") : t("day.chartHint")}
+ {rug ? {t("day.rugLegend")} : null}
+ {coarse ? t(hint.coarse) : t(hint.fine)}
);
}
diff --git a/src/components/day/heatmap-day.tsx b/src/components/day/heatmap-day.tsx
new file mode 100644
index 000000000..46581876e
--- /dev/null
+++ b/src/components/day/heatmap-day.tsx
@@ -0,0 +1,159 @@
+"use client";
+
+import { useEffect, useRef, useState, type RefObject } from "react";
+
+import type { DateKey } from "@/lib/day/contract";
+
+import { TooltipDayAction, useCoarsePointer } from "./chart-day";
+import { openDay, useOpenDay } from "./day-layer-controller";
+import { isOpenableDay } from "./day-url";
+import { useTodayKey } from "./use-today-key";
+
+/**
+ * The day view's doors on a calendar heatmap (mood, intake), the cell twin of
+ * `useChartDayLinks`:
+ *
+ * - fine pointer: hovering a cell shows its tooltip, a click opens its day;
+ * - touch: a tap pins the tooltip, and the tooltip's button ("View the
+ * whole day", the same button every chart's tooltip carries) opens it;
+ * a tap outside or Escape clears it;
+ * - the open day's cell carries a dashed outline, the heatmap's form of
+ * the dashed line a chart draws through it (`OPEN_DAY_CELL`);
+ * - the keyboard and screen-reader way to a day is the heatmap's data
+ * table (`ChartDataTable` with `dayLinks`), as for every chart.
+ *
+ * A cell opens only when its day holds an entry and is not in the future.
+ */
+
+/** The dashed outline drawn over the open day's cell. */
+export const OPEN_DAY_CELL = {
+ fill: "none",
+ stroke: "var(--foreground)",
+ strokeWidth: 1.5,
+ strokeDasharray: "3 2",
+} as const;
+
+interface HeatmapTooltip {
+ x: number;
+ y: number;
+ text: string;
+ /** A touch tooltip stays after the finger lifts. */
+ pinned?: boolean;
+ /** The day a pinned tooltip offers to open. */
+ day?: DateKey;
+}
+
+export interface HeatmapCellInput {
+ dateKey: string;
+ /** True when the day holds an entry this heatmap shows. */
+ hasEntry: boolean;
+ /** The cell's text, for the tooltip. */
+ describe: () => 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 ``. */
+ const svgProps = {
+ onMouseLeave: () => setTooltip((prev) => (prev?.pinned ? prev : null)),
+ };
+
+ const tooltipNode = tooltip ? (
+
+ {tooltip.text}
+ {tooltip.day ? (
+ open(tooltip.day as DateKey)} />
+ ) : null}
+
+ ) : null;
+
+ return { cellProps, svgProps, tooltipNode, openKey, coarse };
+}
diff --git a/src/components/insights/nutrients/caffeine-card.tsx b/src/components/insights/nutrients/caffeine-card.tsx
index 49e799711..e35e065a2 100644
--- a/src/components/insights/nutrients/caffeine-card.tsx
+++ b/src/components/insights/nutrients/caffeine-card.tsx
@@ -81,6 +81,7 @@ export function CaffeineCard() {
unit={data.unit}
valueLabel={t("nutrients.names.caffeine")}
referenceValue={data.reference?.value ?? null}
+ dayLinks
/>
diff --git a/src/components/insights/nutrients/hydration-card.tsx b/src/components/insights/nutrients/hydration-card.tsx
index d2eb54f4f..c66ea2fe2 100644
--- a/src/components/insights/nutrients/hydration-card.tsx
+++ b/src/components/insights/nutrients/hydration-card.tsx
@@ -78,6 +78,7 @@ export function HydrationCard() {
unit={data.unit}
valueLabel={t("nutrients.names.water")}
referenceValue={data.reference?.value ?? null}
+ dayLinks
/>
>
)}
diff --git a/src/components/insights/recovery/recovery-metric-block.tsx b/src/components/insights/recovery/recovery-metric-block.tsx
index c790c26b9..262771972 100644
--- a/src/components/insights/recovery/recovery-metric-block.tsx
+++ b/src/components/insights/recovery/recovery-metric-block.tsx
@@ -99,6 +99,9 @@ export function RecoveryMetricBlock({
compareBaseline={compareBaseline}
userTimezone={user?.timezone}
onVisibleStats={onVisibleStats}
+ // 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}
-
- {payload.map((entry) => {
- const stage = String(entry.dataKey ?? "");
- const minutes =
- typeof entry.value === "number" ? entry.value : 0;
- if (minutes === 0) return null;
- const isNap = stage === NAP_KEY;
- const label = isNap
- ? napCount > 1
- ? t("insights.sleep.stages.napCount", {
- count: String(napCount),
- })
- : stageLabels[NAP_KEY]
- : (stageLabels[stage] ?? stage);
- const pct =
- totals.nightMinutes > 0
- ? Math.round(
- (minutes / totals.nightMinutes) * 100,
- )
- : 0;
- 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}
+
+ {payload.map((entry) => {
+ const stage = String(entry.dataKey ?? "");
+ const minutes =
+ typeof entry.value === "number" ? entry.value : 0;
+ if (minutes === 0) return null;
+ const isNap = stage === NAP_KEY;
+ const label = isNap
+ ? napCount > 1
+ ? t("insights.sleep.stages.napCount", {
+ count: String(napCount),
+ })
+ : stageLabels[NAP_KEY]
+ : (stageLabels[stage] ?? stage);
+ const pct =
+ totals.nightMinutes > 0
+ ? Math.round(
+ (minutes / totals.nightMinutes) * 100,
+ )
+ : 0;
+ 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}%`}
-
-
- );
- })}
- {totals.nightMinutes > 0 && (
-
-
- {t("insights.sleep.mainSleep")}
-
- {formatDurationMinutes(totals.nightMinutes, t)}
-
-
- {totals.napMinutes > 0 && (
-
- {t("insights.sleep.totalSleep")}
-
- {formatDurationMinutes(totals.dayMinutes, t)}
+ {isNap
+ ? formatDurationMinutes(minutes, t)
+ : `${formatDurationMinutes(minutes, t)} · ${pct}%`}
- )}
-
- )}
-
- );
- }}
- />
- stageLabels[value] ?? value}
- />
- {STAGE_ORDER.map((stage) => (
-
- |
-
- ))}
- {hasNap && (
-
- 0 && (
+
+
+ {t("insights.sleep.mainSleep")}
+
+ {formatDurationMinutes(
+ totals.nightMinutes,
+ t,
+ )}
+
+
+ {totals.napMinutes > 0 && (
+
+ {t("insights.sleep.totalSleep")}
+
+ {formatDurationMinutes(
+ totals.dayMinutes,
+ t,
+ )}
+
+
+ )}
+
+ )}
+ {chartDays.tooltipAction(
+ rowIndex === -1 ? undefined : rowIndex,
+ )}
+ |
+ );
+ }}
+ />
+ stageLabels[value] ?? value}
+ />
+ {STAGE_ORDER.map((stage) => (
+
+ |
+
+ ))}
+ {hasNap && (
+
-
- )}
-
-
-
+ isAnimationActive={false}
+ >
+
|
+
+ )}
+
+
+
+ ({
+ timestamp:
+ typeof row.dayKey === "string" && row.dayKey !== "aggregate"
+ ? dayAnchor(row.dayKey)
+ : 0,
+ }))}
+ axis="band"
+ mark="bar"
+ // The plot's margin (8) + the y axis (60) on the left, the
+ // margin (16) on the right.
+ insetLeft={8 + 60}
+ insetRight={16}
+ />
+ {chartDays.active ? (
+ ({
+ date: String(row.dayKey),
+ timestamp: dayAnchor(String(row.dayKey)),
+ ...Object.fromEntries(
+ tableColumns.map(({ key }) => [
+ key,
+ typeof row[key] === "number" && (row[key] as number) > 0
+ ? (row[key] as number)
+ : undefined,
+ ]),
+ ),
+ }))}
+ columns={tableColumns}
+ formatValue={(minutes) => formatDurationMinutes(minutes, t)}
+ formatDate={(date) => fmtDay(date)}
+ bucket="day"
+ metricLabel={t("insights.sleep.compositionTitle")}
+ dayLinks
+ />
+ ) : null}
+ >
)}
diff --git a/src/components/labs/lab-biomarker-chart.tsx b/src/components/labs/lab-biomarker-chart.tsx
index ec2a1774e..7a8828340 100644
--- a/src/components/labs/lab-biomarker-chart.tsx
+++ b/src/components/labs/lab-biomarker-chart.tsx
@@ -26,8 +26,11 @@ import {
import { dateOnlyKey, isNoonUtcAnchor } from "@/lib/tz/date-only";
import { RichChartTooltip, type RichTooltipRow } from "../charts/chart-tooltip";
-import { TooltipDayAction, useCoarsePointer } from "../day/chart-day";
-import { openDay, useOpenDay } from "../day/day-layer-controller";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "../day/chart-day-links";
import { dateKeyOfInstant } from "../day/day-url";
import type { LabResultDto } from "./types";
import { useLabNumber } from "./use-lab-format";
@@ -114,45 +117,13 @@ export function LabBiomarkerChart({
: fmt.dateShortSmart(instant);
};
const [range, setRange] = useState("365");
- // v1.42 — a reading opens its day: a click on a fine pointer, the
- // tooltip's button on a touch screen. The open day's reading is ringed.
const timeZone = useDisplayTimezone();
- const coarse = useCoarsePointer();
- const openDayKey = useOpenDay();
const dayOf = (timestamp: number) => {
const instant = new Date(timestamp);
return isNoonUtcAnchor(instant)
? dateOnlyKey(instant)
: dateKeyOfInstant(instant, timeZone);
};
- const openReadingDay = (point: ChartPoint | undefined) => {
- if (!point) return;
- const ordered = [...readings]
- .filter((r) => r.value !== null)
- .sort(
- (a, b) => new Date(a.takenAt).getTime() - new Date(b.takenAt).getTime(),
- );
- const at = ordered.findIndex((r) => r.id === point.id);
- const before = at > 0 ? ordered[at - 1] : undefined;
- const date = dayOf(point.timestamp);
- openDay(date, {
- focus: {
- date,
- label: readings[0]?.analyte ?? "",
- value: labNumber(point.value),
- unit,
- compare:
- before && before.value !== null
- ? {
- label: t("day.previousReading", {
- date: labShortDate(before.takenAt),
- }),
- value: `${labNumber(before.value)} ${unit}`.trim(),
- }
- : undefined,
- },
- });
- };
// Capture "now" once at mount so the recency filter stays pure across
// re-renders (an inline `Date.now()` in render is impure).
const [nowMs] = useState(() => Date.now());
@@ -230,6 +201,43 @@ export function LabBiomarkerChart({
return [min >= 0 ? Math.max(0, min - pad) : min - pad, max + pad];
}, [points, lowerBound, upperBound, sourceBand]);
+ // v1.42 — a reading opens its day through the doors every day-linked
+ // chart has; the day opens with the reading on top and the one before it
+ // beside it. The open day's reading is ringed and its line dashed.
+ const chartDays = useChartDayLinks({
+ enabled: true,
+ days: points.map((point) => dayOf(point.timestamp)),
+ focusFor: (index) => {
+ const point = points[index];
+ if (!point) return null;
+ // The reading before it, in or out of the range in view.
+ const ordered = [...readings]
+ .filter((r) => r.value !== null)
+ .sort(
+ (x, y) =>
+ new Date(x.takenAt).getTime() - new Date(y.takenAt).getTime(),
+ );
+ const at = ordered.findIndex((r) => r.id === point.id);
+ const before = at > 0 ? ordered[at - 1] : undefined;
+ return {
+ label: readings[0]?.analyte ?? "",
+ value: labNumber(point.value),
+ unit,
+ compare:
+ before && before.value !== null
+ ? {
+ label: t("day.previousReading", {
+ date: labShortDate(before.takenAt),
+ }),
+ value: `${labNumber(before.value)} ${unit}`.trim(),
+ }
+ : undefined,
+ };
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined ? points[chartDays.openIndex] : undefined;
+
const animate = !prefersReducedMotion();
const primary = "var(--primary)";
// A second muted hue from the chart palette. Distinct from the primary band
@@ -260,188 +268,187 @@ export function LabBiomarkerChart({
) : (
-
- {
- const index = Number(state?.activeTooltipIndex);
- if (Number.isInteger(index))
- openReadingDay(points[index]);
- }
- }
- >
-
- labShortDate(ts)}
- tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
- stroke="var(--border)"
- minTickGap={32}
- />
- labNumber(v)}
- />
- {/* Reference window — muted band + dashed bounds. No alarm
+
+
+
+
+ labShortDate(ts)}
+ tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
+ stroke="var(--border)"
+ minTickGap={32}
+ />
+ labNumber(v)}
+ />
+ {/* Reference window — muted band + dashed bounds. No alarm
colour: the in/out verdict is shown by the neutral badge,
not by painting the chart red. */}
- {lowerBound != null && upperBound != null ? (
-
- ) : null}
- {lowerBound != null ? (
-
- ) : null}
- {upperBound != null ? (
-
- ) : null}
- {/* The source window — outlined, not filled, so it reads as a
+ {lowerBound != null && upperBound != null ? (
+
+ ) : null}
+ {lowerBound != null ? (
+
+ ) : null}
+ {upperBound != null ? (
+
+ ) : null}
+ {/* The source window — outlined, not filled, so it reads as a
second band over the catalog one rather than a second fill
competing with it. Same no-alarm-colour rule. */}
- {sourceBand &&
- sourceBand.low != null &&
- sourceBand.high != null ? (
-
- ) : null}
- {sourceBand &&
- sourceBand.low != null &&
- sourceBand.high == null ? (
-
- ) : null}
- {sourceBand &&
- sourceBand.high != null &&
- sourceBand.low == null ? (
-
- ) : null}
- {
- const active = props.active ?? false;
- const payload = props.payload as
- ReadonlyArray<{ payload?: ChartPoint }> | undefined;
- const point = payload?.[0]?.payload;
- if (!active || !point) {
- return ;
- }
- const rows: RichTooltipRow[] = [
- {
- name: t("labs.chart.valueLabel"),
- value: `${labNumber(point.value)} ${unit}`,
- color: primary,
- },
- ];
- // Name the window THIS reading was judged against. Two
- // readings on one chart can carry different printed windows,
- // so the band alone cannot answer it per point.
- if (point.referenceOrigin === "source") {
- rows.push({
- name: t("labs.chart.sourceRangeLabel"),
- value:
- point.sourceReferenceText ??
- `${formatReferenceRange(
- point.referenceLow,
- point.referenceHigh,
- labNumber,
- )} ${unit}`.trim(),
- color: secondary,
- });
- }
- return (
- openReadingDay(point)}
- />
- ) : undefined
- }
- />
- );
- }}
- />
- {points
- .filter(
- (point) =>
- openDayKey !== null &&
- dayOf(point.timestamp) === openDayKey,
- )
- .map((point) => (
-
- ))}
-
-
-
+ ) : null}
+ {sourceBand &&
+ sourceBand.low != null &&
+ sourceBand.high == null ? (
+
+ ) : null}
+ {sourceBand &&
+ sourceBand.high != null &&
+ sourceBand.low == null ? (
+
+ ) : null}
+ {openPoint ? (
+
+ ) : null}
+ {
+ const active = props.active ?? false;
+ const payload = props.payload as
+ ReadonlyArray<{ payload?: ChartPoint }> | undefined;
+ const point = payload?.[0]?.payload;
+ if (!active || !point) {
+ return ;
+ }
+ const rows: RichTooltipRow[] = [
+ {
+ name: t("labs.chart.valueLabel"),
+ value: `${labNumber(point.value)} ${unit}`,
+ color: primary,
+ },
+ ];
+ // Name the window THIS reading was judged against. Two
+ // readings on one chart can carry different printed windows,
+ // so the band alone cannot answer it per point.
+ if (point.referenceOrigin === "source") {
+ rows.push({
+ name: t("labs.chart.sourceRangeLabel"),
+ value:
+ point.sourceReferenceText ??
+ `${formatReferenceRange(
+ point.referenceLow,
+ point.referenceHigh,
+ labNumber,
+ )} ${unit}`.trim(),
+ color: secondary,
+ });
+ }
+ return (
+
+ );
+ }}
+ />
+ {points
+ .filter(
+ (point) =>
+ chartDays.openDay !== null &&
+ dayOf(point.timestamp) === chartDays.openDay,
+ )
+ .map((point) => (
+
+ ))}
+
+
+
+
+
{sourceBand ? (
{sourceBand.mixed
diff --git a/src/components/mental-health/assessment-history-chart.tsx b/src/components/mental-health/assessment-history-chart.tsx
index 8dd09f896..1cdf57adb 100644
--- a/src/components/mental-health/assessment-history-chart.tsx
+++ b/src/components/mental-health/assessment-history-chart.tsx
@@ -25,6 +25,7 @@ import {
CartesianGrid,
ComposedChart,
Line,
+ ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
@@ -34,7 +35,17 @@ import {
import { RichChartTooltip, type RichTooltipRow } from "../charts/chart-tooltip";
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
-import { useTranslations, useFormatters } from "@/lib/i18n/context";
+import {
+ useDisplayTimezone,
+ useTranslations,
+ useFormatters,
+} from "@/lib/i18n/context";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "../day/chart-day-links";
+import { dateKeyOfInstant } from "../day/day-url";
import { INSTRUMENTS } from "@/lib/mental-health/instruments";
import type { AssessmentRow, InstrumentId } from "./types";
@@ -69,6 +80,26 @@ export function AssessmentHistoryChart({
}));
}, [rows]);
+ // v1.42 — each result opens the day it was taken on, through the doors
+ // every day-linked chart has. The dated list under the chart is the
+ // keyboard way to the same days.
+ const timeZone = useDisplayTimezone();
+ const chartDays = useChartDayLinks({
+ enabled: true,
+ days: points.map((point) => dateKeyOfInstant(point.timestamp, timeZone)),
+ focusFor: (index) => {
+ const point = points[index];
+ return point
+ ? {
+ label: t(`mentalHealth.instrument.${def.i18nKey}`),
+ value: String(point.value),
+ }
+ : null;
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined ? points[chartDays.openIndex] : undefined;
+
const animate = !prefersReducedMotion();
const primary = "var(--primary)";
const gradientId = `mh-trend-${instrument}`;
@@ -82,86 +113,108 @@ export function AssessmentHistoryChart({
}
return (
-
-
+
-
-
-
-
-
-
-
-
fmt.dateShortSmart(new Date(ts))}
- tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
- stroke="var(--border)"
- minTickGap={32}
- />
-
- {
- const active = props.active ?? false;
- const payload = props.payload as
- ReadonlyArray<{ payload?: ChartPoint }> | undefined;
- const point = payload?.[0]?.payload;
- if (!active || !point) {
- return ;
- }
- const rowsOut: RichTooltipRow[] = [
- {
- name: t("mentalHealth.history.totalLabel"),
- value: String(point.value),
- color: primary,
- },
- {
- name: t("mentalHealth.history.bandLabel"),
- value: t(`mentalHealth.band.${instrument}.${point.band}`),
- color: "var(--muted-foreground)",
- },
- ];
- return (
-
- );
- }}
- />
-
-
-
-
+
+
+
+
+
+
+
+
+
+ fmt.dateShortSmart(new Date(ts))}
+ tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
+ stroke="var(--border)"
+ minTickGap={32}
+ />
+
+ {openPoint ? (
+
+ ) : null}
+ {
+ const active = props.active ?? false;
+ const payload = props.payload as
+ ReadonlyArray<{ payload?: ChartPoint }> | undefined;
+ const point = payload?.[0]?.payload;
+ if (!active || !point) {
+ return ;
+ }
+ const rowsOut: RichTooltipRow[] = [
+ {
+ name: t("mentalHealth.history.totalLabel"),
+ value: String(point.value),
+ color: primary,
+ },
+ {
+ name: t("mentalHealth.history.bandLabel"),
+ value: t(`mentalHealth.band.${instrument}.${point.band}`),
+ color: "var(--muted-foreground)",
+ },
+ ];
+ return (
+
+ );
+ }}
+ />
+
+
+
+
+
+
+
);
}
diff --git a/src/components/mental-health/assessment-history.tsx b/src/components/mental-health/assessment-history.tsx
index 42ffa7abd..685742cfe 100644
--- a/src/components/mental-health/assessment-history.tsx
+++ b/src/components/mental-health/assessment-history.tsx
@@ -36,6 +36,8 @@ import { crisisResourcesForLocale } from "@/lib/mental-health/crisis-resources";
import { Activity, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
+import { DayLinkAt } from "@/components/day/day-link";
+
import { AssessmentItemBreakdown } from "./assessment-item-breakdown";
import { CrisisCard } from "./crisis-card";
import type { AssessmentRow, CrisisSet, InstrumentId } from "./types";
@@ -132,9 +134,11 @@ export function AssessmentHistory({
return (
-
+ {/* v1.42 — the date opens the day around the result: the
+ keyboard way to the days the chart above opens. */}
+
{formatDate(row.takenAt)}
-
+
{flagged && (
Date: Thu, 8 Oct 2026 15:30:12 +0200
Subject: [PATCH 2/6] feat: prepare the next visit from the server's notable
window
The block under a planned visit read the day index and up to twelve days
to find what changed, so a dose change on a quiet day could fall out of
the picked days. It now reads GET /api/day/notable for the stretch from
the last visit to today: every change the server names, every notable
reading.
Add a guard that walks every chart, chart mount and calendar heatmap and
fails when one drawn in days lacks the day doors and is not on the
reasoned NOT_HERE list. Give the dose-strength curve, the efficacy chart,
the mood dimensions, the intraday pulse header and the environment note
the same doors.
---
messages/de.json | 4 +
messages/en.json | 4 +
messages/es.json | 4 +
messages/fr.json | 4 +
messages/it.json | 4 +
messages/ko.json | 4 +
messages/pl.json | 4 +
.../compliance-heatmap-a11y.test.tsx | 35 +-
.../__tests__/mood-heatmap-a11y.test.tsx | 33 +-
src/components/charts/chart-data-table.tsx | 7 +-
src/components/charts/compliance-heatmap.tsx | 14 +-
src/components/charts/health-chart.tsx | 1 -
.../cycle/__tests__/bbt-chart.test.tsx | 7 +-
src/components/dashboard/environment-chip.tsx | 14 +-
.../day/__tests__/chart-day.test.ts | 89 +++-
.../__tests__/day-door-coverage-guard.test.ts | 270 ++++++++++++
src/components/day/chart-day.tsx | 15 +-
src/components/day/since-last-visit.tsx | 160 +++----
.../sleep-stage-stacked-bar.test.tsx | 7 +-
.../insights/intraday-pulse-chart.tsx | 9 +-
.../insights/mood/mood-dimension-trends.tsx | 108 ++++-
.../detail/efficacy/efficacy-chart.tsx | 392 +++++++++++-------
.../medications/dose-strength-curve.tsx | 241 ++++++++---
src/lib/query-keys/day.ts | 3 +
24 files changed, 1048 insertions(+), 385 deletions(-)
create mode 100644 src/components/day/__tests__/day-door-coverage-guard.test.ts
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/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(
- /]*data-slot="compliance-heatmap-day-list"[^>]*>([\s\S]*?)<\/ul>/,
+ const table = html.match(
+ /]*data-slot="chart-data-table"[^>]*>([\s\S]*?)<\/table>/,
);
- expect(listMatch).not.toBeNull();
- const items = listMatch![1].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(
- /]*data-slot="mood-heatmap-day-list"[^>]*>([\s\S]*?)<\/ul>/,
+ const table = html.match(
+ /]*data-slot="chart-data-table"[^>]*>([\s\S]*?)<\/table>/,
);
- expect(listMatch).not.toBeNull();
- const items = listMatch![1].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 98e1aee0d..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 {
@@ -229,7 +234,7 @@ export function ChartDataTable({
>
) : (
- formatValue(numeric)
+ (column.format ?? formatValue)(numeric)
)}
);
diff --git a/src/components/charts/compliance-heatmap.tsx b/src/components/charts/compliance-heatmap.tsx
index b6c30f1c1..67bad9159 100644
--- a/src/components/charts/compliance-heatmap.tsx
+++ b/src/components/charts/compliance-heatmap.tsx
@@ -375,6 +375,8 @@ export function ComplianceHeatmap({
points={activeCells.map((cell) => ({
date: cell.dateKey,
timestamp: dayAnchor(cell.dateKey),
+ taken: cell.data.taken,
+ expected: cell.data.expected,
rate:
cell.data.expected > 0
? Math.min(
@@ -383,8 +385,16 @@ export function ComplianceHeatmap({
)
: undefined,
}))}
- columns={[{ key: "rate", label: t("medications.compliance") }]}
- formatValue={(value) => `${value} %`}
+ columns={[
+ { key: "taken", label: t("medications.taken") },
+ { key: "expected", label: t("doctorReport.colExpected") },
+ {
+ key: "rate",
+ label: t("medications.compliance"),
+ format: (value) => `${value} %`,
+ },
+ ]}
+ formatValue={(value) => String(value)}
formatDate={(date) => formatDay(dateOnlyKey(date))}
bucket="day"
metricLabel={t("insights.medicationCompliance")}
diff --git a/src/components/charts/health-chart.tsx b/src/components/charts/health-chart.tsx
index 2d74f3c89..3f539c146 100644
--- a/src/components/charts/health-chart.tsx
+++ b/src/components/charts/health-chart.tsx
@@ -1760,7 +1760,6 @@ export function HealthChart({
: [],
focusFor: (index) => dayFocusFor(dayLinkSource?.[index]),
});
- const coarsePointer = chartDays.coarse;
const openDayIndex = chartDays.openIndex;
const openDayPoint =
openDayIndex !== undefined ? chartData?.[openDayIndex] : undefined;
diff --git a/src/components/cycle/__tests__/bbt-chart.test.tsx b/src/components/cycle/__tests__/bbt-chart.test.tsx
index 52c9fc140..baf1661b9 100644
--- a/src/components/cycle/__tests__/bbt-chart.test.tsx
+++ b/src/components/cycle/__tests__/bbt-chart.test.tsx
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
// `useUnitDisplay` reads the account through react-query; these static
// renders have no QueryClient, so the hook is a real display for a fixed
@@ -18,9 +19,13 @@ import { unitDisplayFor } from "@/__tests__/helpers/unit-display-mock";
import { I18nProvider } from "@/lib/i18n/context";
import type { CalendarDay } from "../types";
+// v1.42 — the chart's row of day dots reads the day index through
+// react-query, so the static render carries a client (it never fetches).
function render(node: React.ReactNode) {
return renderToStaticMarkup(
- {node} ,
+
+ {node}
+ ,
);
}
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..4dd79b891
--- /dev/null
+++ b/src/components/day/__tests__/day-door-coverage-guard.test.ts
@@ -0,0 +1,270 @@
+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 (click, the touch tooltip's button,
+ * 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 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 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",
+ "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/app/page-client.tsx":
+ "The dashboard is today (decision D12): its charts are a summary of the record, and past days open as a layer over it from a date, never from the dashboard's own charts.",
+ "src/components/charts/medication-compliance-chart.tsx":
+ "Mounted on the dashboard only (see above); the adherence days open from the intake calendar on the medication insights page.",
+ "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 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.
+ expect(doors.mounts).toBeGreaterThanOrEqual(11);
+ // HealthChart, the mood line and the nutrient bars themselves, sleep
+ // stages, mood dimensions, lab marker, custom metric, questionnaire,
+ // basal temperature, dose strength, efficacy: eleven.
+ expect(
+ doors.chartFiles.length,
+ doors.chartFiles.join("\n"),
+ ).toBeGreaterThanOrEqual(11);
+ // 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/chart-day.tsx b/src/components/day/chart-day.tsx
index 34b5ec77c..8826fcb23 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";
@@ -59,19 +59,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();
diff --git a/src/components/day/since-last-visit.tsx b/src/components/day/since-last-visit.tsx
index 624fc1145..9a7768285 100644
--- a/src/components/day/since-last-visit.tsx
+++ b/src/components/day/since-last-visit.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { useState } from "react";
-import { useQueries } from "@tanstack/react-query";
+import { useQuery } from "@tanstack/react-query";
import {
Activity,
CircleDashed,
@@ -24,8 +24,7 @@ import type {
DateKey,
DayEventKind,
DayNotable,
- DayResponse,
- DaySectionKey,
+ DayNotableWindowResponse,
} from "@/lib/day/contract";
import {
useDisplayTimezone,
@@ -37,9 +36,8 @@ import { queryKeys } from "@/lib/query-keys";
import { DAY_SECTION_LABEL, useNotableText } from "./day-sections";
import { DayLink } from "./day-link";
-import { dateKeyOfInstant, shiftDateKey, daysBetween } from "./day-url";
+import { dateKeyOfInstant } from "./day-url";
import { tileKeyOf } from "./day-values-model";
-import { useDayIndex } from "./use-day";
import { useDayValueFormat } from "./use-day-value-format";
import { useTodayKey } from "./use-today-key";
@@ -50,35 +48,12 @@ import { useTodayKey } from "./use-today-key";
* opening its day. Compiled from the record without any judgement; the
* wording is the day view's own.
*
- * Built from what the day routes already answer: the index names the days
- * that carry a context change or a notable observation, and those days (at
- * most {@link MAX_DAYS_READ}) are read for their entries. Nothing is
- * recomputed here.
+ * One read, `GET /api/day/notable` for the window from the last visit to
+ * today: the server lists every context change in it (a dose change always,
+ * however quiet the day around it) and every notable observation. Nothing is
+ * recomputed here; this only spells the rows.
*/
-/** Sections whose presence alone makes a day worth reading here. */
-const CONTEXT_SECTIONS: readonly DaySectionKey[] = [
- "illness",
- "labs",
- "vaccinations",
- "visits",
- "allergies",
-];
-
-/** Entry kinds that are a change of context, the rows this block lists. */
-const CONTEXT_EVENTS: ReadonlySet = new Set([
- "doseChange",
- "medicationStart",
- "medicationEnd",
- "pauseStart",
- "courseStart",
- "illnessOnset",
- "allergyOnset",
- "labResult",
- "procedure",
- "vaccination",
-]);
-
const EVENT_ICON: Partial> = {
doseChange: Pill,
medicationStart: Pill,
@@ -92,12 +67,10 @@ const EVENT_ICON: Partial> = {
vaccination: Syringe,
};
-/** Days read for their entries, newest kept when there are more. */
-export const MAX_DAYS_READ = 12;
/** Rows shown before "All". */
export const VISIBLE_ROWS = 5;
-interface PrepRow {
+export interface PrepRow {
key: string;
date: DateKey;
Icon: LucideIcon;
@@ -105,28 +78,41 @@ interface PrepRow {
meta: string | null;
}
-/** The days to read: notable ones first, then context days, newest first. */
-export function pickPreparationDays(
- index: {
- days: Record;
- notable: readonly string[];
+/**
+ * The window's rows, oldest first: each context change as the server named
+ * it, each notable observation spelled by the caller. A first reading of a
+ * kind is left out here (it says nothing about the stretch since the visit).
+ */
+export function preparationRows(
+ window: Pick,
+ spell: {
+ notableTitle: (notable: DayNotable) => string;
+ notableText: (notable: DayNotable) => string | null;
+ countMeta: (count: number) => string | null;
},
- max = MAX_DAYS_READ,
-): DateKey[] {
- const notable = [...new Set(index.notable)].sort().reverse();
- const context = Object.entries(index.days)
- .filter(([, sections]) =>
- sections.some((s) => CONTEXT_SECTIONS.includes(s as DaySectionKey)),
- )
- .map(([day]) => day)
- .sort()
- .reverse();
- const picked: DateKey[] = [];
- for (const day of [...notable, ...context]) {
- if (!picked.includes(day)) picked.push(day);
- if (picked.length >= max) break;
+): PrepRow[] {
+ const rows: PrepRow[] = [];
+ for (const change of window.changes) {
+ rows.push({
+ key: `${change.kind}-${change.id}-${change.date}`,
+ date: change.date,
+ Icon: EVENT_ICON[change.kind] ?? FileText,
+ title: change.title,
+ meta: spell.countMeta(change.count),
+ });
}
- return picked.sort();
+ for (const notable of window.observations) {
+ if (notable.kind === "firstValue") continue;
+ rows.push({
+ key: `notable-${notable.date}-${notable.kind}-${notable.type ?? ""}`,
+ date: notable.date,
+ Icon: notable.kind === "gap" ? CircleDashed : Activity,
+ title: spell.notableTitle(notable),
+ meta: spell.notableText(notable),
+ });
+ }
+ // A stable sort: the server's order holds within a day.
+ return rows.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
}
export function SinceLastVisit({
@@ -147,20 +133,16 @@ export function SinceLastVisit({
const [showAll, setShowAll] = useState(false);
const lastDay = dateKeyOfInstant(last.occurredAt, timeZone);
- // The window starts the day after the last visit and ends today; the index
- // answers at most a year at a time, which is the stretch that matters here.
- const from =
- daysBetween(shiftDateKey(lastDay, 1), today) > 365
- ? shiftDateKey(today, -365)
- : shiftDateKey(lastDay, 1);
- const index = useDayIndex(from, today, from <= today);
- const days = index.data ? pickPreparationDays(index.data) : [];
- const reads = useQueries({
- queries: days.map((day) => ({
- queryKey: queryKeys.day(day),
- queryFn: () => apiGet(`/api/day/${day}`),
- staleTime: 5 * 60_000,
- })),
+ // From the last visit's own day (a dose changed at the visit belongs to
+ // what the next one should know) to today. The server caps the span.
+ const window = useQuery({
+ queryKey: queryKeys.dayNotable(lastDay, today),
+ queryFn: () => {
+ const params = new URLSearchParams({ from: lastDay, to: today });
+ return apiGet(`/api/day/notable?${params}`);
+ },
+ enabled: lastDay <= today,
+ staleTime: 5 * 60_000,
});
// "Blood pressure 152/94 mmHg": the reading a notable day is about, in the
@@ -186,37 +168,17 @@ export function SinceLastVisit({
return `${label} ${shown.value}${shown.unit ? ` ${shown.unit}` : ""}`;
};
- const rows: PrepRow[] = [];
- reads.forEach((read, i) => {
- const day = days[i];
- if (!day || !read.data) return;
- for (const event of read.data.events) {
- if (!CONTEXT_EVENTS.has(event.kind)) continue;
- rows.push({
- key: `${event.kind}-${event.id}`,
- date: day,
- Icon: EVENT_ICON[event.kind] ?? FileText,
- title: event.title,
- meta: event.meta,
- });
- }
- for (const notable of read.data.notable) {
- if (notable.kind === "firstValue") continue;
- rows.push({
- key: `notable-${day}-${notable.kind}-${notable.type ?? ""}`,
- date: day,
- Icon: notable.kind === "gap" ? CircleDashed : Activity,
- title: notableTitle(notable),
- meta: notableText(notable),
- });
- }
- });
- rows.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
+ const rows = window.data
+ ? preparationRows(window.data, {
+ notableTitle,
+ notableText,
+ countMeta: (count) =>
+ count > 1 ? tCount("day.countEntries", count) : null,
+ })
+ : [];
- const loading =
- index.isPending ||
- reads.some((read) => read.isPending && read.fetchStatus !== "idle");
- const failed = index.isError || reads.some((read) => read.isError);
+ const loading = window.isPending && window.fetchStatus !== "idle";
+ const failed = window.isError;
if (!loading && !failed && rows.length === 0) return null;
// A preparation that could not be read is left out rather than shown half:
// the visit card stands on its own, and the day links stay everywhere else.
diff --git a/src/components/insights/__tests__/sleep-stage-stacked-bar.test.tsx b/src/components/insights/__tests__/sleep-stage-stacked-bar.test.tsx
index 3ff6b6baa..0abdb5b3c 100644
--- a/src/components/insights/__tests__/sleep-stage-stacked-bar.test.tsx
+++ b/src/components/insights/__tests__/sleep-stage-stacked-bar.test.tsx
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import {
@@ -31,9 +32,13 @@ import {
* path stays render-safe)
*/
+// v1.42 — the chart's row of day dots reads the day index through
+// react-query, so the static render carries a client (it never fetches).
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
- {node} ,
+
+ {node}
+ ,
);
}
diff --git a/src/components/insights/intraday-pulse-chart.tsx b/src/components/insights/intraday-pulse-chart.tsx
index cb50fcd43..42b7c0523 100644
--- a/src/components/insights/intraday-pulse-chart.tsx
+++ b/src/components/insights/intraday-pulse-chart.tsx
@@ -21,6 +21,7 @@ import { queryKeys } from "@/lib/query-keys";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { userDayKey, shiftDateKey, DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { TileHeader } from "@/components/insights/tile-header";
+import { DayLink } from "@/components/day/day-link";
import { Button } from "@/components/ui/button";
import { QueryErrorCard } from "@/components/ui/query-error-card";
import { Skeleton } from "@/components/ui/skeleton";
@@ -219,8 +220,12 @@ export function IntradayPulseChart({
>
-
- {dayLabel}
+ {/* v1.42 — the date opens the whole day this chart is one part
+ of, the one thing every date in the app does. */}
+
+
+ {dayLabel}
+
(30);
const present = dimensions.filter((d) => d.present);
@@ -105,6 +118,14 @@ export function MoodDimensionTrends({
return dimension ? t(dimension.labelKey) : key;
};
+ // v1.42 — each answered day opens its day, through the doors every
+ // day-linked chart has.
+ const rowDays = chartData.map((row) => String(row.date));
+ const chartDays = useChartDayLinks({
+ enabled: present.length > 0 && chartData.length > 0,
+ days: rowDays,
+ });
+
if (present.length === 0) {
return (
@@ -134,17 +155,27 @@ export function MoodDimensionTrends({
))}
-
+
value.slice(5)}
+ tickFormatter={(value: string) =>
+ fmt.dateShortSmartCalendar(value)
+ }
minTickGap={24}
/>
+ {chartDays.openIndex !== undefined ? (
+
+ ) : null}
{
+ const payload = props.payload as unknown as
+ | ReadonlyArray<{
+ dataKey?: string | number;
+ value?: number;
+ color?: string;
+ payload?: Record;
+ }>
+ | undefined;
+ const row = payload?.[0]?.payload;
+ if (!props.active || !row) {
+ return ;
+ }
+ const rows: RichTooltipRow[] = (payload ?? [])
+ .filter((item) => typeof item.value === "number")
+ .map((item) => ({
+ name: labelFor(String(item.dataKey)),
+ value: String(item.value),
+ color: item.color ?? "var(--chart-1)",
+ }));
+ return (
+
+ );
}}
- labelStyle={{ color: "var(--muted-foreground)" }}
- formatter={(value, name) => [
- String(value ?? ""),
- labelFor(String(name)),
- ]}
/>
{present.map((summary) => (
+
({ timestamp: dayAnchor(day) }))}
+ // The y axis (60) less the plot's negative left margin (20); the
+ // margin (8) on the right.
+ insetLeft={60 - 20}
+ insetRight={8}
+ />
+ {chartDays.active ? (
+ ({
+ ...row,
+ date: String(row.date),
+ timestamp: dayAnchor(String(row.date)),
+ }))}
+ columns={present.map((summary) => ({
+ key: summary.key,
+ label: labelFor(summary.key),
+ }))}
+ formatValue={(value) => String(value)}
+ formatDate={(date) => fmt.dateShortSmartCalendar(date)}
+ bucket="day"
+ metricLabel={t("insights.mood.dimensions.title")}
+ dayLinks
+ />
+ ) : null}
{present.map((summary) => {
diff --git a/src/components/medications/detail/efficacy/efficacy-chart.tsx b/src/components/medications/detail/efficacy/efficacy-chart.tsx
index a3e98f47f..0d0307570 100644
--- a/src/components/medications/detail/efficacy/efficacy-chart.tsx
+++ b/src/components/medications/detail/efficacy/efficacy-chart.tsx
@@ -23,10 +23,22 @@ import {
Tooltip,
ReferenceLine,
ReferenceArea,
+ ReferenceDot,
} from "recharts";
import { makeFormatters } from "@/lib/format-locale";
import { useDateFormatPreference, useTranslations } from "@/lib/i18n/context";
import { axisUnitSuffix } from "@/lib/charts/axis-unit";
+import {
+ RichChartTooltip,
+ type RichTooltipRow,
+} from "@/components/charts/chart-tooltip";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
+import { dateKeyOfInstant } from "@/components/day/day-url";
+import { dateOnlyKey, isNoonUtcAnchor } from "@/lib/tz/date-only";
export interface EfficacyChartTarget {
label: string;
@@ -137,6 +149,40 @@ export function EfficacyChart({
return [Math.floor(min - pad), Math.ceil(max + pad)];
}, [displaySeries]);
+ // v1.42 — each value of the target series opens its day, through the doors
+ // every day-linked chart has. The series and the adherence lane are two
+ // `` arrays on one time axis, so a click is placed by its x
+ // value, not by an index into the chart's data.
+ const seriesDays = displaySeries.map((p) => {
+ const instant = new Date(p.t);
+ return isNoonUtcAnchor(instant)
+ ? dateOnlyKey(instant)
+ : dateKeyOfInstant(instant, timezone);
+ });
+ const chartDays = useChartDayLinks({
+ enabled: displaySeries.length > 0,
+ days: seriesDays,
+ focusFor: (index) => {
+ const point = displaySeries[index];
+ if (!point) return null;
+ return {
+ label: target.label,
+ value: mode === "percent" ? `${point.value}%` : String(point.value),
+ unit: mode === "percent" ? undefined : (target.unit ?? undefined),
+ };
+ },
+ indexOfClick: (state) => {
+ const x = Number(state.activeLabel);
+ if (!Number.isFinite(x)) return null;
+ const at = displaySeries.findIndex((p) => p.t === x);
+ return at === -1 ? null : at;
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined
+ ? displaySeries[chartDays.openIndex]
+ : undefined;
+
if (seriesData.length === 0 || !domain) return null;
const unitSuffix = mode === "percent" ? "%" : target.unit;
@@ -145,153 +191,221 @@ export function EfficacyChart({
// domain max keeps the render pure (no `Date.now()` in the render body).
const rightEdge = domain[1];
return (
-
-
-
-
- fmt.date(new Date(v))}
- />
-
-
+
+
+
+
+
+ fmt.date(new Date(v))}
+ />
+
+
- {/* Population reference band — faint context, labelled "typical
+ {/* Population reference band — faint context, labelled "typical
range", explicitly NOT a target line. Hidden in percent mode:
an absolute band is meaningless once the series is normalized. */}
- {mode === "absolute" && target.referenceBand ? (
-
- ) : null}
+ {mode === "absolute" && target.referenceBand ? (
+
+ ) : null}
- {/* Shaded pause bands. An open pause runs to now. */}
- {pauses.map((p, i) => (
-
- ))}
+ {/* Shaded pause bands. An open pause runs to now. */}
+ {pauses.map((p, i) => (
+
+ ))}
- {/* Adherence lane — faint, hidden right axis. */}
-
-
- {/* The target series. */}
-
-
- {/* Start marker. */}
- {startMs !== null ? (
-
+
+ {/* The target series. */}
+
+
+ {/* Start marker. */}
+ {startMs !== null ? (
+
+ ) : null}
+
+ {/* Dose-change markers — quiet, dashed. */}
+ {doseChanges.map((d, i) => (
+
+ ))}
+
+ {/* The open day: the dashed line every chart draws through it,
+ and a ring on its value, which keeps it apart from the quiet
+ dose-change lines. */}
+ {openPoint ? (
+
+ ) : null}
+ {openPoint ? (
+
+ ) : null}
+
+ {
+ const payload = props.payload as unknown as
+ | ReadonlyArray<{
+ name?: string;
+ value?: number;
+ color?: string;
+ payload?: { t: number };
+ }>
+ | undefined;
+ if (!props.active || !payload || payload.length === 0) {
+ return ;
+ }
+ const x = payload[0]?.payload?.t;
+ const rows: RichTooltipRow[] = payload
+ .filter((item) => typeof item.value === "number")
+ .map((item) => {
+ const num = Number(item.value);
+ const value =
+ item.name === adherenceLabel
+ ? `${Math.round(num)}%`
+ : mode === "percent"
+ ? `${num}%`
+ : `${num}${target.unit ? ` ${target.unit}` : ""}`;
+ return {
+ name: String(item.name ?? ""),
+ value,
+ color: item.color ?? "var(--chart-1)",
+ };
+ });
+ const index =
+ typeof x === "number"
+ ? displaySeries.findIndex((p) => p.t === x)
+ : -1;
+ return (
+
+ );
}}
/>
- ) : null}
-
- {/* Dose-change markers — quiet, dashed. */}
- {doseChanges.map((d, i) => (
-
- ))}
-
- fmt.date(new Date(Number(v)))}
- formatter={(value, name) => {
- const num = Number(value);
- if (name === adherenceLabel) {
- return [`${Math.round(num)}%`, String(name)];
- }
- const text =
- mode === "percent"
- ? `${num}%`
- : `${num}${target.unit ? ` ${target.unit}` : ""}`;
- return [text, String(name)];
- }}
- />
-
-
+
+
+
+
);
}
diff --git a/src/components/medications/dose-strength-curve.tsx b/src/components/medications/dose-strength-curve.tsx
index 983977e1e..4b08d8082 100644
--- a/src/components/medications/dose-strength-curve.tsx
+++ b/src/components/medications/dose-strength-curve.tsx
@@ -39,13 +39,31 @@ import {
CartesianGrid,
Line,
LineChart,
+ ReferenceLine,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
-import { useTranslations, useFormatters } from "@/lib/i18n/context";
+import {
+ useDisplayTimezone,
+ useTranslations,
+ useFormatters,
+} from "@/lib/i18n/context";
+import { ChartDataTable } from "@/components/charts/chart-data-table";
+import {
+ RichChartTooltip,
+ type RichTooltipRow,
+} from "@/components/charts/chart-tooltip";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ dayAnchor,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
+import { dateKeyOfInstant } from "@/components/day/day-url";
+import { dateOnlyKey, isNoonUtcAnchor } from "@/lib/tz/date-only";
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
@@ -175,6 +193,44 @@ export function DoseStrengthCurve({
const unit = latest?.doseUnit ?? "mg";
+ // v1.42 — each dose change opens the day it took effect, through the doors
+ // every day-linked chart has. The point carried forward to today is not a
+ // change and opens nothing.
+ const timeZone = useDisplayTimezone();
+ const changeCount = Math.min(
+ doseChanges.filter(
+ (dc) =>
+ Number.isFinite(Date.parse(dc.effectiveFrom)) &&
+ Number.isFinite(dc.doseValue),
+ ).length,
+ chartData.length,
+ );
+ const pointDays = chartData.map((p, index) => {
+ if (index >= changeCount) return null;
+ const instant = new Date(p.t);
+ return isNoonUtcAnchor(instant)
+ ? dateOnlyKey(instant)
+ : dateKeyOfInstant(instant, timeZone);
+ });
+ const chartDays = useChartDayLinks({
+ enabled: hasCurve,
+ days: pointDays,
+ focusFor: (index) => {
+ const point = chartData[index];
+ return point
+ ? {
+ label: t("medications.doseStrength.tooltipLabel"),
+ value: fmt.number(point.dose),
+ unit,
+ }
+ : null;
+ },
+ });
+ const openPoint =
+ chartDays.openIndex !== undefined
+ ? chartData[chartDays.openIndex]
+ : undefined;
+
const body = isLoading ? (
{t("medications.doseStrength.empty")}
) : (
-
-
-
-
- fmt.dateShortSmart(new Date(v as number))}
- tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
- tickLine={false}
- axisLine={false}
- />
- fmt.number(v as number)}
- />
- fmt.dateShortSmart(new Date(v as number))}
- formatter={(value) => [
- `${fmt.number(value as number)} ${unit}`,
- t("medications.doseStrength.tooltipLabel"),
- ]}
- contentStyle={{
- backgroundColor: "var(--popover)",
- border: "1px solid var(--border)",
- borderRadius: "0.375rem",
- fontSize: "0.75rem",
- }}
- />
-
-
-
-
+ <>
+
+
+
+
+ fmt.dateShortSmart(new Date(v as number))}
+ tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
+ tickLine={false}
+ axisLine={false}
+ />
+ fmt.number(v as number)}
+ />
+ {openPoint ? (
+
+ ) : null}
+ {
+ const payload = props.payload as unknown as
+ | ReadonlyArray<{ payload?: { t: number; dose: number } }>
+ | undefined;
+ const point = payload?.[0]?.payload;
+ if (!props.active || !point) {
+ return ;
+ }
+ const rows: RichTooltipRow[] = [
+ {
+ name: t("medications.doseStrength.tooltipLabel"),
+ value: `${fmt.number(point.dose)} ${unit}`,
+ color: CURVE_COLOR,
+ },
+ ];
+ return (
+
+ );
+ }}
+ />
+
+
+
+
+ ({ timestamp: p.t }))}
+ axis="time"
+ // The margin (4) + the y axis (34) on the left, the margin (14) on
+ // the right.
+ insetLeft={4 + 34}
+ insetRight={14}
+ />
+ {chartDays.active ? (
+ ({
+ date: pointDays[index]!,
+ timestamp: dayAnchor(pointDays[index]!),
+ dose: p.dose,
+ }))}
+ columns={[
+ {
+ key: "dose",
+ label: t("medications.doseStrength.tooltipLabel"),
+ },
+ ]}
+ unit={unit}
+ formatValue={(value) => fmt.number(value)}
+ formatDate={(date) => fmt.dateShortSmartCalendar(date)}
+ bucket="day"
+ metricLabel={t("medications.doseStrength.title")}
+ dayLinks
+ />
+ ) : null}
+ >
);
return (
diff --git a/src/lib/query-keys/day.ts b/src/lib/query-keys/day.ts
index 778c91f6f..012ead3ba 100644
--- a/src/lib/query-keys/day.ts
+++ b/src/lib/query-keys/day.ts
@@ -15,4 +15,7 @@ export const dayKeys = {
day: (date: string) => ["day", "detail", date] as const,
/** `GET /api/day/index`: the window bounds are the key. */
dayIndex: (from: string, to: string) => ["day", "index", from, to] as const,
+ /** `GET /api/day/notable`: what changed in a window, for a visit. */
+ dayNotable: (from: string, to: string) =>
+ ["day", "notable", from, to] as const,
};
From fee6088e0821c2aac807c9bda463012baca83525 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?=
Date: Thu, 8 Oct 2026 15:56:40 +0200
Subject: [PATCH 3/6] feat: open the day with one tap and from every place a
day is shown
A tap on a point, a bar, a calendar cell or a date now opens the day at
once, as a click does; the tooltip's second step is gone and the tapped
value heads the day. The dashboard's charts (not its today area), the
adherence chart, the rhythm events, the ECG list and detail and the rest
mode notes open their days too.
The day's header carries the close control top left, the Coach panel's
own toggle and glyph, the date on one centred line and the arrows on the
right. While the day is docked, the Coach button and the documents bar
move clear of it.
Smooth the layer: the tooltip no longer glides into place on touch, the
neighbouring day is read before a step, the sheet animates in 300 ms and
not at all under reduced motion, and the opener stays put while the page
beside the docked day reflows.
---
e2e/day-doors.spec.ts | 291 ++++++++++++++++++
e2e/day-view.spec.ts | 115 ++-----
e2e/setup/day-doors-fixture.ts | 90 ++++++
e2e/setup/day-mock.ts | 115 +++++++
e2e/setup/global-setup.ts | 49 +++
messages/de.json | 6 +-
messages/en.json | 6 +-
messages/es.json | 6 +-
messages/fr.json | 6 +-
messages/it.json | 6 +-
messages/ko.json | 6 +-
messages/pl.json | 6 +-
src/app/page-client.tsx | 9 +
src/components/charts/health-chart.tsx | 5 -
.../charts/medication-compliance-chart.tsx | 267 +++++++++-------
src/components/charts/mood-chart.tsx | 11 +-
.../charts/nutrient-daily-bar-chart.tsx | 1 -
.../custom-metrics/custom-metric-chart.tsx | 1 -
src/components/cycle/bbt-chart.tsx | 20 +-
.../__tests__/day-door-coverage-guard.test.ts | 27 +-
.../day/__tests__/day-not-here-guard.test.ts | 16 +-
.../day/__tests__/day-view.test.tsx | 1 +
src/components/day/chart-day-links.tsx | 60 ++--
src/components/day/chart-day.tsx | 30 +-
src/components/day/day-layer-controller.ts | 23 +-
src/components/day/day-layer.tsx | 78 ++++-
src/components/day/day-view.tsx | 103 +++++--
src/components/day/heatmap-day.tsx | 31 +-
src/components/day/use-day.ts | 32 +-
.../documents/document-bulk-bar.tsx | 4 +
.../__tests__/health-score-card.test.tsx | 11 +-
src/components/insights/ecg-detail.tsx | 12 +-
src/components/insights/ecg-section.tsx | 41 ++-
src/components/insights/health-score-card.tsx | 37 ++-
src/components/insights/layout-coach-fab.tsx | 7 +-
.../insights/mood/mood-dimension-trends.tsx | 1 -
src/components/insights/rest-mode-banner.tsx | 15 +-
.../insights/rhythm-events-card.tsx | 6 +-
.../insights/sleep-stage-stacked-bar.tsx | 4 -
src/components/labs/lab-biomarker-chart.tsx | 1 -
.../detail/efficacy/efficacy-chart.tsx | 7 -
.../medications/dose-strength-curve.tsx | 1 -
.../assessment-history-chart.tsx | 1 -
43 files changed, 1114 insertions(+), 451 deletions(-)
create mode 100644 e2e/day-doors.spec.ts
create mode 100644 e2e/setup/day-doors-fixture.ts
create mode 100644 e2e/setup/day-mock.ts
diff --git a/e2e/day-doors.spec.ts b/e2e/day-doors.spec.ts
new file mode 100644
index 000000000..af3b4c2ea
--- /dev/null
+++ b/e2e/day-doors.spec.ts
@@ -0,0 +1,291 @@
+import type { Locator, Page, TestInfo } from "@playwright/test";
+
+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 door: a click on a point (or a calendar cell) opens
+ * the day beside the page, and on a touch screen a tap does the same as a
+ * bottom sheet, the tapped value on top. 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)) {
+ // One tap, the same door as the click: no tooltip step in between.
+ await page.touchscreen.tap(x, y);
+ 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();
+ 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");
+ 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 });
+ await page.goto("/insights/weight");
+ const fab = page.locator('[data-slot="coach-fab"]');
+ test.skip((await fab.count()) === 0, "no Coach on this account");
+ 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..43806f074 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";
@@ -14,103 +15,20 @@ import { MOBILE_ROUTES_ANALYTE } from "./setup/mobile-routes-fixture";
* day, what the history does, and where no door is.
*
* - a chart point opens the day beside the chart (desktop);
- * - on a touch screen the first tap shows the value and the tooltip offers
- * the day, the second opens it as a bottom sheet;
+ * - on a touch screen a tap on a point opens the day at once, as a bottom
+ * sheet with the tapped value on top (the maintainer's call on the beta:
+ * the two-step tooltip broke the flow);
* - a date in a list opens the day while the row keeps its own target;
* - `?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` /
+ * `chart-plot[data-day-links]`, `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 {
@@ -233,7 +151,7 @@ test.describe("the day view", () => {
await expect(page).toHaveURL(/\/mood$/);
});
- test("on a phone the first tap shows the value, the second opens the day", async ({
+ test("on a phone a tap on a point opens its day at once", async ({
page,
}, testInfo) => {
test.skip(testInfo.project.name !== "chromium-mobile", "touch only");
@@ -244,14 +162,12 @@ test.describe("the day view", () => {
await plot.scrollIntoViewIfNeeded();
await expect(plot).toBeVisible();
const box = (await plot.boundingBox())!;
+ // One tap, the same door as a click on a desktop: the day opens as a
+ // bottom sheet with the tapped value on top.
await page.touchscreen.tap(box.x + box.width * 0.8, box.y + box.height / 2);
- const open = page.locator('[data-slot="chart-tooltip-open-day"]');
- await expect(open).toBeVisible();
- // A tap alone never opens a sheet.
- await expect(panel(page)).toHaveCount(0);
- await open.tap();
await expect(panel(page)).toBeVisible();
await expect(panel(page)).toHaveAttribute("data-shell", "bottom");
+ await expect(page.locator('[data-slot="day-focus"]')).toBeVisible();
});
test("the dashboard's today area offers no day door", async ({ page }) => {
@@ -259,8 +175,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 b9b9399de..2aa8f3350 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -12201,11 +12201,11 @@
"captureShort": "Erfassen",
"inTimelineShort": "Zeitleiste",
"askCoachPrompt": "Was war am {date}?",
- "chartHintTouch": "Antippen zeigt den Wert.",
+ "chartHintTouch": "Antippen eines Punkts öffnet den Tag.",
"chartHintBar": "Klick auf einen Balken öffnet den Tag.",
- "chartHintTouchBar": "Antippen zeigt die Werte.",
+ "chartHintTouchBar": "Antippen eines Balkens öffnet den Tag.",
"chartHintCell": "Klick auf einen Tag öffnet ihn.",
- "chartHintTouchCell": "Antippen zeigt den Wert des Tages.",
+ "chartHintTouchCell": "Antippen eines Tages öffnet ihn.",
"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 7efb7a78b..f5e55df8b 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -12201,11 +12201,11 @@
"captureShort": "Log",
"inTimelineShort": "Timeline",
"askCoachPrompt": "What happened on {date}?",
- "chartHintTouch": "Tap a point to see its value.",
+ "chartHintTouch": "Tap a point to open its day.",
"chartHintBar": "Click a bar to open its day.",
- "chartHintTouchBar": "Tap a bar to see its values.",
+ "chartHintTouchBar": "Tap a bar to open its day.",
"chartHintCell": "Click a day to open it.",
- "chartHintTouchCell": "Tap a day to see its value.",
+ "chartHintTouchCell": "Tap a day to open it.",
"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 e38b9e1a8..2a458aa35 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -12201,11 +12201,11 @@
"captureShort": "Registrar",
"inTimelineShort": "Cronología",
"askCoachPrompt": "¿Qué pasó el {date}?",
- "chartHintTouch": "Toca un punto para ver su valor.",
+ "chartHintTouch": "Toca un punto para abrir su día.",
"chartHintBar": "Haz clic en una barra para abrir su día.",
- "chartHintTouchBar": "Toca una barra para ver sus valores.",
+ "chartHintTouchBar": "Toca una barra para abrir su día.",
"chartHintCell": "Haz clic en un día para abrirlo.",
- "chartHintTouchCell": "Toca un día para ver su valor.",
+ "chartHintTouchCell": "Toca un día para abrirlo.",
"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 9070b5fdc..70d2bd366 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -12201,11 +12201,11 @@
"captureShort": "Enregistrer",
"inTimelineShort": "Chronologie",
"askCoachPrompt": "Que s’est-il passé le {date} ?",
- "chartHintTouch": "Touchez un point pour voir sa valeur.",
+ "chartHintTouch": "Touchez un point pour ouvrir son jour.",
"chartHintBar": "Cliquez sur une barre pour ouvrir son jour.",
- "chartHintTouchBar": "Touchez une barre pour voir ses valeurs.",
+ "chartHintTouchBar": "Touchez une barre pour ouvrir son jour.",
"chartHintCell": "Cliquez sur un jour pour l’ouvrir.",
- "chartHintTouchCell": "Touchez un jour pour voir sa valeur.",
+ "chartHintTouchCell": "Touchez un jour pour l’ouvrir.",
"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 7da2126a2..9dfef1da6 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -12201,11 +12201,11 @@
"captureShort": "Registra",
"inTimelineShort": "Cronologia",
"askCoachPrompt": "Cosa è successo il {date}?",
- "chartHintTouch": "Tocca un punto per vederne il valore.",
+ "chartHintTouch": "Tocca un punto per aprire il suo giorno.",
"chartHintBar": "Fai clic su una barra per aprire il suo giorno.",
- "chartHintTouchBar": "Tocca una barra per vederne i valori.",
+ "chartHintTouchBar": "Tocca una barra per aprire il suo giorno.",
"chartHintCell": "Fai clic su un giorno per aprirlo.",
- "chartHintTouchCell": "Tocca un giorno per vederne il valore.",
+ "chartHintTouchCell": "Tocca un giorno per aprirlo.",
"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 ccd0eb935..484effaaa 100644
--- a/messages/ko.json
+++ b/messages/ko.json
@@ -12201,11 +12201,11 @@
"captureShort": "기록",
"inTimelineShort": "타임라인",
"askCoachPrompt": "{date}에 무슨 일이 있었나요?",
- "chartHintTouch": "점을 탭하면 값이 보여요.",
+ "chartHintTouch": "점을 탭하면 그날이 열려요.",
"chartHintBar": "막대를 클릭하면 그날이 열려요.",
- "chartHintTouchBar": "막대를 탭하면 값이 보여요.",
+ "chartHintTouchBar": "막대를 탭하면 그날이 열려요.",
"chartHintCell": "날짜 칸을 클릭하면 그날이 열려요.",
- "chartHintTouchCell": "날짜 칸을 탭하면 값이 보여요.",
+ "chartHintTouchCell": "날짜 칸을 탭하면 그날이 열려요.",
"coachChips": "이 답변에 쓰인 날",
"description": "이 날에 대한 모든 기록이에요.",
"openDocument": "문서 열기",
diff --git a/messages/pl.json b/messages/pl.json
index 032c99b02..d07ef24d2 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -12201,11 +12201,11 @@
"captureShort": "Zapisz",
"inTimelineShort": "Oś czasu",
"askCoachPrompt": "Co się działo {date}?",
- "chartHintTouch": "Dotknij punktu, aby zobaczyć wartość.",
+ "chartHintTouch": "Dotknij punktu, aby otworzyć jego dzień.",
"chartHintBar": "Kliknij słupek, aby otworzyć jego dzień.",
- "chartHintTouchBar": "Dotknij słupka, aby zobaczyć wartości.",
+ "chartHintTouchBar": "Dotknij słupka, aby otworzyć jego dzień.",
"chartHintCell": "Kliknij dzień, aby go otworzyć.",
- "chartHintTouchCell": "Dotknij dnia, aby zobaczyć jego wartość.",
+ "chartHintTouchCell": "Dotknij dnia, aby go otworzyć.",
"coachChips": "Dni w tej odpowiedzi",
"description": "Wszystko, co Twoje wpisy zawierają dla tego dnia.",
"openDocument": "Otwórz dokument",
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/health-chart.tsx b/src/components/charts/health-chart.tsx
index 3f539c146..c31fe7eca 100644
--- a/src/components/charts/health-chart.tsx
+++ b/src/components/charts/health-chart.tsx
@@ -2404,11 +2404,6 @@ export function HealthChart({
: dateLabel
}
rows={rows}
- action={chartDays.tooltipAction(
- hoverPoint
- ? dayLinkSource?.indexOf(hoverPoint)
- : undefined,
- )}
/>
);
}}
diff --git a/src/components/charts/medication-compliance-chart.tsx b/src/components/charts/medication-compliance-chart.tsx
index fa5aefa0e..4fb12ca5d 100644
--- a/src/components/charts/medication-compliance-chart.tsx
+++ b/src/components/charts/medication-compliance-chart.tsx
@@ -70,6 +70,12 @@ import { chooseTickInterval } from "@/lib/charts/x-axis-density";
import { apiGet } from "@/lib/api/api-fetch";
import { shouldFireDataReady } from "@/lib/charts/data-ready-latch";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
+import { chartPointDayKey } from "@/components/day/chart-day";
+import {
+ ChartDayFooter,
+ OPEN_DAY_LINE,
+ useChartDayLinks,
+} from "@/components/day/chart-day-links";
interface DailyCompliancePoint {
/** Berlin calendar day, "YYYY-MM-DD". */
@@ -205,6 +211,11 @@ interface MedicationComplianceChartProps {
* Optional and repeat-safe.
*/
onDataReady?: () => void;
+ /**
+ * v1.42 — each day's point opens that day, through the doors every
+ * day-linked chart has (`useChartDayLinks`).
+ */
+ dayLinks?: boolean;
}
export function MedicationComplianceChart({
@@ -212,6 +223,7 @@ export function MedicationComplianceChart({
userTimezone = DEFAULT_TIMEZONE,
compareBaseline,
onDataReady,
+ dayLinks = false,
}: MedicationComplianceChartProps) {
// v1.4.27 R4 RC3 — the prop is accepted so the dashboard can pass
// `compareBaseline={compareBaseline}` uniformly across every chart.
@@ -343,6 +355,17 @@ export function MedicationComplianceChart({
};
const displayTitle = title ?? t("dashboard.medications");
+
+ const chartDays = useChartDayLinks({
+ enabled: dayLinks && chartData.length >= 3,
+ days: chartData.map((point) => chartPointDayKey(point.timestamp)),
+ focusFor: (index) => {
+ const point = chartData[index];
+ return point
+ ? { label: displayTitle, value: `${fmt.integer(point.rate)} %` }
+ : null;
+ },
+ });
const yAxisFormatter = (value: number) => `${fmt.integer(value)} %`;
const animationsEnabled = !prefersReducedMotion();
@@ -535,121 +558,145 @@ export function MedicationComplianceChart({
/>
)
) : (
-
-
-
-
-
-
- {
- const { active, payload } = props as unknown as {
- active?: boolean;
- payload?: Array<{
- value?: number;
- color?: string;
- payload?: ChartPoint;
- }>;
- };
- if (!active || !payload?.length) return null;
- const ts = payload[0]?.payload?.timestamp;
- const dateLabel = ts ? tzFmt.date(new Date(ts)) : "";
- const rate = payload[0]?.value;
- if (typeof rate !== "number") return null;
- // Delta vs. the 100 % goal — a positive delta means
- // "100 % target hit" and reads as success; a
- // negative delta is the gap to close.
- const gap = 100 - rate;
- let delta: string | undefined;
- if (gap < 0.5) {
- delta = t("charts.deltaUnchanged");
- } else {
- const formatted = `−${fmt.integer(gap)} pp`;
- delta = t("charts.deltaVsTarget").replace(
- "{delta}",
- formatted,
+ <>
+
+
+
+
+
+
+ {chartDays.openIndex !== undefined ? (
+
+ ) : null}
+ {
+ const { active, payload } = props as unknown as {
+ active?: boolean;
+ payload?: Array<{
+ value?: number;
+ color?: string;
+ payload?: ChartPoint;
+ }>;
+ };
+ if (!active || !payload?.length) return null;
+ const ts = payload[0]?.payload?.timestamp;
+ const dateLabel = ts ? tzFmt.date(new Date(ts)) : "";
+ const rate = payload[0]?.value;
+ if (typeof rate !== "number") return null;
+ // Delta vs. the 100 % goal — a positive delta means
+ // "100 % target hit" and reads as success; a
+ // negative delta is the gap to close.
+ const gap = 100 - rate;
+ let delta: string | undefined;
+ if (gap < 0.5) {
+ delta = t("charts.deltaUnchanged");
+ } else {
+ const formatted = `−${fmt.integer(gap)} pp`;
+ delta = t("charts.deltaVsTarget").replace(
+ "{delta}",
+ formatted,
+ );
+ }
+ const rows: RichTooltipRow[] = [
+ {
+ name: t("dashboard.compliance7d"),
+ value: `${fmt.integer(rate)} %`,
+ color: payload[0]?.color ?? COLOR_LINE,
+ delta,
+ },
+ ];
+ return (
+
);
- }
- const rows: RichTooltipRow[] = [
- {
- name: t("dashboard.compliance7d"),
- value: `${fmt.integer(rate)} %`,
- color: payload[0]?.color ?? COLOR_LINE,
- delta,
- },
- ];
- return (
-
- );
- }}
- />
- {/* v1.4.18 — minimum-acceptable threshold + goal line
+ }}
+ />
+ {/* v1.4.18 — minimum-acceptable threshold + goal line
are now opt-in via the "Target range" overlay
toggle. Default OFF; chart renders as a clean line
until the user activates the overlay from the
settings popover. */}
- {showTargetRange ? (
- <>
-
-
- >
- ) : null}
-
-
-
-
+ {showTargetRange ? (
+ <>
+
+
+ >
+ ) : null}
+
+
+
+
+
+ >
)}
);
diff --git a/src/components/charts/mood-chart.tsx b/src/components/charts/mood-chart.tsx
index eeb46aec8..5f0371278 100644
--- a/src/components/charts/mood-chart.tsx
+++ b/src/components/charts/mood-chart.tsx
@@ -1015,16 +1015,7 @@ export function MoodChart({
}
}
if (rows.length === 0) return null;
- return (
-
- );
+ return ;
}}
/>
);
}}
diff --git a/src/components/custom-metrics/custom-metric-chart.tsx b/src/components/custom-metrics/custom-metric-chart.tsx
index e35a77dc8..af828a9da 100644
--- a/src/components/custom-metrics/custom-metric-chart.tsx
+++ b/src/components/custom-metrics/custom-metric-chart.tsx
@@ -239,7 +239,6 @@ export function CustomMetricChart({
active
label={fmt.dateShortSmart(new Date(point.timestamp))}
rows={rows}
- action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
diff --git a/src/components/cycle/bbt-chart.tsx b/src/components/cycle/bbt-chart.tsx
index b29454d08..9e62520c2 100644
--- a/src/components/cycle/bbt-chart.tsx
+++ b/src/components/cycle/bbt-chart.tsx
@@ -24,7 +24,7 @@
* it surfaces a "log your morning temperature" hint rather than a flat dot.
*/
-import { useMemo, type ReactNode } from "react";
+import { useMemo } from "react";
import { Thermometer } from "lucide-react";
import {
CartesianGrid,
@@ -288,20 +288,7 @@ export function BbtChart({
strokeOpacity: 0.3,
strokeDasharray: "3 3",
}}
- content={(props) => {
- const payload = props.payload as unknown as
- { payload: BbtPoint }[] | undefined;
- const point = payload?.[0]?.payload;
- return (
-
- );
- }}
+ content={ }
/>
{ovulationMs != null ? (
) : null}
- {props.action ?? null}
);
}
diff --git a/src/components/day/__tests__/day-door-coverage-guard.test.ts b/src/components/day/__tests__/day-door-coverage-guard.test.ts
index 4dd79b891..3d5b534e8 100644
--- a/src/components/day/__tests__/day-door-coverage-guard.test.ts
+++ b/src/components/day/__tests__/day-door-coverage-guard.test.ts
@@ -9,17 +9,18 @@ import { describe, expect, it } from "vitest";
* 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 (click, the touch tooltip's button,
+ * three kinds of surface to the same doors (a click or a tap opens the 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 nutrient bar chart) passes `dayLinks`, or is
+ * 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 action);
+ * `OPEN_DAY_LINE`, the tooltip's props);
* C. a calendar heatmap (anything laid out by `heatmapDays`) calls
* `useHeatmapDay`.
*
@@ -48,6 +49,7 @@ const PROP_GATED = [
"HealthChart",
"HealthChartDynamic",
"MoodChart",
+ "MedicationComplianceChart",
"NutrientDailyBarChart",
"NutrientDailyBarChartDynamic",
] as const;
@@ -68,10 +70,6 @@ const DATE_AXIS_KEYS = [
* The integration plan's §1.2 and its table are the source of each reason.
*/
const NOT_HERE: Record = {
- "src/app/page-client.tsx":
- "The dashboard is today (decision D12): its charts are a summary of the record, and past days open as a layer over it from a date, never from the dashboard's own charts.",
- "src/components/charts/medication-compliance-chart.tsx":
- "Mounted on the dashboard only (see above); the adherence days open from the intake calendar on the medication insights page.",
"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":
@@ -197,15 +195,14 @@ function findMissingDoors(): {
/\buseChartDayLinks\(/.test(text) &&
/\bChartDayFooter\b/.test(text) &&
/\bOPEN_DAY_LINE\b/.test(text) &&
- /\.tooltipProps\b/.test(text) &&
- /\.tooltipAction\(/.test(text);
+ /\.tooltipProps\b/.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 action)",
+ why: "a date-axis chart without the shared day doors (useChartDayLinks, ChartDayFooter, OPEN_DAY_LINE, tooltip props)",
});
}
}
@@ -232,15 +229,17 @@ describe("every chart drawn in days opens its days, or says why not", () => {
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.
- expect(doors.mounts).toBeGreaterThanOrEqual(11);
+ // 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: eleven.
+ // basal temperature, dose strength, efficacy, the adherence chart:
+ // twelve.
expect(
doors.chartFiles.length,
doors.chartFiles.join("\n"),
- ).toBeGreaterThanOrEqual(11);
+ ).toBeGreaterThanOrEqual(12);
// The mood and the intake calendars.
expect(doors.heatmaps).toBeGreaterThanOrEqual(2);
});
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/chart-day-links.tsx b/src/components/day/chart-day-links.tsx
index 12f8c70d5..5b0438f18 100644
--- a/src/components/day/chart-day-links.tsx
+++ b/src/components/day/chart-day-links.tsx
@@ -1,13 +1,13 @@
"use client";
-import { useCallback, useMemo, useRef, type ReactNode } from "react";
+import { useCallback, useMemo, useRef } 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,
@@ -25,11 +25,11 @@ import { useTodayKey } from "./use-today-key";
* 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") opens the day. Two steps, so a scroll that
- * grazes the chart never opens a sheet;
+ * - a click, or a tap, on the plot opens the day of the point under it.
+ * On a fine pointer hovering still shows the tooltip; on a touch screen
+ * the tap opens the day at once, and the day puts the tapped value at
+ * its top. A scroll that grazes the chart is a pan, not a tap, and opens
+ * nothing;
* - 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.
@@ -90,13 +90,13 @@ export interface ChartDayLinks {
/** Pass as the Recharts chart's `onClick`. */
onChartClick:
((state: ChartClickState | null | undefined) => void) | undefined;
- /** Spread on ``: on touch it stays put and takes taps. */
- tooltipProps: {
- trigger: "click" | "hover";
- wrapperStyle?: React.CSSProperties;
- };
- /** The tooltip's button for point `index`, on a touch screen only. */
- tooltipAction: (index: number | undefined) => ReactNode | undefined;
+ /**
+ * Spread on ``. On touch, and under reduced motion, the tooltip
+ * does not glide: Recharts slides it from where it last was for 400 ms,
+ * which on a tap drew a box sweeping across the chart while the day was
+ * already opening.
+ */
+ tooltipProps: { isAnimationActive?: boolean };
}
export function useChartDayLinks({
@@ -134,17 +134,16 @@ export function useChartDayLinks({
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;
+ const onChartClick = enabled
+ ? (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,
@@ -160,16 +159,7 @@ export function useChartDayLinks({
plotClassName: enabled && !coarse ? "cursor-pointer" : "",
onChartClick,
tooltipProps:
- enabled && coarse
- ? {
- trigger: "click",
- wrapperStyle: { pointerEvents: "auto", zIndex: 20 },
- }
- : { trigger: "hover" },
- tooltipAction: (index) =>
- enabled && coarse && index !== undefined && canOpen(index) ? (
- open(index)} />
- ) : undefined,
+ coarse || prefersReducedMotion() ? { isAnimationActive: false } : {},
};
}
diff --git a/src/components/day/chart-day.tsx b/src/components/day/chart-day.tsx
index 8826fcb23..679fb690b 100644
--- a/src/components/day/chart-day.tsx
+++ b/src/components/day/chart-day.tsx
@@ -1,7 +1,6 @@
"use client";
import { useSyncExternalStore } from "react";
-import { ArrowRight } from "lucide-react";
import type { DateKey } from "@/lib/day/contract";
import { dateOnlyKey } from "@/lib/tz/date-only";
@@ -16,11 +15,10 @@ import { useTodayKey } from "./use-today-key";
/**
* The day view's entry points on a value chart.
*
- * - 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.
+ * - A click, or a tap, on the plot opens the day of the point under it,
+ * with that value at the top of the day. Hovering on a fine pointer
+ * keeps showing the tooltip; a scroll that grazes the chart is a pan,
+ * not a tap, and opens nothing.
* - 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,26 +57,6 @@ export function chartPointDayKey(timestamp: number): DateKey {
return dateOnlyKey(new Date(timestamp));
}
-/** The tooltip's way to the day on a touch screen. */
-export function TooltipDayAction({ onOpen }: { onOpen: () => void }) {
- const { t } = useTranslations();
- return (
- {
- event.stopPropagation();
- onOpen();
- }}
- onPointerDown={(event) => event.stopPropagation()}
- className="bg-muted hover:bg-muted/80 focus-visible:ring-ring/50 mt-2.5 flex min-h-11 w-full items-center justify-center gap-1.5 rounded-md px-3 text-sm font-medium transition-colors focus-visible:ring-[3px] focus-visible:outline-none"
- >
- {t("day.viewWholeDay")}
-
-
- );
-}
-
interface RugPoint {
timestamp: number;
}
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..0b7ff57a1 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";
/**
@@ -91,6 +93,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,
@@ -114,6 +126,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 +184,42 @@ 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. */}
+
+ {compact ? (
+
+ ) : (
+
+ )}
+
+ {/* One line, centred in the band: the date and nothing under it. */}
+
+ {longLabel(date)}
+
onStep(-1)}
className={ICON_BUTTON}
>
@@ -208,6 +246,9 @@ export function DayView({
aria-label={t("day.nextDay")}
title={t("day.nextDayShortcut")}
disabled={date >= today}
+ onPointerEnter={warm(1)}
+ onPointerDown={warm(1)}
+ onFocus={warm(1)}
onClick={() => onStep(1)}
className={ICON_BUTTON}
>
@@ -216,18 +257,6 @@ export function DayView({
aria-hidden="true"
/>
-
-
-
+ {/* 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 ? (
) {
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();
@@ -109,18 +104,17 @@ export function useHeatmapDay(containerRef: RefObject) {
setTooltip((prev) => (prev?.pinned ? prev : null));
},
onPointerDown: (e: React.PointerEvent) => {
- lastPointer.current = e.pointerType;
- if (e.pointerType !== "touch") return;
+ // A touch on a cell with a day to open opens it (the click below);
+ // any other cell pins its tooltip so the tap still answers.
+ if (e.pointerType !== "touch" || openable) 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);
},
@@ -135,9 +129,7 @@ export function useHeatmapDay(containerRef: RefObject) {
const tooltipNode = tooltip ? (
) {
}}
>
{tooltip.text}
- {tooltip.day ? (
- open(tooltip.day as DateKey)} />
- ) : null}
) : null;
diff --git a/src/components/day/use-day.ts b/src/components/day/use-day.ts
index 5dcc8fc97..8f2792f5f 100644
--- a/src/components/day/use-day.ts
+++ b/src/components/day/use-day.ts
@@ -1,6 +1,7 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
+import { useCallback } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { apiGet } from "@/lib/api/api-fetch";
import type {
@@ -18,15 +19,34 @@ import { queryKeys } from "@/lib/query-keys";
* running-day counts and the notable observations. Nothing here recomputes
* any of it.
*/
-export function useDay(date: DateKey | null) {
- return useQuery({
- queryKey: queryKeys.day(date ?? ""),
+function dayQuery(date: DateKey) {
+ return {
+ queryKey: queryKeys.day(date),
queryFn: () => apiGet(`/api/day/${date}`),
- enabled: date !== null,
// A past day changes only when something is written into it, and every
// record write evicts the `["day"]` root.
staleTime: 5 * 60_000,
- });
+ };
+}
+
+export function useDay(date: DateKey | null) {
+ return useQuery({ ...dayQuery(date ?? ""), enabled: date !== null });
+}
+
+/**
+ * Read a day ahead of time, so the step to it paints the day instead of a
+ * skeleton: the neighbouring day when the pointer rests on, or the keyboard
+ * reaches, the arrow that leads there. A day already read (and fresh) is not
+ * read again; the query layer dedupes one that is already on its way.
+ */
+export function usePrefetchDay(): (date: DateKey) => void {
+ const queryClient = useQueryClient();
+ return useCallback(
+ (date: DateKey) => {
+ void queryClient.prefetchQuery(dayQuery(date));
+ },
+ [queryClient],
+ );
}
/**
diff --git a/src/components/documents/document-bulk-bar.tsx b/src/components/documents/document-bulk-bar.tsx
index 45d3a2069..07a5466c4 100644
--- a/src/components/documents/document-bulk-bar.tsx
+++ b/src/components/documents/document-bulk-bar.tsx
@@ -90,6 +90,10 @@ export function DocumentBulkBar({
aria-label={t("documents.bulk.barLabel")}
className={cn(
"bg-card border-border fixed bottom-20 left-1/2 z-40 -translate-x-1/2 md:bottom-6",
+ // v1.42 — while a day is docked on the right, the bar sits against
+ // the page's right edge instead of the window's centre, clear of the
+ // day's footer actions and of an expanded sidebar.
+ "[body:has([data-slot=day-panel][data-shell=docked])_&]:right-[calc(26.25rem+1rem)] [body:has([data-slot=day-panel][data-shell=docked])_&]:left-auto [body:has([data-slot=day-panel][data-shell=docked])_&]:max-w-[calc(100vw-44.25rem)] [body:has([data-slot=day-panel][data-shell=docked])_&]:translate-x-0",
"flex w-[calc(100%-2rem)] max-w-2xl flex-wrap items-center gap-2 rounded-xl border p-3 shadow-lg",
)}
>
diff --git a/src/components/insights/__tests__/health-score-card.test.tsx b/src/components/insights/__tests__/health-score-card.test.tsx
index f30bfe79b..e27243b14 100644
--- a/src/components/insights/__tests__/health-score-card.test.tsx
+++ b/src/components/insights/__tests__/health-score-card.test.tsx
@@ -641,7 +641,10 @@ describe(" composite states", () => {
const rest = atRest(html);
// The onset is an instant; it reads as the day it falls on in the
// profile timezone, in the user's date format, never as raw ISO.
- expect(rest).toMatch(/Rest Mode active since \d{2}\/\d{2}\/2026\./);
+ // v1.42 — the date is a link to its day; the sentence reads the same.
+ expect(rest.replace(/<[^>]+>/g, "")).toMatch(
+ /Rest Mode active since \d{2}\/\d{2}\/2026\./,
+ );
expect(rest).not.toContain("T23:30:00");
expect(rest).toContain('data-slot="health-score-tension"');
expect(rest).toContain('data-slot="health-score-return-to-band"');
@@ -669,7 +672,11 @@ describe(" composite states", () => {
/>,
);
const rest = atRest(html);
- expect(rest).toMatch(/Rest Mode active since (07\/20\/2026|20\/07\/2026)/);
+ expect(rest.replace(/<[^>]+>/g, "")).toMatch(
+ /Rest Mode active since (07\/20\/2026|20\/07\/2026)/,
+ );
+ // The date opens the day it names, in the profile timezone.
+ expect(rest).toContain('data-day="2026-07-20"');
expect(rest).not.toContain("2026-07-19T");
});
diff --git a/src/components/insights/ecg-detail.tsx b/src/components/insights/ecg-detail.tsx
index c60c2abee..6c9bea58a 100644
--- a/src/components/insights/ecg-detail.tsx
+++ b/src/components/insights/ecg-detail.tsx
@@ -1,7 +1,10 @@
"use client";
+import type { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
+import { DayLinkAt } from "@/components/day/day-link";
+
import { queryKeys } from "@/lib/query-keys";
import { apiGet } from "@/lib/api/api-fetch";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
@@ -111,7 +114,12 @@ export function EcgDetail({ recordingId }: { recordingId: string }) {
>
+ {fmt.dateTime(new Date(data.recordedAt))}
+
+ }
/>
{label}
diff --git a/src/components/insights/ecg-section.tsx b/src/components/insights/ecg-section.tsx
index fdd8563dc..2741a7d8c 100644
--- a/src/components/insights/ecg-section.tsx
+++ b/src/components/insights/ecg-section.tsx
@@ -15,6 +15,8 @@ import {
type EcgClassification,
} from "@/lib/insights/ecg-classification";
import { ECG_OVERVIEW_LIMIT } from "@/lib/insights/ecg-overview-limit";
+import { DayLinkAt } from "@/components/day/day-link";
+
import { InsightSectionCard } from "./insight-section-card";
// Re-exported so the tests (and any teaser call site) can keep importing the
@@ -140,7 +142,11 @@ export function EcgSection({
the recording, it is not a second fact about it. */}
- {fmt.dateTime(new Date(rec.recordedAt))}
+ {/* v1.42 — the date opens the day; the rest of the
+ row opens the recording. Above the row's link. */}
+
+ {fmt.dateTime(new Date(rec.recordedAt))}
+
{label && (
{rec.hasWaveform ? (
-
+ // v1.42 — two targets in one row: the date opens the day,
+ // the row opens the recording. The row's link is stretched
+ // under the content (the workout list's pattern), so the
+ // date can sit above it instead of inside it.
+
{rowInner}
-
-
+
+
+
+
) : (
{rowInner}
)}
diff --git a/src/components/insights/health-score-card.tsx b/src/components/insights/health-score-card.tsx
index 45b3d5302..ebcceddd3 100644
--- a/src/components/insights/health-score-card.tsx
+++ b/src/components/insights/health-score-card.tsx
@@ -24,6 +24,11 @@ import {
type PillarDetailContext,
} from "@/components/insights/health-score-pillar-detail";
import { useAuth } from "@/hooks/use-auth";
+import {
+ DAY_LINK_SLOT,
+ DayLink,
+ withDayLinkSlot,
+} from "@/components/day/day-link";
import { formatDate } from "@/lib/date-format";
import { DEFAULT_TIMEZONE, userDayKey } from "@/lib/tz/format";
import { useUnitDisplay } from "@/hooks/use-unit-display";
@@ -530,18 +535,30 @@ export function HealthScoreCard({
data-slot="health-score-rest-mode"
className="text-muted-foreground text-xs"
>
- {t("insights.healthScore.restMode", {
- since: report.restMode.since
- ? formatDate(
- userDayKey(
+ {/* v1.42 — the date opens the day rest mode began. */}
+ {report.restMode.since
+ ? withDayLinkSlot(
+ t("insights.healthScore.restMode", { since: DAY_LINK_SLOT }),
+
+ {formatDate(
+ userDayKey(
+ new Date(report.restMode.since),
+ user?.timezone || DEFAULT_TIMEZONE,
+ ),
+ dateFormat,
+ locale,
+ )}
+ ,
+ )
+ : t("insights.healthScore.restMode", {
+ since: t("insights.healthScore.none"),
+ })}
) : null}
{tensionLine ? (
diff --git a/src/components/insights/layout-coach-fab.tsx b/src/components/insights/layout-coach-fab.tsx
index df0f850de..f8815d6fe 100644
--- a/src/components/insights/layout-coach-fab.tsx
+++ b/src/components/insights/layout-coach-fab.tsx
@@ -250,7 +250,12 @@ export function LayoutCoachFab() {
// The default ring alone is hard to see against the gradient;
// the offset ring draws a clear halo around the circle.
"focus-visible:ring-offset-background focus-visible:ring-offset-2",
- "transition-opacity duration-150 motion-reduce:transition-none",
+ "transition-[opacity,right] duration-150 motion-reduce:transition-none",
+ // v1.42 — while a day is docked on the right (from 1280 px), the
+ // launcher moves left with the page's own edge, so it stays over
+ // the page and never over the day's footer actions. The `:has()`
+ // gate keys off the docked panel's slot, like the yields below.
+ "[body:has([data-slot=day-panel][data-shell=docked])_&]:right-[calc(26.25rem+2rem)]",
// Yield to the data-list selection bar: its delete action lands
// in the same lower-right band, and the destructive control
// wins. The `:has()` gate keys off the bar's `data-slot`.
diff --git a/src/components/insights/mood/mood-dimension-trends.tsx b/src/components/insights/mood/mood-dimension-trends.tsx
index 52a860719..bb20d8aff 100644
--- a/src/components/insights/mood/mood-dimension-trends.tsx
+++ b/src/components/insights/mood/mood-dimension-trends.tsx
@@ -216,7 +216,6 @@ export function MoodDimensionTrends({
active
label={fmt.dateShortSmartCalendar(String(row.date))}
rows={rows}
- action={chartDays.tooltipAction(chartData.indexOf(row))}
/>
);
}}
diff --git a/src/components/insights/rest-mode-banner.tsx b/src/components/insights/rest-mode-banner.tsx
index 3f4e1af87..cdda468eb 100644
--- a/src/components/insights/rest-mode-banner.tsx
+++ b/src/components/insights/rest-mode-banner.tsx
@@ -2,6 +2,11 @@
import { HeartPulse } from "lucide-react";
+import {
+ DAY_LINK_SLOT,
+ DayLinkStated,
+ withDayLinkSlot,
+} from "@/components/day/day-link";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import type { RestModeAnnotation } from "@/lib/analytics/score/types";
@@ -62,8 +67,14 @@ export function RestModeBanner({
{t("insights.restMode.title")}
- {sinceLabel
- ? t("insights.restMode.bodySince", { since: sinceLabel })
+ {/* v1.42 — the onset date opens the day the episode began. */}
+ {sinceLabel && since
+ ? withDayLinkSlot(
+ t("insights.restMode.bodySince", { since: DAY_LINK_SLOT }),
+
+ {sinceLabel}
+ ,
+ )
: t("insights.restMode.body")}
diff --git a/src/components/insights/rhythm-events-card.tsx b/src/components/insights/rhythm-events-card.tsx
index 2367a516a..670d21a7f 100644
--- a/src/components/insights/rhythm-events-card.tsx
+++ b/src/components/insights/rhythm-events-card.tsx
@@ -12,6 +12,7 @@ import { cn } from "@/lib/utils";
import { SectionHeading } from "@/components/ui/section-heading";
import { InsightSectionCard } from "./insight-section-card";
import { QueryErrorRow } from "@/components/ui/query-error-row";
+import { DayLinkAt } from "@/components/day/day-link";
/**
* v1.10.0 — device-flagged event awareness surface (categorical events,
@@ -174,7 +175,10 @@ export function RhythmEventsCard({
)}
- {fmt.dateTime(new Date(event.occurredAt))}
+ {/* v1.42 — the date opens the day around the event. */}
+
+ {fmt.dateTime(new Date(event.occurredAt))}
+
diff --git a/src/components/insights/sleep-stage-stacked-bar.tsx b/src/components/insights/sleep-stage-stacked-bar.tsx
index ccf2e94c0..bd09ae618 100644
--- a/src/components/insights/sleep-stage-stacked-bar.tsx
+++ b/src/components/insights/sleep-stage-stacked-bar.tsx
@@ -469,7 +469,6 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
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
@@ -550,9 +549,6 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
)}
)}
- {chartDays.tooltipAction(
- rowIndex === -1 ? undefined : rowIndex,
- )}
);
}}
diff --git a/src/components/labs/lab-biomarker-chart.tsx b/src/components/labs/lab-biomarker-chart.tsx
index 7a8828340..97f78dcf8 100644
--- a/src/components/labs/lab-biomarker-chart.tsx
+++ b/src/components/labs/lab-biomarker-chart.tsx
@@ -406,7 +406,6 @@ export function LabBiomarkerChart({
active
label={labShortDate(point.timestamp)}
rows={rows}
- action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
diff --git a/src/components/medications/detail/efficacy/efficacy-chart.tsx b/src/components/medications/detail/efficacy/efficacy-chart.tsx
index 0d0307570..36bab7d32 100644
--- a/src/components/medications/detail/efficacy/efficacy-chart.tsx
+++ b/src/components/medications/detail/efficacy/efficacy-chart.tsx
@@ -378,18 +378,11 @@ export function EfficacyChart({
color: item.color ?? "var(--chart-1)",
};
});
- const index =
- typeof x === "number"
- ? displaySeries.findIndex((p) => p.t === x)
- : -1;
return (
);
}}
diff --git a/src/components/medications/dose-strength-curve.tsx b/src/components/medications/dose-strength-curve.tsx
index 4b08d8082..6040fb7c7 100644
--- a/src/components/medications/dose-strength-curve.tsx
+++ b/src/components/medications/dose-strength-curve.tsx
@@ -326,7 +326,6 @@ export function DoseStrengthCurve({
active
label={fmt.dateShortSmart(new Date(point.t))}
rows={rows}
- action={chartDays.tooltipAction(chartData.indexOf(point))}
/>
);
}}
diff --git a/src/components/mental-health/assessment-history-chart.tsx b/src/components/mental-health/assessment-history-chart.tsx
index 1cdf57adb..548b2165b 100644
--- a/src/components/mental-health/assessment-history-chart.tsx
+++ b/src/components/mental-health/assessment-history-chart.tsx
@@ -183,7 +183,6 @@ export function AssessmentHistoryChart({
active
label={fmt.dateShortSmart(new Date(point.timestamp))}
rows={rowsOut}
- action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
From 8bcb3e6301f24864bb36129469c7507d144668c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?=
Date: Thu, 8 Oct 2026 16:04:54 +0200
Subject: [PATCH 4/6] fix: keep the two-step on chart points on touch
A point and a calendar cell are small targets; one tap that opened the
day opened days by accident. On a touch screen the first tap shows the
value again and the tooltip's calm 44 px row opens the day, on every
day-linked chart and calendar alike. A date in a list still opens in one
tap; a click on a fine pointer still opens directly. The tooltip keeps
not gliding into place.
---
e2e/day-doors.spec.ts | 26 +++++--
e2e/day-view.spec.ts | 17 +++--
messages/de.json | 6 +-
messages/en.json | 6 +-
messages/es.json | 6 +-
messages/fr.json | 6 +-
messages/it.json | 6 +-
messages/ko.json | 6 +-
messages/pl.json | 6 +-
src/components/charts/health-chart.tsx | 5 ++
.../charts/medication-compliance-chart.tsx | 12 +++-
src/components/charts/mood-chart.tsx | 11 ++-
.../charts/nutrient-daily-bar-chart.tsx | 1 +
.../custom-metrics/custom-metric-chart.tsx | 1 +
src/components/cycle/bbt-chart.tsx | 20 +++++-
.../__tests__/day-door-coverage-guard.test.ts | 12 ++--
src/components/day/chart-day-links.tsx | 67 +++++++++++++------
src/components/day/chart-day.tsx | 31 +++++++--
src/components/day/heatmap-day.tsx | 32 ++++++---
.../insights/mood/mood-dimension-trends.tsx | 1 +
.../insights/sleep-stage-stacked-bar.tsx | 4 ++
src/components/labs/lab-biomarker-chart.tsx | 1 +
.../detail/efficacy/efficacy-chart.tsx | 7 ++
.../medications/dose-strength-curve.tsx | 1 +
.../assessment-history-chart.tsx | 1 +
25 files changed, 213 insertions(+), 79 deletions(-)
diff --git a/e2e/day-doors.spec.ts b/e2e/day-doors.spec.ts
index af3b4c2ea..c83cfa352 100644
--- a/e2e/day-doors.spec.ts
+++ b/e2e/day-doors.spec.ts
@@ -13,11 +13,13 @@ import { expect, test } from "./setup/test";
*
* 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 door: a click on a point (or a calendar cell) opens
- * the day beside the page, and on a touch screen a tap does the same as a
- * bottom sheet, the tapped value on top. 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.
+ * 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;
@@ -41,8 +43,14 @@ async function openFromPlot(page: Page, plot: Locator, testInfo: TestInfo) {
const x = box.x + box.width * 0.8;
const y = box.y + box.height / 2;
if (isPhone(testInfo)) {
- // One tap, the same door as the click: no tooltip step in between.
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);
@@ -143,6 +151,12 @@ test.describe("every chart drawn in days opens its days", () => {
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();
diff --git a/e2e/day-view.spec.ts b/e2e/day-view.spec.ts
index 43806f074..6a04b16f0 100644
--- a/e2e/day-view.spec.ts
+++ b/e2e/day-view.spec.ts
@@ -15,9 +15,8 @@ import { MOBILE_ROUTES_ANALYTE } from "./setup/mobile-routes-fixture";
* day, what the history does, and where no door is.
*
* - a chart point opens the day beside the chart (desktop);
- * - on a touch screen a tap on a point opens the day at once, as a bottom
- * sheet with the tapped value on top (the maintainer's call on the beta:
- * the two-step tooltip broke the flow);
+ * - on a touch screen the first tap shows the value and the tooltip offers
+ * the day, the second opens it as a bottom sheet;
* - a date in a list opens the day while the row keeps its own target;
* - `?day=` opens the layer on any page, Back and Escape close it, a date in
* the future is dropped;
@@ -25,7 +24,7 @@ import { MOBILE_ROUTES_ANALYTE } from "./setup/mobile-routes-fixture";
* - 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]`, `day-prev` /
+ * `chart-plot[data-day-links]`, `chart-tooltip-open-day`, `day-prev` /
* `day-next` / `day-close`.
*/
@@ -151,7 +150,7 @@ test.describe("the day view", () => {
await expect(page).toHaveURL(/\/mood$/);
});
- test("on a phone a tap on a point opens its day at once", async ({
+ test("on a phone the first tap shows the value, the second opens the day", async ({
page,
}, testInfo) => {
test.skip(testInfo.project.name !== "chromium-mobile", "touch only");
@@ -162,11 +161,15 @@ test.describe("the day view", () => {
await plot.scrollIntoViewIfNeeded();
await expect(plot).toBeVisible();
const box = (await plot.boundingBox())!;
- // One tap, the same door as a click on a desktop: the day opens as a
- // bottom sheet with the tapped value on top.
await page.touchscreen.tap(box.x + box.width * 0.8, box.y + box.height / 2);
+ const open = page.locator('[data-slot="chart-tooltip-open-day"]');
+ await expect(open).toBeVisible();
+ // A tap alone never opens a sheet.
+ await expect(panel(page)).toHaveCount(0);
+ 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();
});
diff --git a/messages/de.json b/messages/de.json
index 2aa8f3350..b9b9399de 100644
--- a/messages/de.json
+++ b/messages/de.json
@@ -12201,11 +12201,11 @@
"captureShort": "Erfassen",
"inTimelineShort": "Zeitleiste",
"askCoachPrompt": "Was war am {date}?",
- "chartHintTouch": "Antippen eines Punkts öffnet den Tag.",
+ "chartHintTouch": "Antippen zeigt den Wert.",
"chartHintBar": "Klick auf einen Balken öffnet den Tag.",
- "chartHintTouchBar": "Antippen eines Balkens öffnet den Tag.",
+ "chartHintTouchBar": "Antippen zeigt die Werte.",
"chartHintCell": "Klick auf einen Tag öffnet ihn.",
- "chartHintTouchCell": "Antippen eines Tages ö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 f5e55df8b..7efb7a78b 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -12201,11 +12201,11 @@
"captureShort": "Log",
"inTimelineShort": "Timeline",
"askCoachPrompt": "What happened on {date}?",
- "chartHintTouch": "Tap a point to open its day.",
+ "chartHintTouch": "Tap a point to see its value.",
"chartHintBar": "Click a bar to open its day.",
- "chartHintTouchBar": "Tap 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 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 2a458aa35..e38b9e1a8 100644
--- a/messages/es.json
+++ b/messages/es.json
@@ -12201,11 +12201,11 @@
"captureShort": "Registrar",
"inTimelineShort": "Cronología",
"askCoachPrompt": "¿Qué pasó el {date}?",
- "chartHintTouch": "Toca un punto para abrir su día.",
+ "chartHintTouch": "Toca un punto para ver su valor.",
"chartHintBar": "Haz clic en una barra para abrir su día.",
- "chartHintTouchBar": "Toca 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 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 70d2bd366..9070b5fdc 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -12201,11 +12201,11 @@
"captureShort": "Enregistrer",
"inTimelineShort": "Chronologie",
"askCoachPrompt": "Que s’est-il passé le {date} ?",
- "chartHintTouch": "Touchez un point pour ouvrir son jour.",
+ "chartHintTouch": "Touchez un point pour voir sa valeur.",
"chartHintBar": "Cliquez sur une barre pour ouvrir son jour.",
- "chartHintTouchBar": "Touchez 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 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 9dfef1da6..7da2126a2 100644
--- a/messages/it.json
+++ b/messages/it.json
@@ -12201,11 +12201,11 @@
"captureShort": "Registra",
"inTimelineShort": "Cronologia",
"askCoachPrompt": "Cosa è successo il {date}?",
- "chartHintTouch": "Tocca un punto per aprire il suo giorno.",
+ "chartHintTouch": "Tocca un punto per vederne il valore.",
"chartHintBar": "Fai clic su una barra per aprire il suo giorno.",
- "chartHintTouchBar": "Tocca 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 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 484effaaa..ccd0eb935 100644
--- a/messages/ko.json
+++ b/messages/ko.json
@@ -12201,11 +12201,11 @@
"captureShort": "기록",
"inTimelineShort": "타임라인",
"askCoachPrompt": "{date}에 무슨 일이 있었나요?",
- "chartHintTouch": "점을 탭하면 그날이 열려요.",
+ "chartHintTouch": "점을 탭하면 값이 보여요.",
"chartHintBar": "막대를 클릭하면 그날이 열려요.",
- "chartHintTouchBar": "막대를 탭하면 그날이 열려요.",
+ "chartHintTouchBar": "막대를 탭하면 값이 보여요.",
"chartHintCell": "날짜 칸을 클릭하면 그날이 열려요.",
- "chartHintTouchCell": "날짜 칸을 탭하면 그날이 열려요.",
+ "chartHintTouchCell": "날짜 칸을 탭하면 값이 보여요.",
"coachChips": "이 답변에 쓰인 날",
"description": "이 날에 대한 모든 기록이에요.",
"openDocument": "문서 열기",
diff --git a/messages/pl.json b/messages/pl.json
index d07ef24d2..032c99b02 100644
--- a/messages/pl.json
+++ b/messages/pl.json
@@ -12201,11 +12201,11 @@
"captureShort": "Zapisz",
"inTimelineShort": "Oś czasu",
"askCoachPrompt": "Co się działo {date}?",
- "chartHintTouch": "Dotknij punktu, aby otworzyć jego dzień.",
+ "chartHintTouch": "Dotknij punktu, aby zobaczyć wartość.",
"chartHintBar": "Kliknij słupek, aby otworzyć jego dzień.",
- "chartHintTouchBar": "Dotknij słupka, aby otworzyć jego dzień.",
+ "chartHintTouchBar": "Dotknij słupka, aby zobaczyć wartości.",
"chartHintCell": "Kliknij dzień, aby go otworzyć.",
- "chartHintTouchCell": "Dotknij dnia, 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/components/charts/health-chart.tsx b/src/components/charts/health-chart.tsx
index c31fe7eca..3f539c146 100644
--- a/src/components/charts/health-chart.tsx
+++ b/src/components/charts/health-chart.tsx
@@ -2404,6 +2404,11 @@ export function HealthChart({
: dateLabel
}
rows={rows}
+ action={chartDays.tooltipAction(
+ hoverPoint
+ ? dayLinkSource?.indexOf(hoverPoint)
+ : undefined,
+ )}
/>
);
}}
diff --git a/src/components/charts/medication-compliance-chart.tsx b/src/components/charts/medication-compliance-chart.tsx
index 4fb12ca5d..628ce42ce 100644
--- a/src/components/charts/medication-compliance-chart.tsx
+++ b/src/components/charts/medication-compliance-chart.tsx
@@ -644,8 +644,18 @@ export function MedicationComplianceChart({
delta,
},
];
+ const hoverPoint = payload[0]?.payload;
return (
-
+
);
}}
/>
diff --git a/src/components/charts/mood-chart.tsx b/src/components/charts/mood-chart.tsx
index 5f0371278..eeb46aec8 100644
--- a/src/components/charts/mood-chart.tsx
+++ b/src/components/charts/mood-chart.tsx
@@ -1015,7 +1015,16 @@ export function MoodChart({
}
}
if (rows.length === 0) return null;
- return ;
+ return (
+
+ );
}}
/>
);
}}
diff --git a/src/components/custom-metrics/custom-metric-chart.tsx b/src/components/custom-metrics/custom-metric-chart.tsx
index af828a9da..e35a77dc8 100644
--- a/src/components/custom-metrics/custom-metric-chart.tsx
+++ b/src/components/custom-metrics/custom-metric-chart.tsx
@@ -239,6 +239,7 @@ export function CustomMetricChart({
active
label={fmt.dateShortSmart(new Date(point.timestamp))}
rows={rows}
+ action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
diff --git a/src/components/cycle/bbt-chart.tsx b/src/components/cycle/bbt-chart.tsx
index 9e62520c2..b29454d08 100644
--- a/src/components/cycle/bbt-chart.tsx
+++ b/src/components/cycle/bbt-chart.tsx
@@ -24,7 +24,7 @@
* it surfaces a "log your morning temperature" hint rather than a flat dot.
*/
-import { useMemo } from "react";
+import { useMemo, type ReactNode } from "react";
import { Thermometer } from "lucide-react";
import {
CartesianGrid,
@@ -288,7 +288,20 @@ export function BbtChart({
strokeOpacity: 0.3,
strokeDasharray: "3 3",
}}
- content={ }
+ content={(props) => {
+ const payload = props.payload as unknown as
+ { payload: BbtPoint }[] | undefined;
+ const point = payload?.[0]?.payload;
+ return (
+
+ );
+ }}
/>
{ovulationMs != null ? (
) : null}
+ {props.action ?? null}
);
}
diff --git a/src/components/day/__tests__/day-door-coverage-guard.test.ts b/src/components/day/__tests__/day-door-coverage-guard.test.ts
index 3d5b534e8..68dd8f2ac 100644
--- a/src/components/day/__tests__/day-door-coverage-guard.test.ts
+++ b/src/components/day/__tests__/day-door-coverage-guard.test.ts
@@ -9,8 +9,9 @@ import { describe, expect, it } from "vitest";
* 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 or a tap opens the day,
- * the dashed line through the open day, the row of day dots, the caption):
+ * 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)
@@ -20,7 +21,7 @@ import { describe, expect, it } from "vitest";
* 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);
+ * `OPEN_DAY_LINE`, the tooltip's props and its touch action);
* C. a calendar heatmap (anything laid out by `heatmapDays`) calls
* `useHeatmapDay`.
*
@@ -195,14 +196,15 @@ function findMissingDoors(): {
/\buseChartDayLinks\(/.test(text) &&
/\bChartDayFooter\b/.test(text) &&
/\bOPEN_DAY_LINE\b/.test(text) &&
- /\.tooltipProps\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)",
+ why: "a date-axis chart without the shared day doors (useChartDayLinks, ChartDayFooter, OPEN_DAY_LINE, tooltip props and touch action)",
});
}
}
diff --git a/src/components/day/chart-day-links.tsx b/src/components/day/chart-day-links.tsx
index 5b0438f18..7e645b155 100644
--- a/src/components/day/chart-day-links.tsx
+++ b/src/components/day/chart-day-links.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useMemo, useRef } from "react";
+import { useCallback, useMemo, useRef, type ReactNode } from "react";
import type { DateKey } from "@/lib/day/contract";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
@@ -8,6 +8,7 @@ import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import {
ChartDayCaption,
DayRug,
+ TooltipDayAction,
useCoarsePointer,
type ChartDayAxis,
type ChartDayMark,
@@ -25,11 +26,13 @@ import { useTodayKey } from "./use-today-key";
* button, the dashed line through the open day and the row of dots under the
* axis behave the same on every page:
*
- * - a click, or a tap, on the plot opens the day of the point under it.
- * On a fine pointer hovering still shows the tooltip; on a touch screen
- * the tap opens the day at once, and the day puts the tapped value at
- * its top. A scroll that grazes the chart is a pan, not a tap, and opens
- * nothing;
+ * - 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.
@@ -91,12 +94,19 @@ export interface ChartDayLinks {
onChartClick:
((state: ChartClickState | null | undefined) => void) | undefined;
/**
- * Spread on ``. On touch, and under reduced motion, the tooltip
- * does not glide: Recharts slides it from where it last was for 400 ms,
- * which on a tap drew a box sweeping across the chart while the day was
- * already opening.
+ * 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: { isAnimationActive?: boolean };
+ 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({
@@ -134,16 +144,17 @@ export function useChartDayLinks({
return at === -1 ? undefined : at;
}, [enabled, openKey, days]);
- const onChartClick = enabled
- ? (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;
+ 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,
@@ -159,7 +170,19 @@ export function useChartDayLinks({
plotClassName: enabled && !coarse ? "cursor-pointer" : "",
onChartClick,
tooltipProps:
- coarse || prefersReducedMotion() ? { isAnimationActive: false } : {},
+ 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,
};
}
diff --git a/src/components/day/chart-day.tsx b/src/components/day/chart-day.tsx
index 679fb690b..460d3e746 100644
--- a/src/components/day/chart-day.tsx
+++ b/src/components/day/chart-day.tsx
@@ -1,6 +1,7 @@
"use client";
import { useSyncExternalStore } from "react";
+import { ArrowRight } from "lucide-react";
import type { DateKey } from "@/lib/day/contract";
import { dateOnlyKey } from "@/lib/tz/date-only";
@@ -15,10 +16,12 @@ import { useTodayKey } from "./use-today-key";
/**
* The day view's entry points on a value chart.
*
- * - A click, or a tap, on the plot opens the day of the point under it,
- * with that value at the top of the day. Hovering on a fine pointer
- * keeps showing the tooltip; a scroll that grazes the chart is a pan,
- * not a tap, and opens nothing.
+ * - 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: 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.
@@ -57,6 +60,26 @@ export function chartPointDayKey(timestamp: number): DateKey {
return dateOnlyKey(new Date(timestamp));
}
+/** The tooltip's way to the day on a touch screen. */
+export function TooltipDayAction({ onOpen }: { onOpen: () => void }) {
+ const { t } = useTranslations();
+ return (
+ {
+ event.stopPropagation();
+ onOpen();
+ }}
+ onPointerDown={(event) => event.stopPropagation()}
+ className="bg-muted hover:bg-muted/80 focus-visible:ring-ring/50 mt-2.5 flex min-h-11 w-full items-center justify-center gap-1.5 rounded-md px-3 text-sm font-medium transition-colors focus-visible:ring-[3px] focus-visible:outline-none"
+ >
+ {t("day.viewWholeDay")}
+
+
+ );
+}
+
interface RugPoint {
timestamp: number;
}
diff --git a/src/components/day/heatmap-day.tsx b/src/components/day/heatmap-day.tsx
index d71f97fbc..0eb352c51 100644
--- a/src/components/day/heatmap-day.tsx
+++ b/src/components/day/heatmap-day.tsx
@@ -1,10 +1,10 @@
"use client";
-import { useEffect, useState, type RefObject } from "react";
+import { useEffect, useRef, useState, type RefObject } from "react";
import type { DateKey } from "@/lib/day/contract";
-import { useCoarsePointer } from "./chart-day";
+import { TooltipDayAction, useCoarsePointer } from "./chart-day";
import { openDay, useOpenDay } from "./day-layer-controller";
import { isOpenableDay } from "./day-url";
import { useTodayKey } from "./use-today-key";
@@ -13,10 +13,11 @@ import { useTodayKey } from "./use-today-key";
* The day view's doors on a calendar heatmap (mood, intake), the cell twin of
* `useChartDayLinks`:
*
- * - a click, or a tap, on a cell opens its day; hovering a cell on a fine
- * pointer shows its tooltip. A tap on a cell with nothing to open (no
- * entry, or a day still ahead) pins its tooltip instead, so the cell
- * still says what it is; a tap outside or Escape clears it;
+ * - fine pointer: hovering a cell shows its tooltip, a click opens its day;
+ * - touch: a tap pins the tooltip, and the tooltip's button ("View the
+ * whole day", the same calm 44 px row every chart's tooltip carries)
+ * opens it. Two steps, as on a chart: a cell is a small target. A tap
+ * outside or Escape clears the tooltip;
* - the open day's cell carries a dashed outline, the heatmap's form of
* the dashed line a chart draws through it (`OPEN_DAY_CELL`);
* - the keyboard and screen-reader way to a day is the heatmap's data
@@ -39,6 +40,8 @@ interface HeatmapTooltip {
text: string;
/** A touch tooltip stays after the finger lifts. */
pinned?: boolean;
+ /** The day a pinned tooltip offers to open. */
+ day?: DateKey;
}
export interface HeatmapCellInput {
@@ -51,6 +54,9 @@ export interface HeatmapCellInput {
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();
@@ -104,17 +110,18 @@ export function useHeatmapDay(containerRef: RefObject) {
setTooltip((prev) => (prev?.pinned ? prev : null));
},
onPointerDown: (e: React.PointerEvent) => {
- // A touch on a cell with a day to open opens it (the click below);
- // any other cell pins its tooltip so the tap still answers.
- if (e.pointerType !== "touch" || openable) return;
+ 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);
},
@@ -129,7 +136,9 @@ export function useHeatmapDay(containerRef: RefObject) {
const tooltipNode = tooltip ? (
) {
}}
>
{tooltip.text}
+ {tooltip.day ? (
+ open(tooltip.day as DateKey)} />
+ ) : null}
) : null;
diff --git a/src/components/insights/mood/mood-dimension-trends.tsx b/src/components/insights/mood/mood-dimension-trends.tsx
index bb20d8aff..52a860719 100644
--- a/src/components/insights/mood/mood-dimension-trends.tsx
+++ b/src/components/insights/mood/mood-dimension-trends.tsx
@@ -216,6 +216,7 @@ export function MoodDimensionTrends({
active
label={fmt.dateShortSmartCalendar(String(row.date))}
rows={rows}
+ action={chartDays.tooltipAction(chartData.indexOf(row))}
/>
);
}}
diff --git a/src/components/insights/sleep-stage-stacked-bar.tsx b/src/components/insights/sleep-stage-stacked-bar.tsx
index bd09ae618..ccf2e94c0 100644
--- a/src/components/insights/sleep-stage-stacked-bar.tsx
+++ b/src/components/insights/sleep-stage-stacked-bar.tsx
@@ -469,6 +469,7 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
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
@@ -549,6 +550,9 @@ export function SleepStageStackedBar({ breakdown }: SleepStageStackedBarProps) {
)}
)}
+ {chartDays.tooltipAction(
+ rowIndex === -1 ? undefined : rowIndex,
+ )}
);
}}
diff --git a/src/components/labs/lab-biomarker-chart.tsx b/src/components/labs/lab-biomarker-chart.tsx
index 97f78dcf8..7a8828340 100644
--- a/src/components/labs/lab-biomarker-chart.tsx
+++ b/src/components/labs/lab-biomarker-chart.tsx
@@ -406,6 +406,7 @@ export function LabBiomarkerChart({
active
label={labShortDate(point.timestamp)}
rows={rows}
+ action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
diff --git a/src/components/medications/detail/efficacy/efficacy-chart.tsx b/src/components/medications/detail/efficacy/efficacy-chart.tsx
index 36bab7d32..0d0307570 100644
--- a/src/components/medications/detail/efficacy/efficacy-chart.tsx
+++ b/src/components/medications/detail/efficacy/efficacy-chart.tsx
@@ -378,11 +378,18 @@ export function EfficacyChart({
color: item.color ?? "var(--chart-1)",
};
});
+ const index =
+ typeof x === "number"
+ ? displaySeries.findIndex((p) => p.t === x)
+ : -1;
return (
);
}}
diff --git a/src/components/medications/dose-strength-curve.tsx b/src/components/medications/dose-strength-curve.tsx
index 6040fb7c7..4b08d8082 100644
--- a/src/components/medications/dose-strength-curve.tsx
+++ b/src/components/medications/dose-strength-curve.tsx
@@ -326,6 +326,7 @@ export function DoseStrengthCurve({
active
label={fmt.dateShortSmart(new Date(point.t))}
rows={rows}
+ action={chartDays.tooltipAction(chartData.indexOf(point))}
/>
);
}}
diff --git a/src/components/mental-health/assessment-history-chart.tsx b/src/components/mental-health/assessment-history-chart.tsx
index 548b2165b..1cdf57adb 100644
--- a/src/components/mental-health/assessment-history-chart.tsx
+++ b/src/components/mental-health/assessment-history-chart.tsx
@@ -183,6 +183,7 @@ export function AssessmentHistoryChart({
active
label={fmt.dateShortSmart(new Date(point.timestamp))}
rows={rowsOut}
+ action={chartDays.tooltipAction(points.indexOf(point))}
/>
);
}}
From 4e7221f59b2ed42543bcd676898ebb633e369c7f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?=
Date: Thu, 8 Oct 2026 16:20:36 +0200
Subject: [PATCH 5/6] fix: spell a day's sleep and scores as their charts do
The day route sends a night's length in min and a device score in score.
The day read the night as a bare 412 and the score in the wire's word;
it now reads a duration and the reader's word for points. The phone
sheet's header takes the short date, so a long weekday and month no
longer cut off the year at 360 px.
---
e2e/day-doors.spec.ts | 12 ++-
.../__tests__/use-day-value-format.test.tsx | 77 +++++++++++++++++++
src/components/day/day-view.tsx | 21 ++++-
src/components/day/use-day-value-format.ts | 22 +++++-
4 files changed, 123 insertions(+), 9 deletions(-)
create mode 100644 src/components/day/__tests__/use-day-value-format.test.tsx
diff --git a/e2e/day-doors.spec.ts b/e2e/day-doors.spec.ts
index c83cfa352..357e2773c 100644
--- a/e2e/day-doors.spec.ts
+++ b/e2e/day-doors.spec.ts
@@ -1,5 +1,6 @@
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 {
@@ -203,6 +204,11 @@ test.describe("every chart drawn in days opens its days", () => {
.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();
@@ -265,9 +271,13 @@ test.describe("the dashboard and the list of all values", () => {
}, 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"]');
- test.skip((await fab.count()) === 0, "no Coach on this account");
+ await expect(fab).toBeVisible();
const plot = page
.locator('[data-slot="chart-plot"][data-day-links="true"]')
.first();
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/day-view.tsx b/src/components/day/day-view.tsx
index 0b7ff57a1..55e317a23 100644
--- a/src/components/day/day-view.tsx
+++ b/src/components/day/day-view.tsx
@@ -54,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`));
@@ -118,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();
@@ -218,7 +224,14 @@ export function DayView({
tabIndex={-1}
className="min-w-0 flex-1 truncate px-1 text-base leading-snug font-semibold focus-visible:outline-none"
>
- {longLabel(date)}
+ {compact ? (
+ <>
+ {shortLabel(date)}
+ {longLabel(date)}
+ >
+ ) : (
+ longLabel(date)
+ )}
= new Set([
"RESPIRATORY_RATE",
]);
+/**
+ * Two spellings of one unit: the day route sends a duration in "min", the
+ * client's unit map knows it as "minutes". Read as the same unit, so a night
+ * reads as "6 h 52 min" and not as a bare 412.
+ */
+const UNIT_ALIASES: Readonly> = { min: "minutes" };
+
+/** True when the row carries the type's canonical unit, in either spelling. */
+function isCanonicalUnit(row: Pick): boolean {
+ const canonical = getUnitForType(row.type);
+ return row.unit === canonical || UNIT_ALIASES[row.unit] === canonical;
+}
+
/** True for a type read in whole numbers (counts, pressures, pulses). */
export function isWholeNumberType(type: string): boolean {
return WHOLE_NUMBER_TYPES.has(type);
@@ -68,7 +81,7 @@ export function useDayValueFormat() {
const number = useCallback(
(row: Pick, raw: number): string => {
- const canonical = row.unit === getUnitForType(row.type);
+ const canonical = isCanonicalUnit(row);
const shown = canonical ? units.toDisplay(row.type, raw) : raw;
if (row.type === "SLEEP_DURATION" && canonical) {
return formatDurationMinutes(shown, t);
@@ -89,10 +102,11 @@ export function useDayValueFormat() {
const unitFor = useCallback(
(row: Pick): string => {
if (row.type === "SLEEP_DURATION") return "";
- if (row.unit === getUnitForType(row.type)) return units.unitFor(row.type);
- return row.unit;
+ const unit = isCanonicalUnit(row) ? units.unitFor(row.type) : row.unit;
+ // A device score reads in points, as on its chart.
+ return unit === "score" ? t("insights.deviceScore.unitScore") : unit;
},
- [units],
+ [t, units],
);
const formatTile = useCallback(
From 6f8ea3faf24c05a95aa67622dbdbb98614fdec8f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?=
Date: Thu, 8 Oct 2026 16:35:16 +0200
Subject: [PATCH 6/6] chore: raise the aggregate bundle cap for the chart day
doors
Measured 4386 KB gz on the release branch and 4446 with every chart drawn
in days opening its day; the difference is the aggregate counting the
shared hook, data table and day link once per chart chunk group. Every
eager route stays inside its allowance.
---
bundle-budget.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
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
}