feat: add the timeline page, its readiness inventory and life-event entry

The opt-in timeline module gets its page (#613). At 768 px and up the
record's lanes (life, conditions, allergies, medications, vaccinations,
doctor and procedures, labs, documents) are drawn in one SVG on a shared
time axis, with a year, month or week grid, open periods ending in an
arrow, a dashed lead-in where a start is unknown, dose marks and pauses on
the medication they belong to, a Today line and a selection line. Up to
three neutral value lines run below as monthly means, chosen in a menu.
Recharts stays for every value chart; this surface is plain SVG like the
heatmaps.

All geometry is pure (timeline-geometry.ts): window, scale, row packing
and label placement through one occupancy map, so no label overlaps
another label or a bar, none runs past the card edge, and labels that do
not fit are left out rather than squeezed. The width comes from a
ResizeObserver, so a docked day panel re-runs the layout.

The bar under the chart names the selected month's entries as chips, the
month's means and "Open 3 Jan.", which puts ?day= in the URL for the day
layer. The chart is one tab stop: arrows move the selection by a day, a
month or a year with the zoom, Home and End jump to the ends, Enter opens
the day. A visually hidden table lists every entry for screen readers.
The legend says once that stacked means at the same time, not cause and
effect.

Below 768 px the timeline is a chronicle, newest first by month or year,
with an Ongoing block for what has no meaningful start, rails beside the
rows an episode or course spans, and empty stretches named as such.

Switching the module on in Settings opens the readiness inventory: each
lane carries, is thin or is empty, with one link per gap and the verdict
as a count. The same inventory sits as a dismissible card on the timeline
while a gap is open, and under Layers as "Data coverage".

Life events are entered in a sheet (title, kind, a date to the day, month
or year, an optional end, an optional note) from the timeline, the
capture picker and the dashboard's add menu; one surface line maps the
capture kind to the timeline module, and it is offered in one's own
record only. Deleting asks first.

Server routes are built in parallel; the e2e journey answers them with the
contract's shapes. Copy in all seven locales; the timeline and lifeEvents
release-pending prefixes are gone.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 14:27:02 +02:00
1 parent b8f6372963
commit 32258bc5ab
50 files changed
+8277 -54

No files matched your search

