"use client"; /** * The timeline's lanes and value lines, as one hand-drawn SVG (v1.42, #613). * * Recharts draws every value chart in the app and stays there; it cannot lay * periods and events out in lanes on a shared time axis, so this one surface * is plain SVG, like the mood and intake heatmaps. Nothing is decided here: * `timeline-geometry.ts` places every mark and label, this file paints them. * * Reading it without sight or without a mouse: * - The drawing itself is `aria-hidden`. A visually hidden table beside it * lists every entry with its lane, start and end, and a one-line summary * names the window and the lanes. * - The chart is one tab stop. Left and right move the selection by a day, * a month or a year with the zoom; Home and End jump to the oldest data * and to today; Enter opens the selected day. The selection bar under the * chart announces each move. * - A pointer selects with a click and opens the day with a double click. * * The width comes from a ResizeObserver, so a docked day panel that narrows * the card re-runs the layout: labels that no longer fit are left out, never * overlapped. */ import { metricPageHref } from "@/lib/insights/metric-page"; import Link from "next/link"; import { SeriesPointTips } from "./series-point-tips"; import { useEffect, useMemo, useRef, useState, type KeyboardEvent, } from "react"; import { CalendarHeart, FileText, Flag, FlaskConical, Pill, Shield, Stethoscope, Syringe, Thermometer, type LucideIcon, } from "lucide-react"; import type { TimelineBucket, TimelineLaneKey, TimelineResponse, TimelineZoom, } from "@/lib/day/contract"; import { resolveIntlLocale } from "@/lib/format-locale"; import { useTranslations } from "@/lib/i18n/context"; import { useItemWords, type ItemWordsFn } from "./item-words"; import { LabLines, LabSeriesTable, useLabValueText, type LabValueText, } from "./lab-lines"; import { SeriesTable, TimelineTable, bucketText } from "./timeline-tables"; import { TIMELINE_LANE_LABEL_KEY } from "./label-keys"; import { bucketStart, formatAtPrecision, formatMonthShort, formatMonthYear, } from "./timeline-dates"; import { AXIS_HEIGHT, LANE_COLOR, dateAtPointer, estimateTextWidth, fitText, seriesNameLines, gridTicks, todayLabelFits, wrapToWidth, layoutTimeline, stepSelection, zoomShape, type PlacedPoint, type PlacedSpan, type TimeWindow, } from "./timeline-geometry"; import { SERIES_HEIGHT } from "./series-geometry"; import { formatSeriesValue, type MeanPart, type SeriesValueFormat, } from "./series-format"; /** Where a value line's name and latest value start, right of its swatch. */ const SERIES_TEXT_X = 16; export const LANE_ICON: Readonly> = { life: Flag, illness: Thermometer, allergies: Shield, medications: Pill, vaccinations: Syringe, visits: Stethoscope, labs: FlaskConical, documents: FileText, cycle: CalendarHeart, }; export interface TimelineChartProps { timeline: TimelineResponse; window: TimeWindow; zoom: TimelineZoom; today: string; selected: string | null; hiddenLanes: ReadonlySet; seriesLabel: (key: string) => string; /** The colour of a value line (`series-colors.ts`), as a token string. */ seriesColor: (key: string) => string; /** How a value reads (`useSeriesValueFormat`). */ seriesFormat: SeriesValueFormat; onSelect: (date: string) => void; onOpenDay: (date: string) => void; } /** Observed content width of an element, 0 until measured. */ function useElementWidth() { const ref = useRef(null); const [width, setWidth] = useState(0); useEffect(() => { const el = ref.current; if (!el) return; setWidth(el.clientWidth); if (typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver((entries) => { const next = Math.floor(entries[0]?.contentRect.width ?? el.clientWidth); setWidth((prev) => (prev === next ? prev : next)); }); observer.observe(el); return () => observer.disconnect(); }, []); return { ref, width }; } export function TimelineChart({ timeline, window, zoom, today, selected, hiddenLanes, seriesLabel, seriesColor, seriesFormat, onSelect, onOpenDay, }: TimelineChartProps) { const { t, locale } = useTranslations(); const words = useItemWords(); const fmt = seriesFormat; const labValueText = useLabValueText(); const intl = resolveIntlLocale(locale); const { ref, width } = useElementWidth(); const lanes = useMemo( () => timeline.lanes.filter((l) => !hiddenLanes.has(l.key)), [timeline.lanes, hiddenLanes], ); const layout = useMemo( () => width > 0 ? layoutTimeline({ width, window, lanes, series: timeline.series, labSeries: timeline.labSeries, bucket: timeline.bucket, words, startMissing: t("timeline.startUnknown"), today, }) : null, [ width, window, lanes, timeline.series, timeline.labSeries, timeline.bucket, words, t, today, ], ); const floor = timeline.range.dataFrom ?? window.from; const shape = zoomShape(zoom, window); function handleKey(event: KeyboardEvent) { const current = selected ?? today; let next: string | null = null; if (event.key === "ArrowLeft") next = stepSelection(current, -1, shape, today, floor); else if (event.key === "ArrowRight") next = stepSelection(current, 1, shape, today, floor); else if (event.key === "Home") next = floor; else if (event.key === "End") next = today; else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onOpenDay(current); return; } if (next !== null) { event.preventDefault(); onSelect(next); } } function pointerDate(event: React.MouseEvent): string | null { if (!layout) return null; const rect = event.currentTarget.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; if (x < layout.scale.x0) return null; return dateAtPointer(layout, x, y); } const summary = t("timeline.chartLabel", { from: formatMonthYear(window.from, intl), to: formatMonthYear(window.to, intl), }); return (

{t("timeline.keyboardHint")}

{layout ? ( ) : (
)} {layout ? ( <> bucketText(start, timeline.bucket, intl, t) } onSelect={onSelect} onOpenDay={onOpenDay} /> ) : null}
); } /** * A value line's name leads to its metric's page, as a value tile in the day * view does (`metricPageHref`, one map for both). The names are drawn in the * SVG; the links lie over them as plain HTML, so they take focus, a hover * and a 44 px target over the line's height. A kind without a page keeps a * plain name. Enter on a link follows it and never reaches the chart's own * Enter, which opens the day. */ export function SeriesNameLinks({ layout, seriesLabel, }: { layout: NonNullable>; seriesLabel: (key: string) => string; }) { // A lab line's name leads to its marker's page on the labs list. const rows = [ ...layout.series.map((s) => ({ key: s.key, top: s.top, href: metricPageHref(s.key), })), ...layout.labSeries.map((s) => ({ key: s.key, top: s.top, href: `/labs/${encodeURIComponent(s.biomarkerId)}`, })), ]; return ( <> {rows.map((series) => { const href = series.href; if (!href) return null; return ( event.stopPropagation()} onClick={(event) => event.stopPropagation()} className="hover:bg-foreground/5 focus-visible:ring-ring/50 absolute left-0 rounded-md outline-none focus-visible:ring-2" style={{ top: series.top - 4, width: layout.scale.x0 - 8, height: Math.max(44, SERIES_HEIGHT - 12), }} /> ); })} ); } interface ChartBodyProps { layout: NonNullable>; window: TimeWindow; zoom: Exclude; today: string; selected: string | null; dataFrom: string | null; bucket: TimelineBucket; seriesLabel: (key: string) => string; seriesColor: (key: string) => string; intl: string; t: ReturnType["t"]; fmt: SeriesValueFormat; labValueText: LabValueText; } function ChartBody({ layout, window, zoom, today, selected, dataFrom, bucket, seriesLabel, seriesColor, intl, t, fmt, labValueText, }: ChartBodyProps) { const { scale, height, width } = layout; const todayInWindow = today >= window.from && today <= window.to; const todayX = scale.xMid(today); const todayLabel = t("timeline.today"); const todayLabelWidth = estimateTextWidth(todayLabel, 11); const ticks = gridTicks(window, zoom, scale, { year: (k) => k.slice(0, 4), monthShort: (k) => formatMonthShort(k, intl), monthYear: (k) => formatMonthYear(k, intl), }); const showTodayLabel = todayInWindow && todayLabelFits(ticks, todayX, todayLabelWidth, scale.x0); const noDataUntil = dataFrom && dataFrom > window.from && dataFrom <= window.to ? scale.x(dataFrom) : null; // The bucket that holds the selected day: its point on every line is // ringed in the line's colour, so the selection reads on each scale. const selectedBucket = selected && selected >= window.from && selected <= window.to ? bucketStart(selected, bucket) : null; return ( {noDataUntil !== null && ( )} {/* Grid and axis labels. */} {ticks.map((tick) => ( {tick.label && ( {tick.label} )} ))} {/* Lanes. */} {layout.lanes.map((lane, index) => { const Icon = LANE_ICON[lane.key]; const color = LANE_COLOR[lane.key]; return ( {index > 0 && ( )} {fitText(t(TIMELINE_LANE_LABEL_KEY[lane.key]), scale.x0 - 30, 13)} {/* A medication's bar is drawn in pieces of one item, so a piece is keyed by its item and its own first day. */} {lane.spans.map((span) => ( ))} {lane.points.map((point) => ( ))} ); })} {/* Value lines: one scale each, each in its own colour (the colour its type carries in the measurement list). The colour names the line, never a judgement of its values. */} {/* Lab lines (#1299): single readings, under the value lines. */} {/* Today. */} {todayInWindow && ( {showTodayLabel && ( {todayLabel} )} )} {/* Selection. */} {selected && selected >= window.from && selected <= window.to && ( )} {/* The names last, over the today and selection lines, each on a halo of the card's colour: a line passing a name runs behind it and never through its letters. */} {layout.lanes.flatMap((lane) => lane.labels.map((label, i) => ( {label.text} )), )} ); } /** * The stretch before the record's first entry, shaded and named, so an empty * start reads as "no data yet" and not as a quiet period. */ function NoDataShade({ x0, until, height, label, }: { x0: number; until: number; height: number; label: string; }) { return ( {wrapToWidth(label, until - x0 - 12).map((line, i, lines) => ( {line} ))} ); } /** * The value lines under the lanes, each in its own colour: the swatch beside * the name, the line, the dashed bridge over a gap, the points (hollow where * a mean rests on one or two readings) and the ring on the selected bucket. * Every mark of a line inherits one `color` from its group, so they cannot * drift apart. */ export function SeriesLines({ layout, width, selectedBucket, seriesLabel, seriesColor, t, fmt, }: { layout: NonNullable>; width: number; selectedBucket: string | null; seriesLabel: (key: string) => string; seriesColor: (key: string) => string; t: ReturnType["t"]; fmt: SeriesValueFormat; }) { const { scale, seriesTop } = layout; const nameLines = (key: string) => seriesNameLines(seriesLabel(key), scale.x0 - 12 - SERIES_TEXT_X, 13); return ( <> {layout.series.length > 0 && ( )} {layout.series.map((series) => { const color = seriesColor(series.key); return ( {nameLines(series.key).map((line, i) => ( {line} ))} {series.latest === null ? t("timeline.values.noneInWindow") : formatSeriesValue( series.key, series.latest, series.unit, fmt, )} {series.path && ( )} {series.bridges && ( )} {series.points.map((point) => ( ))} {series.points .filter((point) => point.t === selectedBucket) .map((point) => ( ))} ); })} ); } /** * A bar's hover title: "Ramipril 5 mg: 12 Aug 2020 to 1 Jun 2021", or * "since 12 Aug 2020" while it runs on. A dose's piece of a medication's * bar names that dose and its own days. */ function spanTitle( span: PlacedSpan, intl: string, t: ReturnType["t"], words: ItemWordsFn, ): string { const { item, segment } = span; const { label, sub, tag } = words(item); const name = [label, segment ? segment.dose : sub, tag ? `(${tag})` : null] .filter(Boolean) .join(" "); const start = segment?.start ?? item.start; const end = segment ? segment.end : item.open ? null : item.end; const from = formatAtPrecision(start, item.precision, intl); const when = end === null ? t("timeline.selection.since", { date: from }) : t("timeline.selection.range", { from, to: formatAtPrecision(end, item.precision, intl), }); return `${name}: ${when}`; } export function SpanMark({ span, color, x0, intl, t, }: { span: PlacedSpan; color: string; x0: number; intl: string; t: ReturnType["t"]; }) { const { item, xStart, xEnd, y } = span; const words = useItemWords(); const title = spanTitle(span, intl, t, words); if (span.pause) { return ( {title} ); } const thick = item.open ? 3 : 7; // Only a bar's first piece draws an unknown start, only its last an open // end; a bar that is not cut is both. const first = span.segment?.first ?? true; const last = span.segment?.last ?? true; return ( {title} {!item.startKnown && first && ( )} {item.open && last && ( )} {span.clippedLeft && item.startKnown && ( )} ); } export function PointMark({ point, color, intl, }: { point: PlacedPoint; color: string; intl: string; }) { const { x, y, item, shape } = point; const { label, sub, tag } = useItemWords()(item); const title = `${[label, sub, tag ? `(${tag})` : null].filter(Boolean).join(" ")}: ${formatAtPrecision(item.start, item.precision, intl)}`; let glyph: React.ReactNode; switch (shape) { case "diamond": glyph = ( ); break; case "square": glyph = ( ); break; case "tick": glyph = ( ); break; case "ring": glyph = ( ); break; case "doseMark": glyph = ( ); break; default: glyph = ( ); } return ( {title} {glyph} ); } /** * A means line with each value marked by its line's colour: "● 129/82 mmHg * ● 82,6 kg". The values stand apart by space, not by a separator glyph; * a screen reader hears a comma between them. The dot is decoration; the * text reads the same without it. * * Each dot and its value are one unit that never breaks: a line wraps only * between units (the caller's container is a wrapping flex row), so a dot * cannot stay behind at the end of a line while its value moves to the * next. The dot sits on the middle of the text line, and a name too long for * the row is cut short inside its unit. `lead` (the "Ø" in front of the * selection bar's means) rides in the first unit for the same reason. */ export function MeanPartsLine({ parts, seriesColor, lead, }: { parts: readonly MeanPart[]; seriesColor: (key: string) => string; lead?: React.ReactNode; }) { return parts.map((part, i) => ( {i === 0 && lead ? {lead} : null} {i > 0 ? , : null} )); } /** The row the units of a `MeanPartsLine` wrap in: breaks only between them. */ export const MEAN_PARTS_ROW = "text-muted-foreground inline-flex max-w-full flex-wrap items-center gap-x-3 gap-y-1 text-xs tabular-nums"; /** Inline style for a lane colour dot in HTML (chips, chronicle rails). */ export function laneDotStyle(lane: TimelineLaneKey): React.CSSProperties { return { background: LANE_COLOR[lane] }; }