feat(medications): show the GLP-1 dose-strength curve instead of the empty therapy course

The GLP-1 detail disclosure carried a titration block that only ever
rendered the standard EMA *reference* ladder — a static schedule with no
values from the user's own therapy, blank whenever the medication's brand
fell outside the catalog. Replace it with a dose-strength curve over the
user's recorded dose-change history.

The MedicationDoseChange stream is the history of record for titration
(2.5 -> 5 -> 7.5 mg escalation steps). The new curve plots that series as
a step line, carrying the latest dose forward to now so the current
strength anchors the right edge. With a single dose change there is no
escalation to draw, so the surface states the current dose plainly with a
"no titration history yet" caption rather than a flat single-point chart;
with none it shows the empty state. The curve plots only logged facts, so
unlike the estimated-PK drug-level chart it needs no Research-Mode gate.

Drop the now-unused reference-ladder section, its read route, the ladder
helpers, the titration query key, and the orphaned i18n block.
This commit is contained in:
Marc-André Bombeck committed 2026-06-01 22:59:14 +02:00
1 parent c1f30466e7
commit 3f9fd9095f
18 files changed
+528 -1361

No files matched your search

@@ -1,245 +0,0 @@
"use client";
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2, ExternalLink } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
/**
* v1.4.25 W19f — GLP-1 titration-ladder section.
*
* Sits at the bottom of the medication detail page below the W19e
* SchedulingSection (v1.4.28 retired the IntakeHistoryList block).
* Same chrome as the W19d / W19e sections so the panels read as one
* visual group — chrome is now composed via the shared
* `<MedicationDetailSection>` wrapper.
*
* Layout:
* - Header: drug INN + "Standard ladder (EMA reference)"
* - Vertical step list (mobile) — same nodes laid horizontally
* from `sm` upwards. Each step shows dose, typical-weeks badge,
* and a status dot (current / past / upcoming).
* - Current-step ring with "You are here" caption.
* - Next-step caption + observational dwell hint when the EMA
* dwell-time has elapsed. Copy is strictly observational; the
* ladder is a *reference*, never a prescription (MDR boundary).
* - Disclaimer + EMA-source link.
*
* v1.4.25 W21 Fix-N — dropped the hand-rolled `templateFill` helper;
* the i18n `t()` function already accepts the `params` bag with
* `{key}` placeholder substitution. One source of truth for the
* template-fill semantics.
*
* Data comes from `/api/medications/[id]/titration`; that route owns
* the prisma queries and delegates math to the pure ladder helpers.
*/
interface TitrationStep {
stepIndex: number;
doseMg: number;
typicalWeeks: number;
}
interface TitrationResponse {
drugId: string;
drugInn: string;
ladder: TitrationStep[];
currentStep: TitrationStep | null;
currentStepIndex: number | null;
weeksOnCurrentStep: number;
nextStep: TitrationStep | null;
escalationDue: boolean;
sourceEMA: string;
}
interface TitrationSectionProps {
medicationId: string;
}
export function TitrationSection({ medicationId }: TitrationSectionProps) {
const { t } = useTranslations();
const { data, isLoading, error } = useQuery({
queryKey: queryKeys.medicationTitration(medicationId),
queryFn: async (): Promise<TitrationResponse> => {
const res = await fetch(`/api/medications/${medicationId}/titration`);
if (!res.ok) {
throw new Error(`Failed to load titration: ${res.status}`);
}
const json = await res.json();
return json.data as TitrationResponse;
},
});
const hasLadder = !!data && data.ladder.length > 0;
const currentIdx = data?.currentStepIndex ?? null;
// Compose the optional dwell hint AND the next-step caption. The
// dwell hint is strictly observational — no "you should step up";
// the boolean only gates *display*, never *action*.
const dwellHint = useMemo(() => {
if (!data || data.currentStep === null) return null;
if (data.weeksOnCurrentStep <= 0) return null;
if (data.escalationDue) {
return t("medications.titration.escalationDueHint", {
weeks: data.weeksOnCurrentStep,
typical: data.currentStep.typicalWeeks,
});
}
return t("medications.titration.currentStepDwell", {
weeks: data.weeksOnCurrentStep,
});
}, [data, t]);
const nextStepCaption = useMemo(() => {
if (!data) return null;
if (!data.nextStep) return null;
return t("medications.titration.nextStepCaption", {
dose: data.nextStep.doseMg,
weeks: data.currentStep?.typicalWeeks ?? data.nextStep.typicalWeeks,
});
}, [data, t]);
const headerExtras = data ? (
<span
className="text-muted-foreground text-xs uppercase tracking-wide"
data-slot="titration-drug-inn"
>
{data.drugInn}
</span>
) : null;
return (
<MedicationDetailSection
titleId="titration-heading"
title={t("medications.titration.section")}
headerExtras={headerExtras}
dataSlot="titration-section"
>
{isLoading && (
<div className="text-muted-foreground flex items-center gap-2">
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
<span>{t("medications.titration.loading")}</span>
</div>
)}
{!!error && !isLoading && (
<p className="text-destructive">
{t("medications.titration.loadFailed")}
</p>
)}
{data && !isLoading && (
<div className="space-y-3">
<p className="text-muted-foreground text-xs uppercase tracking-wide">
{t("medications.titration.drugLadderHeader")}
</p>
{hasLadder ? (
<ol
// v1.4.27 MB7 / CF-48 — keep the vertical (`flex-col`)
// layout until `md:` instead of breaking to horizontal
// at `sm:`. On Pixel 5 (375 px) the horizontal ladder
// had 4-5 visible steps but each step's "Standard 0.5
// mg" + "typical 4 weeks" label combo wrapped to 3
// lines per step, which read as a denser block than
// the vertical layout below. From `md:` upwards the
// wider container can absorb the horizontal stride.
className="flex flex-col gap-2 md:flex-row md:flex-wrap md:items-stretch"
aria-label={t("medications.titration.drugLadderHeader")}
>
{data.ladder.map((step) => {
const isCurrent = currentIdx === step.stepIndex;
const isPast =
currentIdx !== null && step.stepIndex < currentIdx;
return (
<li
key={step.stepIndex}
className={[
"border-border/70 flex flex-1 flex-col rounded-md border px-2.5 py-2 md:min-w-[7rem]",
isCurrent
? "border-primary ring-primary/40 ring-2"
: "",
].join(" ")}
aria-current={isCurrent ? "step" : undefined}
data-slot="titration-step"
data-step-index={step.stepIndex}
data-step-state={
isCurrent ? "current" : isPast ? "past" : "upcoming"
}
>
<span className="text-muted-foreground text-xs uppercase tracking-wide">
{t("medications.titration.stepLabel", {
n: step.stepIndex + 1,
})}
</span>
<span className="text-foreground text-sm font-medium">
{step.doseMg} {t("medications.titration.doseUnitMg")}
</span>
<span className="text-muted-foreground text-xs">
{t("medications.titration.typicalWeeksOnStep", {
weeks: step.typicalWeeks,
})}
</span>
{isCurrent && (
<span className="text-primary mt-1 text-xs font-medium uppercase tracking-wide">
{t("medications.titration.youAreHere")}
</span>
)}
</li>
);
})}
</ol>
) : (
<p className="text-muted-foreground">
{t("medications.titration.emptyState")}
</p>
)}
{data.currentStep === null && hasLadder && (
<p className="text-muted-foreground">
{t("medications.titration.nonStandardDose")}
</p>
)}
{dwellHint && (
<p
className="text-muted-foreground"
data-slot="titration-dwell-hint"
>
{dwellHint}
</p>
)}
{nextStepCaption && (
<p className="text-muted-foreground">{nextStepCaption}</p>
)}
{data.nextStep === null && data.currentStep !== null && (
<p className="text-muted-foreground">
{t("medications.titration.ceilingMessage")}
</p>
)}
<div className="border-border/60 border-t pt-2">
<p className="text-muted-foreground text-xs">
{t("medications.titration.disclaimer")}
</p>
<a
href={data.sourceEMA}
target="_blank"
rel="noopener noreferrer"
className="text-foreground/80 hover:text-foreground mt-1 inline-flex items-center gap-1 text-xs underline-offset-2 hover:underline"
>
{t("medications.titration.emaSourceCta")}
<ExternalLink className="h-2.5 w-2.5" aria-hidden="true" />
</a>
</div>
</div>
)}
</MedicationDetailSection>
);
}
@@ -1,221 +0,0 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { TitrationSection } from "@/components/medications/TitrationSection";
/**
* v1.4.25 W19f — TitrationSection SSR smoke tests.
*
* Same testing convention as `SchedulingSection.test.tsx`:
* `renderToStaticMarkup` + seeded react-query cache. Interactive
* branches (loading spinner, fetch-error) are covered by the API
* route tests + the pure ladder tests; surface tests here pin the
* static-render contract:
*
* 1. Header + drug INN render.
* 2. Each ladder step renders with dose + typical-weeks label.
* 3. The current step has a "You are here" caption.
* 4. The next-step caption renders when a next step exists.
* 5. The ceiling message renders when the user is on the top
* step (no next step).
* 6. The non-standard dose caption renders when current step is
* null but the ladder is non-empty.
* 7. The disclaimer + EMA source link always render with data.
* 8. Empty ladder → empty-state copy renders.
* 9. The escalationDueHint copy is observational, not prescriptive.
* 10. German locale renders.
*/
function makeClient() {
return new QueryClient({
defaultOptions: {
queries: {
retry: false,
staleTime: Number.POSITIVE_INFINITY,
refetchOnMount: false,
},
},
});
}
interface SeedShape {
drugId: string;
drugInn: string;
ladder: Array<{ stepIndex: number; doseMg: number; typicalWeeks: number }>;
currentStep: { stepIndex: number; doseMg: number; typicalWeeks: number } | null;
currentStepIndex: number | null;
weeksOnCurrentStep: number;
nextStep: { stepIndex: number; doseMg: number; typicalWeeks: number } | null;
escalationDue: boolean;
sourceEMA: string;
}
function seed(client: QueryClient, medId: string, payload: SeedShape) {
client.setQueryData(["medications", medId, "titration"], payload);
}
function render(
node: React.ReactNode,
client: QueryClient,
locale: "en" | "de" = "en",
) {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<QueryClientProvider client={client}>{node}</QueryClientProvider>
</I18nProvider>,
);
}
const TIRZEPATIDE_LADDER = [
{ stepIndex: 0, doseMg: 2.5, typicalWeeks: 4 },
{ stepIndex: 1, doseMg: 5, typicalWeeks: 4 },
{ stepIndex: 2, doseMg: 7.5, typicalWeeks: 4 },
{ stepIndex: 3, doseMg: 10, typicalWeeks: 4 },
{ stepIndex: 4, doseMg: 12.5, typicalWeeks: 4 },
{ stepIndex: 5, doseMg: 15, typicalWeeks: 4 },
];
const SEED_ON_STEP_5MG: SeedShape = {
drugId: "tirzepatide",
drugInn: "Tirzepatide",
ladder: TIRZEPATIDE_LADDER,
currentStep: TIRZEPATIDE_LADDER[1],
currentStepIndex: 1,
weeksOnCurrentStep: 2,
nextStep: TIRZEPATIDE_LADDER[2],
escalationDue: false,
sourceEMA:
"https://www.ema.europa.eu/en/documents/product-information/mounjaro-epar-product-information_en.pdf",
};
beforeEach(() => {
vi.clearAllMocks();
});
describe("<TitrationSection> — surface render", () => {
it("renders the section heading and drug INN", () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain("Titration ladder");
expect(html).toContain("Tirzepatide");
expect(html).toContain("Standard ladder (EMA reference)");
});
it("renders every step on the ladder", () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(<TitrationSection medicationId="med-1" />, client);
for (const step of TIRZEPATIDE_LADDER) {
// Each step's dose label appears (e.g. "2.5 mg", "15 mg").
expect(html).toContain(`${step.doseMg} mg`);
}
// Step ladder count = 6 steps; each step renders one card.
const stepCards = html.match(/data-slot="titration-step"/g) ?? [];
expect(stepCards.length).toBe(6);
});
it('renders "You are here" on the current step only', () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain("You are here");
// Only one "you are here" caption rendered, on the matched step.
expect(html.match(/You are here/g)?.length).toBe(1);
});
it("renders the next-step caption when a next step exists", () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain("Next step (typical): 7.5 mg");
});
it("renders the ceiling message at the top of the ladder", () => {
const client = makeClient();
seed(client, "med-1", {
...SEED_ON_STEP_5MG,
currentStep: TIRZEPATIDE_LADDER[5],
currentStepIndex: 5,
nextStep: null,
});
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain("You are at the top of the standard ladder.");
});
it("renders the non-standard dose caption when current step is null", () => {
const client = makeClient();
seed(client, "med-1", {
...SEED_ON_STEP_5MG,
currentStep: null,
currentStepIndex: null,
nextStep: null,
weeksOnCurrentStep: 0,
});
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain(
"Current dose is outside the standard ladder buckets.",
);
});
it("always renders the disclaimer and the EMA-source link", () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain(
"EMA reference values. Talk to your doctor before changing doses.",
);
expect(html).toContain("EMA source");
expect(html).toContain("mounjaro-epar-product-information");
});
it("renders the empty-state copy when the ladder is empty", () => {
const client = makeClient();
seed(client, "med-1", {
...SEED_ON_STEP_5MG,
ladder: [],
currentStep: null,
currentStepIndex: null,
nextStep: null,
});
const html = render(<TitrationSection medicationId="med-1" />, client);
expect(html).toContain(
"No dose history yet. Log a dose to see where you are on the ladder.",
);
});
it("renders the escalation-due hint as an observation, not a prescription", () => {
const client = makeClient();
seed(client, "med-1", {
...SEED_ON_STEP_5MG,
weeksOnCurrentStep: 6,
escalationDue: true,
});
const html = render(<TitrationSection medicationId="med-1" />, client);
// The copy must NOT prescribe an action ("you should step up").
expect(html).not.toMatch(/should step up/i);
expect(html).not.toMatch(/must step up/i);
expect(html).not.toMatch(/recommend.*step up/i);
// The observational template must be rendered.
expect(html).toContain("the ladder typically steps up around");
// The escaped apostrophe is the SSR render of the curly-apostrophe-free
// template; we assert on the unencoded plain segment instead of the
// contraction itself to stay robust to the renderer's HTML entity choice.
expect(html).toContain("been on this step for 6 weeks");
});
it("renders the section heading in German", () => {
const client = makeClient();
seed(client, "med-1", SEED_ON_STEP_5MG);
const html = render(
<TitrationSection medicationId="med-1" />,
client,
"de",
);
expect(html).toContain("Titrationsstufen");
expect(html).toContain("Standard-Schema (EMA-Referenz)");
expect(html).toContain("Hier stehst du");
});
});
@@ -0,0 +1,187 @@
/**
* v1.8.6 W4c — dose-strength (titration) curve tests.
*
* Pins the three honest data states and the pure point-builder:
* - 0 dose-change rows → empty state, current-dose absent.
* - exactly 1 row → empty state, current dose surfaced (no flat
* single-point chart).
* - 2+ rows → the step-curve SVG body renders.
*
* Recharts in `renderToStaticMarkup` paints the static frame only, so we
* assert on the `data-slot` seams rather than measured geometry — the
* same approach the sibling DrugLevelChart test uses.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
const queryResults: Record<string, unknown> = {};
function setQueryResult(keyJoined: string, data: unknown) {
queryResults[keyJoined] = data;
}
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
const key = (queryKey as Array<string | number>).join("/");
return { data: queryResults[key], isLoading: false };
},
}));
import {
DoseStrengthCurve,
buildCurvePoints,
} from "../dose-strength-curve";
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
const KEY = "medications/med-1/glp1-details";
const ASOF = new Date("2026-06-01T12:00:00Z");
beforeEach(() => {
for (const k of Object.keys(queryResults)) delete queryResults[k];
});
describe("buildCurvePoints", () => {
it("returns an empty list for no dose changes", () => {
expect(buildCurvePoints([], ASOF)).toEqual([]);
});
it("returns the single row unchanged (no carry-forward) for one change", () => {
const pts = buildCurvePoints(
[
{
id: "a",
effectiveFrom: "2026-04-01T00:00:00Z",
doseValue: 2.5,
doseUnit: "mg",
},
],
ASOF,
);
expect(pts).toHaveLength(1);
expect(pts[0].dose).toBe(2.5);
});
it("sorts by effectiveFrom and carries the latest dose forward to asOf", () => {
const pts = buildCurvePoints(
[
{
id: "b",
effectiveFrom: "2026-05-01T00:00:00Z",
doseValue: 5,
doseUnit: "mg",
},
{
id: "a",
effectiveFrom: "2026-04-01T00:00:00Z",
doseValue: 2.5,
doseUnit: "mg",
},
],
ASOF,
);
// two source rows + the carried-forward "now" anchor
expect(pts).toHaveLength(3);
expect(pts.map((p) => p.dose)).toEqual([2.5, 5, 5]);
expect(pts[2].t).toBe(ASOF.getTime());
});
it("drops rows with unparseable dates or non-finite doses", () => {
const pts = buildCurvePoints(
[
{
id: "bad-date",
effectiveFrom: "not-a-date",
doseValue: 5,
doseUnit: "mg",
},
{
id: "ok",
effectiveFrom: "2026-04-01T00:00:00Z",
doseValue: 2.5,
doseUnit: "mg",
},
{
id: "ok-2",
effectiveFrom: "2026-05-01T00:00:00Z",
doseValue: 7.5,
doseUnit: "mg",
},
],
ASOF,
);
expect(pts.map((p) => p.dose)).toEqual([2.5, 7.5, 7.5]);
});
});
describe("<DoseStrengthCurve>", () => {
it("renders the empty state with no current dose for zero rows", () => {
setQueryResult(KEY, { doseChanges: [] });
const html = render(
<DoseStrengthCurve medicationId="med-1" asOf={ASOF} />,
);
expect(html).toContain('data-slot="dose-strength-curve-empty"');
expect(html).toContain("No dose recorded yet.");
expect(html).toContain("No titration history yet.");
expect(html).not.toContain('data-slot="dose-strength-curve-area"');
});
it("surfaces the current dose but no curve for a single dose change", () => {
setQueryResult(KEY, {
doseChanges: [
{
id: "a",
effectiveFrom: "2026-05-01T00:00:00Z",
doseValue: 5,
doseUnit: "mg",
},
],
});
const html = render(
<DoseStrengthCurve medicationId="med-1" asOf={ASOF} />,
);
expect(html).toContain('data-slot="dose-strength-curve-empty"');
expect(html).toContain("Current dose: 5 mg");
expect(html).not.toContain('data-slot="dose-strength-curve-area"');
});
it("renders the step curve for two or more dose changes", () => {
setQueryResult(KEY, {
doseChanges: [
{
id: "a",
effectiveFrom: "2026-04-01T00:00:00Z",
doseValue: 2.5,
doseUnit: "mg",
},
{
id: "b",
effectiveFrom: "2026-05-01T00:00:00Z",
doseValue: 5,
doseUnit: "mg",
},
],
});
const html = render(
<DoseStrengthCurve medicationId="med-1" asOf={ASOF} />,
);
expect(html).toContain('data-slot="dose-strength-curve-area"');
expect(html).toContain('data-slot="dose-strength-curve-caption"');
// Mounted inside the shared section chrome.
expect(html).toContain('aria-labelledby="dose-strength-curve-title"');
expect(html).not.toContain('data-slot="dose-strength-curve-empty"');
});
});
@@ -0,0 +1,284 @@
"use client";
/**
* v1.8.6 W4c — GLP-1 dose-strength (titration) curve.
*
* Replaces the EMA *reference*-ladder block that showed no values when
* the medication's brand fell outside the catalog. This surface plots
* the user's OWN dose-strength history — the `MedicationDoseChange`
* stream (`effectiveFrom` + `doseValue` + `doseUnit`) returned by
* `GET /api/medications/[id]/glp1` — as a step curve over time, so a
* 2.5 → 5 → 7.5 → 10 mg escalation reads at a glance.
*
* Honest data contract:
* - 2+ dose-change rows → step curve, the latest dose carried forward
* to "now" so the current strength stays visible at the right edge.
* - exactly 1 row → no escalation to draw; surface the single current
* dose plainly with a "no titration history yet" caption rather than
* a flat single-point chart.
* - 0 rows → empty state with the same caption. The
* `MedicationDoseChange` table is the history of record; when it is
* empty there is genuinely no time series to plot.
*
* No Research-Mode gate — unlike the estimated-PK `DrugLevelChart`, this
* curve plots only logged facts (the user's recorded dose strengths), so
* it carries no pharmacokinetic estimate and needs no disclaimer gate.
*
* Dracula purple tokens + the shared `<MedicationDetailSection>` chrome
* so the GLP-1 disclosure reads as one visual group with the drug-level
* chart that sits beside it.
*/
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2, TrendingUp } from "lucide-react";
import {
CartesianGrid,
Line,
LineChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import { MedicationDetailSection } from "@/components/medications/medication-detail-section";
const CURVE_COLOR = "var(--dracula-purple)";
interface DoseChange {
id: string;
effectiveFrom: string;
doseValue: number;
doseUnit: string;
note?: string | null;
}
interface Glp1DetailsResponse {
doseChanges: DoseChange[];
}
export interface DoseStrengthCurveProps {
medicationId: string;
/** Override "now" for deterministic snapshot tests. */
asOf?: Date;
}
interface CurvePoint {
t: number;
dose: number;
unit: string;
}
/**
* Build the step-curve points from the dose-change stream. The series is
* sorted by `effectiveFrom`, finite-guarded, and the latest dose is
* carried forward to `asOf` so the current strength anchors the right
* edge. Exported for the unit test.
*/
export function buildCurvePoints(
doseChanges: readonly DoseChange[],
asOf: Date,
): CurvePoint[] {
const sorted = doseChanges
.map((dc) => ({
t: Date.parse(dc.effectiveFrom),
dose: dc.doseValue,
unit: dc.doseUnit,
}))
.filter((p) => Number.isFinite(p.t) && Number.isFinite(p.dose))
.sort((a, b) => a.t - b.t);
if (sorted.length < 2) return sorted;
// Carry the latest dose forward to "now" so the most-recent strength
// reads as a flat segment up to the right edge rather than ending at
// the last change date.
const last = sorted[sorted.length - 1];
const nowMs = asOf.getTime();
if (nowMs > last.t) {
sorted.push({ t: nowMs, dose: last.dose, unit: last.unit });
}
return sorted;
}
export function DoseStrengthCurve({
medicationId,
asOf,
}: DoseStrengthCurveProps) {
const { t } = useTranslations();
const fmt = useFormatters();
const { data: details, isLoading } = useQuery<Glp1DetailsResponse | null>({
queryKey: queryKeys.medicationGlp1Details(medicationId),
queryFn: async () => {
const res = await fetch(`/api/medications/${medicationId}/glp1`);
if (!res.ok) return null;
const json = await res.json();
return json.data as Glp1DetailsResponse;
},
staleTime: 60 * 1000,
});
const now = useMemo(() => asOf ?? new Date(), [asOf]);
const doseChanges = useMemo(
() => details?.doseChanges ?? [],
[details],
);
const points = useMemo(
() => buildCurvePoints(doseChanges, now),
[doseChanges, now],
);
const animationsEnabled = !prefersReducedMotion();
// The latest logged dose — surfaced in the single-row / empty states so
// the user always sees their current strength even without a curve.
const latest = useMemo(() => {
if (doseChanges.length === 0) return null;
const sorted = [...doseChanges].sort(
(a, b) => Date.parse(a.effectiveFrom) - Date.parse(b.effectiveFrom),
);
return sorted[sorted.length - 1];
}, [doseChanges]);
const hasCurve = points.length >= 2;
const chartData = useMemo(
() =>
points.map((p) => ({
t: p.t,
dose: p.dose,
})),
[points],
);
// Four evenly-spaced date ticks across the plotted span so the strip
// reads start → … → now without crowding.
const ticks = useMemo(() => {
if (chartData.length < 2) return [];
const first = chartData[0].t;
const last = chartData[chartData.length - 1].t;
const span = last - first;
if (span <= 0) return [first];
return [0, 0.33, 0.66, 1].map((f) => Math.round(first + span * f));
}, [chartData]);
const unit = latest?.doseUnit ?? "mg";
const body = isLoading ? (
<div
className="flex h-[200px] min-h-[200px] items-center justify-center"
data-slot="dose-strength-curve-loading"
>
<Loader2 className="text-primary h-6 w-6 animate-spin motion-reduce:animate-none" />
</div>
) : !hasCurve ? (
<div
className="text-muted-foreground bg-muted/40 flex flex-col items-start gap-2 rounded-md p-4 text-sm"
data-slot="dose-strength-curve-empty"
>
<div className="flex items-center gap-2">
<TrendingUp className="h-4 w-4 shrink-0" aria-hidden="true" />
{latest ? (
<p>
{t("medications.doseStrength.currentDose", {
dose: fmt.number(latest.doseValue),
unit: latest.doseUnit,
})}
</p>
) : (
<p>{t("medications.doseStrength.noCurrentDose")}</p>
)}
</div>
<p className="text-xs italic">{t("medications.doseStrength.empty")}</p>
</div>
) : (
<div
className="touch-pan-y"
style={{ height: "200px" }}
data-slot="dose-strength-curve-area"
>
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={chartData}
margin={{ top: 10, right: 14, bottom: 16, left: 4 }}
>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--border)"
opacity={0.5}
/>
<XAxis
dataKey="t"
type="number"
scale="time"
domain={["dataMin", "dataMax"]}
ticks={ticks}
tickFormatter={(v) => fmt.dateShort(new Date(v as number))}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
/>
<YAxis
domain={[0, "auto"]}
width={34}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
tickFormatter={(v) => fmt.number(v as number)}
/>
<Tooltip
cursor={{
stroke: "var(--muted-foreground)",
strokeOpacity: 0.3,
strokeDasharray: "3 3",
}}
labelFormatter={(v) => fmt.dateShort(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",
}}
/>
<Line
type="stepAfter"
dataKey="dose"
stroke={CURVE_COLOR}
strokeWidth={2}
dot={{ r: 3, fill: CURVE_COLOR, strokeWidth: 0 }}
activeDot={{ r: 4 }}
isAnimationActive={animationsEnabled}
animationDuration={animationsEnabled ? 600 : 0}
animationEasing="ease-out"
/>
</LineChart>
</ResponsiveContainer>
</div>
);
return (
<MedicationDetailSection
titleId="dose-strength-curve-title"
title={t("medications.doseStrength.title")}
dataSlot="dose-strength-curve"
>
{hasCurve && (
<p
className="text-muted-foreground mb-2 text-xs"
data-slot="dose-strength-curve-caption"
>
{t("medications.doseStrength.axisLabel", { unit })}
</p>
)}
{body}
</MedicationDetailSection>
);
}