@@ -0,0 +1,167 @@
/**
* v1.42 (#613) — the phone chronicle: newest first, grouped, empty stretches
* said out loud, open things once in the Ongoing block, closed periods as
* rails.
*/
import { describe, expect, it } from "vitest";
import {
buildChronicle,
chronicleEntries,
standingChips,
type ChronicleRow,
} from "../chronicle-model";
import { TODAY, fullTimeline } from "./timeline-fixture";
function headers(rows: ChronicleRow[]) {
return rows
.filter((r) => r.type === "header")
.map((r) => (r.type === "header" ? r.group : ""));
}
describe("chronicleEntries", () => {
it("lists points, period starts and period ends, newest first", () => {
const entries = chronicleEntries(fullTimeline(), TODAY);
const dates = entries.map((e) => e.date);
expect([...dates].sort().reverse()).toEqual(dates);
const cold = entries.filter(
(e) => e.kind === "item" && e.item.id === "ill-5",
);
expect(cold.map((e) => (e.kind === "item" ? e.role : null))).toEqual([
"end",
"start",
]);
const end = cold[0];
expect(end.kind === "item" && end.days).toBe(9);
});
it("never lists anything after today", () => {
const tl = fullTimeline();
tl.lanes[0].items.push({
id: "future",
kind: "lifeEvent",
start: "2027-01-01",
end: null,
open: false,
precision: "DAY",
startKnown: true,
label: "x",
sub: null,
href: null,
});
expect(chronicleEntries(tl, TODAY).some((e) => e.date > TODAY)).toBe(false);
});
it("carries the quiet notable line", () => {
const entries = chronicleEntries(fullTimeline(), TODAY);
expect(entries.find((e) => e.kind === "notable")).toMatchObject({
date: "2026-01-04",
notable: "extremeHigh",
});
});
});
describe("buildChronicle", () => {
it("folds a run of empty months into one honest gap row", () => {
const rows = buildChronicle(fullTimeline(), TODAY, "month");
// The last entry is the course ending on 31 March 2026: April to
// October 2026 hold nothing.
const gap = rows.find((r) => r.type === "gap" && r.to === "2026-10-01");
expect(gap).toEqual({
type: "gap",
from: "2026-04-01",
to: "2026-10-01",
rails: {},
});
expect(headers(rows)[0]).toBe("2026-03-01");
});
it("keeps a course's rail through an empty stretch it spans", () => {
const rows = buildChronicle(fullTimeline(), TODAY, "month");
// The 2024/25 winter course runs from November to March; nothing else
// is dated in December to February.
const gap = rows.find((r) => r.type === "gap" && r.from === "2024-12-01");
expect(gap?.type === "gap" && gap.rails.medications).toBe("full");
});
it("never shows two gap rows next to each other", () => {
const rows = buildChronicle(fullTimeline(), TODAY, "month");
for (let i = 1; i < rows.length; i++) {
expect(rows[i].type === "gap" && rows[i - 1].type === "gap").toBe(false);
}
});
it("groups by year when asked", () => {
const rows = buildChronicle(fullTimeline(), TODAY, "year");
expect(headers(rows)).toEqual([
"2026-01-01",
"2025-01-01",
"2024-01-01",
"2023-01-01",
"2022-01-01",
"2021-01-01",
"2020-01-01",
"2019-01-01",
// The grass-pollen allergy began in 2018.
"2018-01-01",
]);
});
it("draws a closed episode as a rail from its end row down to its start row", () => {
const rows = buildChronicle(fullTimeline(), TODAY, "month");
const railOf = (id: string, role: string) => {
const row = rows.find(
(r) =>
r.type === "entry" &&
r.entry.kind === "item" &&
r.entry.item.id === id &&
r.entry.role === role,
);
return row && row.type === "entry" ? row.rails.illness : undefined;
};
expect(railOf("ill-5", "end")).toBe("end");
expect(railOf("ill-5", "start")).toBe("start");
// The visit on 3 January sits inside the cold.
const visit = rows.find(
(r) =>
r.type === "entry" &&
r.entry.kind === "item" &&
r.entry.item.id === "v-4",
);
expect(visit?.type === "entry" && visit.rails.illness).toBe("full");
});
it("is empty for a record without anything dated", () => {
expect(
buildChronicle(
{
lanes: [],
notable: [],
range: { from: "2026-01-01", to: "2026-12-31", dataFrom: null },
},
TODAY,
"month",
),
).toEqual([]);
});
});
describe("standingChips", () => {
it("collects open things once and folds several allergies into one chip", () => {
const chips = standingChips(fullTimeline());
expect(chips.map((c) => c.id)).toEqual([
"ill-chronic",
"med-1",
"allergies",
]);
expect(chips.at(-1)).toMatchObject({ lane: "allergies", count: 2 });
});
it("lists a standing item without a start", () => {
const tl = fullTimeline();
tl.standing = [
{ lane: "illness", id: "pre", label: "Asthma", since: null, href: null },
];
expect(standingChips(tl).map((c) => c.label)).toContain("Asthma");
});
});
@@ -0,0 +1,154 @@
/**
* v1.42 (#613) — the readiness inventory's reading order and card rule, and
* the life-event form's checks and request bodies.
*/
import { describe, expect, it } from "vitest";
import type { LifeEventDTO } from "@/lib/day/contract";
import {
alignToPrecision,
createBody,
draftFromEvent,
emptyDraft,
updateBody,
validateDraft,
withPrecision,
} from "../life-event-draft";
import {
orderedReadinessLanes,
readinessGaps,
readinessTally,
showReadinessCard,
} from "../readiness-model";
import { readiness } from "./timeline-fixture";
describe("readiness", () => {
it("reads carrying lanes first, then thin, then empty", () => {
expect(orderedReadinessLanes(readiness()).map((l) => l.status)).toEqual([
"carries",
"carries",
"carries",
"thin",
"empty",
"empty",
]);
});
it("offers one link per gap, in reading order", () => {
expect(readinessGaps(readiness()).map((g) => g.key)).toEqual([
"medicationsWithoutStart",
"lifeEventsEmpty",
"vaccinationsEmpty",
]);
});
it("counts the carrying lanes, never a score", () => {
expect(readinessTally(readiness())).toEqual({ carrying: 3, total: 6 });
});
it("shows the card while a thin or empty lane has a link, until closed", () => {
expect(showReadinessCard(readiness(), false)).toBe(true);
expect(showReadinessCard(readiness(), true)).toBe(false);
expect(showReadinessCard(undefined, false)).toBe(false);
const allCarry = readiness({
lanes: readiness().lanes.map((l) => ({
...l,
status: "carries" as const,
gaps: [],
})),
});
expect(showReadinessCard(allCarry, false)).toBe(false);
});
});
const STORED: LifeEventDTO = {
id: "le-1",
category: "HOME",
startDate: "2023-09-01",
endDate: null,
precision: "MONTH",
title: "Umzug",
note: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
describe("life-event draft", () => {
it("asks for a title and a kind before anything is sent", () => {
expect(validateDraft(emptyDraft("2026-10-07"))).toEqual({
title: "titleRequired",
category: "categoryRequired",
});
});
it("refuses an end before the start and an over-long title", () => {
const draft = {
...emptyDraft("2026-10-07"),
title: "x".repeat(121),
category: "WORK" as const,
end: "2026-01-01",
};
expect(validateDraft(draft)).toEqual({
title: "titleTooLong",
end: "endBeforeStart",
});
});
it("refuses a date that is not a calendar date", () => {
const draft = {
...emptyDraft("2026-02-30"),
title: "a",
category: "OTHER" as const,
};
expect(validateDraft(draft).start).toBe("dateRequired");
});
it("aligns both ends when the precision changes", () => {
expect(alignToPrecision("2023-09-17", "MONTH")).toBe("2023-09-01");
expect(alignToPrecision("2023-09-17", "YEAR")).toBe("2023-01-01");
const draft = withPrecision(
{ ...emptyDraft("2023-09-17"), end: "2024-02-11" },
"MONTH",
);
expect([draft.start, draft.end]).toEqual(["2023-09-01", "2024-02-01"]);
});
it("sends a trimmed body, a blank note as null", () => {
const body = createBody({
...emptyDraft("2023-09-17"),
title: " Umzug nach Bochum ",
category: "HOME",
precision: "MONTH",
note: " ",
});
expect(body).toEqual({
category: "HOME",
precision: "MONTH",
startDate: "2023-09-01",
endDate: null,
title: "Umzug nach Bochum",
note: null,
});
});
it("patches only what changed, dates and precision together", () => {
const draft = draftFromEvent(STORED);
expect(updateBody(STORED, draft)).toEqual({});
expect(
updateBody(STORED, { ...draft, title: "Umzug nach Bochum" }),
).toEqual({
title: "Umzug nach Bochum",
});
expect(updateBody(STORED, withPrecision(draft, "YEAR"))).toEqual({
precision: "YEAR",
startDate: "2023-01-01",
endDate: null,
});
expect(
updateBody({ ...STORED, note: "alt" }, { ...draft, note: "" }),
).toEqual({
note: null,
});
});
});
@@ -0,0 +1,163 @@
/**
* v1.42 (#613) — the timeline's surfaces as rendered: the readiness
* inventory in its three states, the card, the phone chronicle's honest
* gaps and the selection bar's hand-off to the day, and the capture-picker
* gate for life events.
*/
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import {
CAPTURE_KIND_ORDER,
visibleCaptureKinds,
} from "@/components/layout/capture-picker";
import { I18nProvider } from "@/lib/i18n/context";
import { ReadinessCard } from "../readiness-card";
import { ReadinessInventory, VerdictMeter } from "../readiness-inventory";
import { SelectionBar } from "../selection-bar";
import { TimelineChronicle } from "../timeline-chronicle";
import { TODAY, fullTimeline, readiness } from "./timeline-fixture";
function render(node: React.ReactElement, locale: "de" | "en" = "de") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
describe("readiness inventory", () => {
it("names every lane with its state and one link per gap", () => {
const html = render(<ReadinessInventory readiness={readiness()} />);
expect(html.match(/data-slot="timeline-readiness-lane"/g)).toHaveLength(6);
expect(html).toContain('data-status="carries"');
expect(html).toContain('data-status="thin"');
expect(html).toContain('data-status="empty"');
expect(html).toContain("6 Episoden, davon 1 chronisch");
expect(html).toContain("5 Medikamente, 3 ohne Startdatum");
expect(html).toContain("3 Messgrößen seit März 2019");
expect(html.match(/data-slot="timeline-readiness-gap"/g)).toHaveLength(3);
expect(html).toContain('href="/medications/med-1?edit=1"');
expect(html).toContain("Impfpass erfassen");
});
it("leaves out a detail the bundle cannot word instead of showing a raw key", () => {
const html = render(
<ReadinessInventory
readiness={readiness({
lanes: [
{
key: "labs",
status: "carries",
count: 2,
detail: { key: "somethingNew", params: { count: 2 } },
gaps: [{ key: "unknownGap", count: 0, href: "/labs" }],
},
],
})}
/>,
);
expect(html).not.toContain("somethingNew");
expect(html).not.toContain("unknownGap");
expect(html).not.toContain('data-slot="timeline-readiness-gap"');
});
it("states the verdict as a count, never a score", () => {
const carries = render(<VerdictMeter readiness={readiness()} />);
expect(carries).toContain("Trägt schon.");
expect(carries).toContain(
"3 von 6 Spuren reichen für einen Überblick ab März 2019.",
);
expect(carries).toContain('aria-label="3 von 6 Spuren tragen"');
const thin = render(
<VerdictMeter readiness={readiness({ verdict: "thin", since: null })} />,
);
expect(thin).toContain("Noch dünn.");
expect(thin).not.toContain("Überblick ab");
});
it("puts the gaps on the timeline card with their lines", () => {
const html = render(
<ReadinessCard readiness={readiness()} onDismiss={() => undefined} />,
);
expect(html).toContain("3 Medikamente ohne Startdatum");
expect(html).toContain("Noch keine Lebensereignisse");
expect(html).toContain('href="/timeline?add=lifeEvent"');
expect(html).toContain('data-slot="timeline-readiness-card-dismiss"');
});
});
describe("chronicle", () => {
it("names an empty stretch instead of skipping it, and folds the ongoing items", () => {
const html = render(
<TimelineChronicle
timeline={fullTimeline()}
today={TODAY}
grouping="month"
selected="2026-01-03"
onOpenDay={() => undefined}
onEditLifeEvent={null}
/>,
);
expect(html).toContain("April bis Oktober 2026 · keine Einträge");
expect(html).toContain("Dauerhaft");
expect(html).toContain("2 Allergien");
expect(html).toContain("Erkältung vorbei");
expect(html).toContain("nach 9 Tagen");
expect(html).toContain("Höchster Wert seit Langem");
// The selected day is the highlighted row.
expect(html).toMatch(/data-date="2026-01-03"><button[^>]*bg-muted/);
});
it("shows the month's means beside the month", () => {
const html = render(
<TimelineChronicle
timeline={fullTimeline()}
today={TODAY}
grouping="month"
selected={null}
onOpenDay={() => undefined}
onEditLifeEvent={null}
/>,
);
expect(html).toContain("129/82 mmHg · 82,6 kg");
});
});
describe("selection bar", () => {
it("lists the month's entries and offers the selected day", () => {
const html = render(
<SelectionBar
timeline={fullTimeline()}
selected="2026-01-03"
today={TODAY}
onOpenDay={() => undefined}
/>,
);
expect(html).toContain("Januar 2026");
expect(html).toContain("Erkältung · 31. Dez. bis 8. Jan.");
expect(html).toContain("Vitamin D (Winter) · laufend");
expect(html).not.toContain("Bluthochdruck");
expect(html).toContain("3. Jan. öffnen");
expect(html).toContain('data-date="2026-01-03"');
expect(html).toContain("Ø 129/82 mmHg · 82,6 kg");
});
});
describe("life events in the capture picker", () => {
const own = { inSharedRecord: false, canWriteDomain: () => true };
it("is offered only with the timeline module on", () => {
expect(
visibleCaptureKinds(own, CAPTURE_KIND_ORDER, { timeline: false }),
).not.toContain("lifeEvent");
expect(
visibleCaptureKinds(own, CAPTURE_KIND_ORDER, { timeline: true }),
).toContain("lifeEvent");
});
it("is never offered inside somebody else's record", () => {
const delegate = { inSharedRecord: true, canWriteDomain: () => true };
expect(
visibleCaptureKinds(delegate, CAPTURE_KIND_ORDER, { timeline: true }),
).not.toContain("lifeEvent");
});
});
@@ -0,0 +1,329 @@
/**
* A made-up record for the timeline tests: a chronic condition and several
* episodes, two allergies, a standing medication with a dose change, a winter
* course three years running, a medication whose start is unknown, visits
* with two procedures, documents, vaccinations and three life events. All
* data invented.
*/
import type {
TimelineItem,
TimelineReadinessResponse,
TimelineResponse,
} from "@/lib/day/contract";
export function item(
over: Partial<TimelineItem> & Pick<TimelineItem, "id" | "kind" | "start">,
): TimelineItem {
return {
end: null,
open: false,
precision: "DAY",
startKnown: true,
label: over.id,
sub: null,
href: null,
...over,
};
}
export const TODAY = "2026-10-07";
export function fullTimeline(): TimelineResponse {
return {
zoom: "all",
range: { from: "2019-01-01", to: "2026-12-31", dataFrom: "2019-01-01" },
lanes: [
{
key: "life",
items: [
item({
id: "le-1",
kind: "lifeEvent",
start: "2021-05-14",
label: "Geburt Tochter",
}),
item({
id: "le-2",
kind: "lifeEvent",
start: "2023-09-01",
precision: "MONTH",
label: "Umzug",
}),
item({
id: "le-3",
kind: "lifeEvent",
start: "2024-10-01",
label: "Neue Stelle",
}),
],
},
{
key: "illness",
items: [
item({
id: "ill-chronic",
kind: "chronic",
start: "2019-03-10",
open: true,
label: "Bluthochdruck",
sub: "chronisch",
}),
item({
id: "ill-1",
kind: "episode",
start: "2020-09-01",
end: "2020-10-20",
label: "Schulter",
}),
item({
id: "ill-2",
kind: "episode",
start: "2022-03-08",
end: "2022-03-24",
label: "COVID-19",
}),
item({
id: "ill-3",
kind: "episode",
start: "2022-11-02",
end: "2023-02-15",
label: "Bandscheibe L4/L5",
}),
item({
id: "ill-4",
kind: "episode",
start: "2024-08-10",
end: "2024-08-16",
label: "Magen-Darm",
}),
item({
id: "ill-5",
kind: "episode",
start: "2025-12-31",
end: "2026-01-08",
label: "Erkältung",
}),
],
},
{
key: "allergies",
items: [
item({
id: "al-1",
kind: "allergy",
start: "2018-01-01",
open: true,
label: "Gräserpollen",
}),
item({
id: "al-2",
kind: "allergy",
start: "2020-07-15",
open: true,
label: "Penicillin",
}),
],
},
{
key: "medications",
items: [
item({
id: "med-1",
kind: "medication",
start: "2019-04-02",
open: true,
label: "Ramipril",
sub: "2,5 mg",
}),
item({
id: "dose-1",
kind: "doseChange",
start: "2020-08-12",
label: "Ramipril",
sub: "5 mg",
}),
item({
id: "med-2",
kind: "medication",
start: "2022-11-03",
end: "2022-12-10",
label: "Ibuprofen",
}),
item({
id: "course-1",
kind: "course",
start: "2023-11-01",
end: "2024-03-31",
label: "Vitamin D (Winter)",
}),
item({
id: "course-2",
kind: "course",
start: "2024-11-01",
end: "2025-03-31",
label: "Vitamin D (Winter)",
}),
item({
id: "course-3",
kind: "course",
start: "2025-11-01",
end: "2026-03-31",
label: "Vitamin D (Winter)",
}),
item({
id: "pause-1",
kind: "pause",
start: "2021-06-01",
end: "2021-06-20",
label: "Pause",
}),
],
},
{
key: "vaccinations",
items: [
"2020-06-10",
"2021-05-20",
"2021-07-01",
"2022-10-15",
"2024-10-18",
"2025-10-10",
].map((d, i) =>
item({
id: `vac-${i}`,
kind: "vaccination",
start: d,
label: "Impfung",
}),
),
},
{
key: "visits",
items: [
item({
id: "v-1",
kind: "visit",
start: "2019-03-10",
label: "Hausarztpraxis",
}),
item({
id: "v-2",
kind: "procedure",
start: "2022-11-08",
label: "MRT Lendenwirbelsäule",
}),
item({
id: "v-3",
kind: "procedure",
start: "2025-03-12",
label: "Darmspiegelung",
}),
item({
id: "v-4",
kind: "visit",
start: "2026-01-03",
label: "Hausarztpraxis",
}),
],
},
{ key: "labs", items: [] },
{
key: "documents",
items: ["2019-03-12", "2022-11-09", "2026-01-03"].map((d, i) =>
item({ id: `doc-${i}`, kind: "document", start: d, label: "Befund" }),
),
},
],
standing: [],
series: [
{
key: "BLOOD_PRESSURE_SYS",
unit: "mmHg",
granularity: "month",
points: [
{ t: "2025-10-01", mean: 127 },
{ t: "2025-11-01", mean: 128 },
{ t: "2025-12-01", mean: 130 },
{ t: "2026-01-01", mean: 129 },
// Nothing for February to June.
{ t: "2026-07-01", mean: 131 },
],
},
{
key: "BLOOD_PRESSURE_DIA",
unit: "mmHg",
granularity: "month",
points: [{ t: "2026-01-01", mean: 82 }],
},
{
key: "WEIGHT",
unit: "kg",
granularity: "month",
points: [{ t: "2026-01-01", mean: 82.6 }],
},
],
notable: [{ date: "2026-01-04", kind: "extremeHigh" }],
};
}
export function readiness(
over: Partial<TimelineReadinessResponse> = {},
): TimelineReadinessResponse {
return {
verdict: "carries",
since: "2019-03-01",
lanes: [
{
key: "values",
status: "carries",
count: 3,
detail: { key: "values", params: { count: 3, since: "2019-03-01" } },
gaps: [],
},
{
key: "life",
status: "empty",
count: 0,
detail: { key: "emptyLife", params: {} },
gaps: [
{ key: "lifeEventsEmpty", count: 0, href: "/timeline?add=lifeEvent" },
],
},
{
key: "illness",
status: "carries",
count: 6,
detail: { key: "illness", params: { count: 6, chronic: 1 } },
gaps: [],
},
{
key: "medications",
status: "thin",
count: 5,
detail: { key: "medications", params: { count: 5, missingStart: 3 } },
gaps: [
{
key: "medicationsWithoutStart",
count: 3,
href: "/medications/med-1?edit=1",
},
],
},
{
key: "vaccinations",
status: "empty",
count: 0,
detail: { key: "empty", params: {} },
gaps: [{ key: "vaccinationsEmpty", count: 0, href: "/vaccinations" }],
},
{
key: "visits",
status: "carries",
count: 11,
detail: { key: "visits", params: { count: 11, procedures: 2 } },
gaps: [],
},
],
...over,
};
}
@@ -0,0 +1,421 @@
/**
* v1.42 (#613) — the timeline's geometry: window, scale, grid, rows, labels
* and value lines. The renderer paints exactly this, so the promises the
* chart makes (no label on top of another, nothing past the card edge, an
* unknown start says so) are pinned here.
*/
import { describe, expect, it } from "vitest";
import {
createScale,
dateAtPointer,
estimateTextWidth,
fitText,
gridTicks,
itemLabel,
itemsInMonth,
layoutLane,
layoutSeries,
layoutTimeline,
stepSelection,
todayLabelFits,
windowFor,
wrapToWidth,
type LaneLayout,
type TimelineLayout,
} from "../timeline-geometry";
import { dayNumber } from "../timeline-dates";
import { TODAY, fullTimeline, item } from "./timeline-fixture";
const FMT = {
year: (k: string) => k.slice(0, 4),
monthShort: (k: string) => k.slice(5, 7),
monthYear: (k: string) => `Monat ${k.slice(0, 7)}`,
};
function layoutAt(width: number): TimelineLayout {
const tl = fullTimeline();
return layoutTimeline({
width,
window: windowFor("all", TODAY, null, tl.range),
lanes: tl.lanes,
series: tl.series,
startMissing: "Startdatum fehlt",
today: TODAY,
});
}
/** Every label's box, by the same estimate the layout uses. */
function boxes(lane: LaneLayout) {
return lane.labels.map((l) => ({
...l,
a: l.x,
b: l.x + estimateTextWidth(l.text),
}));
}
describe("text fitting", () => {
it("cuts a name to its column with an ellipsis", () => {
expect(fitText("Arzt und Eingriffe", 200, 13)).toBe("Arzt und Eingriffe");
const cut = fitText("Arzt und Eingriffe", 60, 13);
expect(cut.endsWith("…")).toBe(true);
expect(estimateTextWidth(cut, 13)).toBeLessThanOrEqual(60);
});
it("wraps a note onto lines that fit, or drops it when a word cannot", () => {
expect(wrapToWidth("Noch keine Daten", 200)).toEqual(["Noch keine Daten"]);
expect(wrapToWidth("Noch keine Daten", 70)).toEqual([
"Noch keine",
"Daten",
]);
expect(wrapToWidth("Noch keine Daten", 20)).toEqual([]);
});
});
describe("windowFor", () => {
it("follows the server range at `all`", () => {
expect(
windowFor("all", TODAY, null, { from: "2019-01-01", to: "2026-12-31" }),
).toEqual({ from: "2019-01-01", to: "2026-12-31" });
});
it("shows twelve whole months that never run past this month", () => {
expect(windowFor("year", TODAY, null)).toEqual({
from: "2025-11-01",
to: "2026-10-31",
});
// An older selection stays in view, with months on both sides.
expect(windowFor("year", TODAY, "2026-01-03")).toEqual({
from: "2025-07-01",
to: "2026-06-30",
});
});
it("shows three months around the selection at `quarter`", () => {
expect(windowFor("quarter", TODAY, "2026-01-03")).toEqual({
from: "2025-12-01",
to: "2026-02-28",
});
expect(windowFor("quarter", TODAY, null)).toEqual({
from: "2026-08-01",
to: "2026-10-31",
});
});
it("ignores a selection in the future", () => {
expect(windowFor("quarter", TODAY, "2027-05-01")).toEqual(
windowFor("quarter", TODAY, null),
);
});
});
describe("createScale", () => {
const scale = createScale({ from: "2026-01-01", to: "2026-12-31" }, 100, 465);
it("maps the window onto the drawing width, one day per step", () => {
expect(scale.x("2026-01-01")).toBe(100);
expect(scale.x(dayNumber("2026-12-31") + 1)).toBe(465);
expect(scale.x("2026-01-02") - scale.x("2026-01-01")).toBeCloseTo(1, 6);
});
it("reads a day back from x, clamped into the window", () => {
expect(scale.dayAt(scale.xMid("2026-03-15"))).toBe("2026-03-15");
expect(scale.dayAt(0)).toBe("2026-01-01");
expect(scale.dayAt(10_000)).toBe("2026-12-31");
});
});
describe("gridTicks", () => {
it("labels years at `all` and drops labels that would touch", () => {
const window = { from: "2019-01-01", to: "2026-12-31" };
const wide = gridTicks(window, "all", createScale(window, 164, 1100), FMT);
expect(wide.filter((t) => t.label).map((t) => t.label)).toEqual([
"2019",
"2020",
"2021",
"2022",
"2023",
"2024",
"2025",
"2026",
]);
const narrow = gridTicks(window, "all", createScale(window, 140, 330), FMT);
const labelled = narrow.filter((t) => t.label);
expect(labelled.length).toBeLessThan(8);
for (let i = 1; i < labelled.length; i++) {
const prevEnd =
labelled[i - 1].x + 6 + estimateTextWidth(labelled[i - 1].label!, 12);
expect(labelled[i].x + 6).toBeGreaterThanOrEqual(prevEnd);
}
});
it("lets the axis labels win over the Today label", () => {
const window = { from: "2019-01-01", to: "2026-12-31" };
const scale = createScale(window, 164, 1100);
const ticks = gridTicks(window, "all", scale, FMT);
// Early October: clear of the 2026 label, room for "Heute".
expect(todayLabelFits(ticks, scale.xMid("2026-10-07"), 30, 164)).toBe(true);
// Mid January: right on top of the 2026 label.
expect(todayLabelFits(ticks, scale.xMid("2026-01-20"), 30, 164)).toBe(
false,
);
});
it("draws months at `year` and weekly lines at `quarter`", () => {
const year = { from: "2025-11-01", to: "2026-10-31" };
expect(
gridTicks(year, "year", createScale(year, 164, 1200), FMT),
).toHaveLength(12);
const quarter = { from: "2025-12-01", to: "2026-02-28" };
const ticks = gridTicks(
quarter,
"quarter",
createScale(quarter, 164, 1200),
FMT,
);
expect(ticks.filter((t) => t.major)).toHaveLength(3);
expect(ticks.filter((t) => !t.major).length).toBeGreaterThanOrEqual(11);
});
});
describe("layoutLane", () => {
const window = { from: "2019-01-01", to: "2026-12-31" };
const scale = createScale(window, 164, 1200);
const opts = { startMissing: "Startdatum fehlt", today: TODAY };
it("puts overlapping periods on separate rows and lets later ones reuse a free row", () => {
const lane = fullTimeline().lanes.find((l) => l.key === "illness")!;
const layout = layoutLane({ lane, top: 0 }, window, scale, opts);
const chronic = layout.spans.find((s) => s.item.id === "ill-chronic")!;
const episodes = layout.spans.filter((s) => s.item.kind === "episode");
expect(chronic.row).toBe(0);
expect(new Set(episodes.map((s) => s.row))).toEqual(new Set([1]));
expect(layout.rows).toBe(2);
});
it("lays a dose change and a pause over the medication they belong to", () => {
const lane = fullTimeline().lanes.find((l) => l.key === "medications")!;
const layout = layoutLane({ lane, top: 0 }, window, scale, opts);
const host = layout.spans.find((s) => s.item.id === "med-1")!;
expect(layout.points.find((p) => p.item.id === "dose-1")?.row).toBe(
host.row,
);
const pause = layout.spans.find((s) => s.item.id === "pause-1")!;
expect(pause.pause).toBe(true);
expect(pause.row).toBe(host.row);
});
it("starts an open period at its start and runs it to today", () => {
const lane = fullTimeline().lanes.find((l) => l.key === "allergies")!;
const layout = layoutLane({ lane, top: 0 }, window, scale, opts);
const grass = layout.spans.find((s) => s.item.id === "al-1")!;
expect(grass.clippedLeft).toBe(true);
expect(grass.xStart).toBe(164);
expect(grass.xEnd).toBeCloseTo(scale.x(dayNumber(TODAY) + 1), 6);
});
it("names an unknown start in the label", () => {
const unknown = item({
id: "m",
kind: "medication",
start: "2024-05-01",
open: true,
startKnown: false,
label: "Ramipril",
sub: "5 mg",
});
expect(itemLabel(unknown, "Startdatum fehlt")).toBe(
"Ramipril · 5 mg · Startdatum fehlt",
);
const layout = layoutLane(
{ lane: { key: "medications", items: [unknown] }, top: 0 },
window,
scale,
opts,
);
expect(layout.labels[0].text).toContain("Startdatum fehlt");
});
it("names life events beside their diamonds, clear of the glyph", () => {
const lane = fullTimeline().lanes.find((l) => l.key === "life")!;
const layout = layoutLane({ lane, top: 0 }, window, scale, opts);
expect(layout.labels.map((l) => l.text)).toEqual([
"Geburt Tochter",
"Umzug",
"Neue Stelle",
]);
for (const label of layout.labels) {
const point = layout.points.find((p) => p.item.id === label.itemId)!;
expect(label.x).toBeGreaterThan(point.x + 7);
expect(label.strong).toBe(true);
}
});
it("puts procedures on their own row below the plain visits", () => {
const lane = fullTimeline().lanes.find((l) => l.key === "visits")!;
const layout = layoutLane({ lane, top: 0 }, window, scale, opts);
expect(
layout.points
.filter((p) => p.item.kind === "visit")
.every((p) => p.row === 0),
).toBe(true);
expect(
layout.points
.filter((p) => p.item.kind === "procedure")
.every((p) => p.row === 1),
).toBe(true);
expect(layout.labels.map((l) => l.text)).toContain("Darmspiegelung");
});
});
describe("label collision avoidance", () => {
// 1440 full, 1440 with the docked day panel (~700), a laptop and a
// narrow tablet column.
for (const width of [1180, 940, 700, 520]) {
it(`never overlaps two labels or runs past the edge at ${width} px`, () => {
const layout = layoutAt(width);
for (const lane of layout.lanes) {
const list = boxes(lane);
for (const box of list) {
expect(box.a).toBeGreaterThanOrEqual(layout.scale.x0);
expect(box.b).toBeLessThanOrEqual(layout.scale.x1);
}
for (let i = 0; i < list.length; i++) {
for (let j = i + 1; j < list.length; j++) {
const a = list[i];
const b = list[j];
if (a.y !== b.y) continue;
const overlap = a.a < b.b && b.a < a.b;
expect(overlap, `${a.text} / ${b.text}`).toBe(false);
}
}
}
});
}
it("never puts a label over a bar of its own row", () => {
const layout = layoutAt(940);
for (const lane of layout.lanes) {
for (const label of lane.labels) {
// Labels on a bar's line sit at y + 4; above-labels at y - 7.
const onLine = lane.spans.filter((s) => s.y + 4 === label.y);
for (const s of onLine) {
const b = label.x + estimateTextWidth(label.text);
const overlap = label.x < s.xEnd && s.xStart < b;
expect(overlap, `${label.text} over ${s.item.label}`).toBe(false);
}
}
}
});
it("drops labels rather than squeezing them when the panel narrows the card", () => {
const wide = layoutAt(1180).lanes.reduce((n, l) => n + l.labels.length, 0);
const narrow = layoutAt(520).lanes.reduce((n, l) => n + l.labels.length, 0);
expect(narrow).toBeLessThan(wide);
expect(narrow).toBeGreaterThan(0);
});
});
describe("layoutTimeline", () => {
it("leaves an empty lane out entirely", () => {
const layout = layoutAt(1180);
expect(layout.lanes.map((l) => l.key)).not.toContain("labs");
expect(layout.lanes.map((l) => l.key)).toEqual([
"life",
"illness",
"allergies",
"medications",
"vaccinations",
"visits",
"documents",
]);
});
it("stacks lanes without gaps and puts the value lines below", () => {
const layout = layoutAt(1180);
for (let i = 1; i < layout.lanes.length; i++) {
expect(layout.lanes[i].top).toBe(
layout.lanes[i - 1].top + layout.lanes[i - 1].height,
);
}
const last = layout.lanes.at(-1)!;
expect(layout.seriesTop).toBeGreaterThan(last.top + last.height);
expect(layout.series).toHaveLength(3);
});
});
describe("layoutSeries", () => {
it("breaks the line across missing months instead of bridging them", () => {
const window = { from: "2025-10-01", to: "2026-10-31" };
const scale = createScale(window, 164, 1200);
const [bp] = layoutSeries(
fullTimeline().series.slice(0, 1),
0,
window,
scale,
);
expect(bp.path.match(/M/g)).toHaveLength(2);
expect(bp.latest).toBe(131);
});
it("keeps an empty series as a row without a line", () => {
const window = { from: "2019-01-01", to: "2019-12-31" };
const scale = createScale(window, 164, 1200);
const [bp] = layoutSeries(
fullTimeline().series.slice(0, 1),
0,
window,
scale,
);
expect(bp.path).toBe("");
expect(bp.latest).toBeNull();
});
});
describe("interaction", () => {
it("snaps a click near a mark to the mark's date", () => {
const layout = layoutAt(1180);
const visits = layout.lanes.find((l) => l.key === "visits")!;
const visit = visits.points.find((p) => p.item.id === "v-4")!;
expect(dateAtPointer(layout, visit.x + 3, visit.y + 2)).toBe("2026-01-03");
});
it("falls back to the day under the pointer", () => {
const layout = layoutAt(1180);
const x = layout.scale.xMid("2023-06-15");
expect(dateAtPointer(layout, x, layout.height - 2)).toBe("2023-06-15");
});
it("steps a day, a month or a year with the zoom, never into the future", () => {
expect(stepSelection("2026-01-03", 1, "quarter", TODAY, "2019-01-01")).toBe(
"2026-01-04",
);
expect(stepSelection("2026-01-03", -1, "year", TODAY, "2019-01-01")).toBe(
"2025-12-03",
);
expect(stepSelection("2026-01-03", -1, "all", TODAY, "2019-01-01")).toBe(
"2025-01-03",
);
expect(stepSelection("2026-10-01", 1, "year", TODAY, "2019-01-01")).toBe(
TODAY,
);
expect(stepSelection("2019-02-01", -1, "all", TODAY, "2019-01-01")).toBe(
"2019-01-01",
);
});
it("names what happens, starts, ends or runs through the month, not the backdrop", () => {
const entries = itemsInMonth(fullTimeline().lanes, "2026-01-03", TODAY);
const ids = entries.map((e) => e.item.id);
expect(ids).toEqual(["ill-5", "course-3", "v-4"]);
// The winter course neither starts nor ends in January: it runs through.
expect(entries.find((e) => e.item.id === "course-3")?.through).toBe(true);
expect(entries.find((e) => e.item.id === "ill-5")?.through).toBe(false);
// Open since 2019 and 2018: the backdrop of every month, left out.
expect(ids).not.toContain("ill-chronic");
expect(ids).not.toContain("al-1");
// An open period that starts in the month is named.
const march2019 = itemsInMonth(fullTimeline().lanes, "2019-03-15", TODAY);
expect(march2019.map((e) => e.item.id)).toContain("ill-chronic");
});
});
@@ -0,0 +1,25 @@
/**
* v1.42 (#613) — the timeline's value selector names each option's owning
* module itself, to keep the signal registry out of its chunk. It must give
* the same answer the registry gives, or a switched-off module's values
* would still be offered.
*/
import { describe, expect, it } from "vitest";
import type { MeasurementType } from "@/generated/prisma/client";
import { moduleForMeasurementType } from "@/lib/modules/measurement-scope";
import { VALUE_OPTION_MODULE } from "../timeline-view";
describe("value options", () => {
for (const [key, owner] of Object.entries(VALUE_OPTION_MODULE)) {
if (key === "MOOD") continue;
it(`${key} is owned by ${owner ?? "no module"}`, () => {
expect(moduleForMeasurementType(key as MeasurementType)).toBe(owner);
});
}
it("ties mood to the mood module", () => {
expect(VALUE_OPTION_MODULE.MOOD).toBe("mood");
});
});