"use client"; /** * Lab markers on the timeline (#1299): their rows under the value lines, * their readings in the selection bar and the phone chronicle, and their * table for a screen reader. * * A lab line is its readings, one point each on the day of the draw, never a * mean. Each row has its own scale, which holds the reference range as well * as the points, and the range is painted behind them as the labs page * paints it: a faint band with dashed edges, in the row's own colour. A * reading outside its range is a triangle pointing the way it left (up above * the range, down below it) and says so in words wherever it is written out, * so the colour is never the only sign. The numbers read through the labs * page's own formatter, so a reading keeps every digit it was stored with. */ import { useCallback } from "react"; import Link from "next/link"; import { useLabNumber } from "@/components/labs/use-lab-format"; import { InlineAction } from "@/components/ui/inline-action"; import type { TimelineBucket, TimelineLabPoint, TimelineLabSeries, } from "@/lib/day/contract"; import { resolveIntlLocale } from "@/lib/format-locale"; import { formatReferenceRange } from "@/lib/labs/reference-range"; import { useTranslations } from "@/lib/i18n/context"; import type { ChronicleEntry } from "./chronicle-model"; import { TIMELINE_LAB_RANGE_KEY } from "./label-keys"; import { bucketAfter, dayKey, dayNumber, formatDayMonth, formatDayMonthYear, } from "./timeline-dates"; import { seriesNameLines, type TimelineLayout } from "./timeline-geometry"; /** "18 ng/mL", every digit the reading holds, in the reader's locale. */ export type LabValueText = ( value: number, sourceValue: number | null, unit: string, ) => string; export function useLabValueText(): LabValueText { const labNumber = useLabNumber(); return useCallback( (value, sourceValue, unit) => `${labNumber(value, sourceValue)} ${unit}`.trim(), [labNumber], ); } /** "below range" / "above range", or null for a reading in range. */ export function useLabVerdict(): ( status: TimelineLabPoint["rangeStatus"], ) => string | null { const { t } = useTranslations(); return useCallback( (status) => status === "below" || status === "above" ? t(TIMELINE_LAB_RANGE_KEY[status]) : null, [t], ); } /** "Reference 30–400 ng/mL", or null without a range. */ export function useLabReference(): ( point: Pick, unit: string, ) => string | null { const { t } = useTranslations(); const labNumber = useLabNumber(); return useCallback( (point, unit) => { const range = formatReferenceRange( point.referenceLow, point.referenceHigh, (v) => labNumber(v), ); return range ? t("timeline.labs.reference", { range: `${range} ${unit}`.trim() }) : null; }, [t, labNumber], ); } /** The readings of every lab line whose day lies in `[from, to]`. */ export function labReadingsIn( labSeries: readonly TimelineLabSeries[], from: string, to: string, ): Array<{ key: string; unit: string; point: TimelineLabPoint }> { return labSeries.flatMap((s) => s.points .filter((p) => p.date >= from && p.date <= to) .map((point) => ({ key: s.key, unit: s.unit, point })), ); } /* ─── The rows on the chart ───────────────────────────────────────────────── */ /** Where a row's name and latest value start, as on the value lines. */ const TEXT_X = 16; /** * A reading's mark: a dot in range (or without one), a triangle pointing up * above it and down below it. Every mark takes the row's `currentColor`. */ export function LabPointGlyph({ x, y, status, }: { x: number; y: number; status: TimelineLabPoint["rangeStatus"]; }) { if (status === "above" || status === "below") { const d = status === "above" ? `M${x} ${y - 4.5}L${x + 4.5} ${y + 3.5}L${x - 4.5} ${y + 3.5}Z` : `M${x} ${y + 4.5}L${x + 4.5} ${y - 3.5}L${x - 4.5} ${y - 3.5}Z`; return ( ); } return ( ); } export function LabLines({ layout, selectedBucket, bucket, seriesLabel, seriesColor, valueText, }: { layout: Pick< TimelineLayout, "labSeries" | "series" | "seriesTop" | "scale" | "width" >; /** The first day of the selected bucket: its readings are ringed. */ selectedBucket: string | null; bucket: TimelineBucket; seriesLabel: (key: string) => string; seriesColor: (key: string) => string; valueText: LabValueText; }) { const { t } = useTranslations(); const { scale, width } = layout; const rows = layout.labSeries; const selectedTo = selectedBucket ? dayKey(dayNumber(bucketAfter(selectedBucket, bucket)) - 1) : null; const nameLines = (key: string) => seriesNameLines(seriesLabel(key), scale.x0 - 12 - TEXT_X, 13); return ( <> {/* The hairline above the rows, when no value line drew it already. */} {layout.series.length === 0 && rows.length > 0 && ( )} {rows.map((row) => { const color = seriesColor(row.key); const lines = nameLines(row.key); return ( {row.band && ( {row.band.top !== null && row.band.bottom !== null && ( )} {[row.band.top, row.band.bottom].map((edge, i) => edge === null ? null : ( ), )} )} {lines.map((line, i) => ( {line} ))} {row.latest === null ? t("timeline.values.noneInWindow") : valueText(row.latest.value, row.latest.sourceValue, row.unit)} {row.path && ( )} {row.points.map((point) => ( ))} {selectedBucket !== null && selectedTo !== null && row.points .filter( (point) => point.date >= selectedBucket && point.date <= selectedTo, ) .map((point) => ( ))} ); })} ); } /* ─── Written out ─────────────────────────────────────────────────────────── */ /** * Lab readings as a line of their own under the means: "● Ferritin 18 ng/mL, * below range, 12 Feb." with the report it came from as a link. Each reading * is one unit that wraps only between units, like a means line. */ export function LabReadingsLine({ readings, label, seriesColor, valueText, showDate, links = true, intl, }: { readings: ReturnType; label: (key: string) => string; seriesColor: (key: string) => string; valueText: LabValueText; /** The day beside each reading: where a line covers more than one day. */ showDate: boolean; /** * The report as a link. Off inside a row that is itself a button (a link * cannot sit inside one); the day the row opens names the report. */ links?: boolean; intl: string; }) { const { t } = useTranslations(); const verdict = useLabVerdict(); return readings.map(({ key, unit, point }, i) => { const words = [ `${label(key)} ${valueText(point.value, point.sourceValue, unit)}`, verdict(point.rangeStatus), showDate ? formatDayMonth(point.date, intl) : null, ] .filter(Boolean) .join(", "); return ( {i > 0 ? , : null} ); }); } /** * A lab day's row in the phone chronicle lists the chosen lab lines' * readings of that day under its names. The row is a button that opens the * day, so the report is named there, not linked here. */ export function ChronicleLabReadings({ entry, labSeries, seriesColor, className, }: { entry: ChronicleEntry; labSeries: readonly TimelineLabSeries[]; seriesColor: (key: string) => string; /** The row's means-line classes, so both read alike. */ className: string; }) { const { locale } = useTranslations(); const valueText = useLabValueText(); if ( entry.kind !== "item" || entry.item.kind !== "labDay" || entry.role === "end" ) { return null; } const readings = labReadingsIn(labSeries, entry.date, entry.date); if (readings.length === 0) return null; return ( labSeries.find((s) => s.key === key)?.name ?? key} seriesColor={seriesColor} valueText={valueText} showDate={false} links={false} intl={resolveIntlLocale(locale)} /> ); } /** * A lab line with readings left out because their unit does not convert into * the marker's says so, once, under the chart (and over the phone list): * nothing is dropped without a word. */ export function LabExcludedNote({ labSeries, label, block = false, }: { labSeries: readonly TimelineLabSeries[]; label: (key: string) => string; /** A line of its own (the phone list), not runs inside the legend. */ block?: boolean; }) { const { tCount } = useTranslations(); const lines = labSeries.filter((s) => s.excluded > 0); if (lines.length === 0) return null; const notes = lines.map((s) => ( {tCount("timeline.labs.excluded", s.excluded, { name: label(s.key) })} )); return block ? (
{notes}
) : ( notes ); } /** * The lab lines as a table, for a screen reader: one row per reading, its * marker, day, value, verdict, range and report. Visually hidden by a * wrapper, as the other chart tables are. */ export function LabSeriesTable({ labSeries, window, label, valueText, intl, }: { labSeries: readonly TimelineLabSeries[]; window: { from: string; to: string }; label: (key: string) => string; valueText: LabValueText; intl: string; }) { const { t } = useTranslations(); const verdict = useLabVerdict(); const reference = useLabReference(); const rows = labReadingsIn(labSeries, window.from, window.to).sort((a, b) => a.point.date < b.point.date ? 1 : -1, ); if (rows.length === 0) return null; return (
{rows.map(({ key, unit, point }) => ( ))}
{t("timeline.table.labsCaption")}
{t("timeline.table.marker")} {t("timeline.table.date")} {t("timeline.table.value")}
{label(key)} {formatDayMonthYear(point.date, intl)} {[ valueText(point.value, point.sourceValue, unit), verdict(point.rangeStatus), reference(point, unit), point.report ? point.report.title ? t("timeline.labs.report", { title: point.report.title, }) : t("timeline.labs.reportUntitled") : null, ] .filter(Boolean) .join(", ")}
); }