chore(release): v1.4.25

Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites).

See CHANGELOG.md for the full per-section delta.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-14 23:49:32 +02:00
1 parent de0689e419
commit 17b8d8d2c2
528 files changed
+104033 -6524

No files matched your search

@@ -0,0 +1,75 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { ConsistencyStrip } from "../consistency-strip";
/**
* v1.4.25 W3e — `<ConsistencyStrip>` replaces the v1.4.22 per-card
* sparkline. Seven dots, one per Berlin-tz day; band-coloured when the
* day's mean reading was in range, hollow when no readings, and a
* trailing caption that flips between "in range" and "logged" depending
* on the cadence.
*/
function render(
props: Parameters<typeof ConsistencyStrip>[0],
locale: "en" | "de" = "en",
) {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<ConsistencyStrip {...props} />
</I18nProvider>,
);
}
describe("<ConsistencyStrip>", () => {
it("renders 7 dots with their band class and the caption", () => {
const html = render({
days: ["in", "in", "near", "in", "out", "in", "in"],
daysInRange: 5,
daysLogged: 7,
});
expect(html).toContain('data-slot="consistency-strip"');
// Seven li elements, one per day.
const liMatches = html.match(/<li/g) ?? [];
expect(liMatches.length).toBe(7);
// Cap shows "5 of 7 in range".
expect(html).toContain("5 of 7 in range");
});
it("flips the cap to a logged-count when ≤ 2 days were logged", () => {
const html = render({
days: [null, null, null, null, null, "in", "in"],
daysInRange: 2,
daysLogged: 2,
});
// Misleading "2 of 7 in range" suppressed; honest "2 of 7 logged"
// surfaced instead.
expect(html).toContain("2 of 7 logged");
expect(html).not.toContain("2 of 7 in range");
});
it("renders all-hollow when every day has null (no readings yet)", () => {
const html = render({
days: [null, null, null, null, null, null, null],
daysInRange: 0,
daysLogged: 0,
});
// No band classes should be present; cap shows the logged variant.
expect(html).not.toContain("var(--dracula-green)");
expect(html).toContain("0 of 7 logged");
});
it("German locale surfaces the localised cap", () => {
const html = render(
{
days: ["in", "in", "in", "in", "in", "in", "in"],
daysInRange: 7,
daysLogged: 7,
},
"de",
);
expect(html).toContain("7 von 7 im Bereich");
});
});
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { RangeBar } from "../range-bar";
/**
* v1.4.25 W3e — `<RangeBar>` was extracted from the inline 790-line
* `targets/page.tsx`. Behaviour is intentionally unchanged from the
* v1.4.22 inline version; these tests pin the contract so the
* extraction is provably side-effect-free.
*/
function render(props: Parameters<typeof RangeBar>[0]) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<RangeBar {...props} />
</I18nProvider>,
);
}
describe("<RangeBar>", () => {
it("renders the bar slot + green/orange/red zones with Dracula tokens", () => {
const html = render({
value: 72,
min: 60,
max: 100,
unit: "bpm",
});
expect(html).toContain('data-slot="target-range-bar"');
expect(html).toContain("bg-dracula-green/20");
expect(html).toContain("bg-dracula-orange/15");
expect(html).toContain("bg-dracula-red/10");
// Pin the absence of the legacy raw Tailwind palette so the swap
// doesn't silently regress on future merges.
expect(html).not.toContain("bg-green-500/20");
expect(html).not.toContain("bg-yellow-500/12");
expect(html).not.toContain("bg-red-500/8");
});
it("paints the marker with the green token when the value is in range", () => {
const html = render({
value: 80,
min: 60,
max: 100,
unit: "bpm",
});
expect(html).toContain("var(--dracula-green)");
});
it("paints the marker with the red token when the value is out of band", () => {
const html = render({
value: 180,
min: 60,
max: 100,
unit: "bpm",
});
expect(html).toContain("var(--dracula-red)");
});
});
@@ -0,0 +1,180 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { TargetCard, type TargetCardData } from "../target-card";
/**
* v1.4.25 W3e — `<TargetCard>` composition. Three load-bearing cases:
*
* 1. Full-data card — headline + status pill + range bar +
* consistency strip + Coach CTA + source link all visible.
* 2. Insufficient-data card — strip + recency line + streak chip
* all suppressed; the explicit "not enough data yet" inline
* message renders instead.
* 3. AI gate — Coach CTA suppressed when `aiEnabled` is false.
*/
function render(props: Parameters<typeof TargetCard>[0]) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<TargetCard {...props} />
</I18nProvider>,
);
}
const fullDataTarget: TargetCardData = {
type: "WEIGHT",
label: "Weight",
current: 78.2,
average30: 79.1,
trend: "down",
unit: "kg",
range: { min: 60, max: 80 },
classification: { category: "Normal", color: "#50fa7b" },
source: "WHO BMI",
daysInRange7d: 5,
daysLogged7d: 7,
lastMetGoalAt: "2026-05-10",
streakDays: 4,
insufficientData: false,
consistency7d: ["in", "in", "near", "in", "out", "in", "in"],
};
const sparseTarget: TargetCardData = {
type: "PULSE",
label: "Resting pulse",
current: 72,
average30: 72,
trend: null,
unit: "bpm",
range: { min: 60, max: 100 },
classification: { category: "On target", color: "#50fa7b" },
source: "AHA",
daysInRange7d: 0,
daysLogged7d: 0,
lastMetGoalAt: null,
streakDays: 0,
insufficientData: true,
consistency7d: [null, null, null, null, null, null, null],
};
describe("<TargetCard>", () => {
it("renders the full layout when the target has rich data", () => {
const html = render({
target: fullDataTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).toContain('data-slot="target-card"');
expect(html).toContain('data-slot="target-status-pill"');
expect(html).toContain('data-slot="target-range-bar"');
expect(html).toContain('data-slot="consistency-strip"');
expect(html).toContain('data-slot="target-coach-cta"');
expect(html).toContain('data-slot="target-streak"');
// Streak chip surfaces the count from i18n
expect(html).toContain("4-day streak");
// Headline number (78.2 → 78.2) + the kg unit
expect(html).toContain("78.2");
});
it("hides the consistency strip + recency + streak when insufficient data", () => {
const html = render({
target: sparseTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).not.toContain('data-slot="consistency-strip"');
expect(html).not.toContain('data-slot="target-last-met"');
expect(html).not.toContain('data-slot="target-streak"');
// The explicit "not enough data yet" message replaces the strip
expect(html).toContain('data-slot="target-insufficient-data"');
});
it("suppresses the Coach CTA when aiEnabled is false", () => {
const html = render({
target: fullDataTarget,
aiEnabled: false,
onAskCoach: vi.fn(),
});
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("renders MOOD_STABILITY headline as a verbal label, not the σ value", () => {
const moodStability: TargetCardData = {
...fullDataTarget,
type: "MOOD_STABILITY",
label: "Mood stability",
current: 0.6,
unit: "σ",
range: { min: 0, max: 0.5 },
classification: { category: "Stable", color: "#f1fa8c" },
};
const html = render({
target: moodStability,
aiEnabled: false,
onAskCoach: vi.fn(),
});
// The big-number slot should carry the EN verbal label, not "0.6".
expect(html).toContain('data-mood-stability="stable"');
expect(html).toContain("stable");
expect(html).not.toMatch(/>0\.6</);
});
/**
* v1.4.25 W3f — per-card edit cog. The cog must render on EVERY
* card regardless of insufficient-data state so the user always has
* an entry point to adjust the target range.
*/
describe("per-card edit cog (v1.4.25 W3f)", () => {
it("renders the edit cog with an aria-label for the rich-data card", () => {
const html = render({
target: fullDataTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).toContain('data-slot="target-edit-cog"');
expect(html).toContain('data-target-type="WEIGHT"');
expect(html).toContain("Edit target range for Weight");
});
it("STILL renders the cog when the target is in insufficient-data mode", () => {
// Consistency rule: target-config UI must always be reachable,
// even when the consistency strip is hidden.
const html = render({
target: sparseTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).toContain('data-slot="target-edit-cog"');
expect(html).toContain('data-target-type="PULSE"');
});
it("renders the cog when the AI provider is disabled (gate is independent)", () => {
// The Coach CTA depends on aiEnabled; the edit cog does not.
const html = render({
target: fullDataTarget,
aiEnabled: false,
onAskCoach: vi.fn(),
});
expect(html).toContain('data-slot="target-edit-cog"');
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("renders the cog button with adequate touch target (min-h-11 + min-w-11)", () => {
// Mobile-first: tap target ≥ 44 px so the cog isn't an
// accessibility hazard on smaller phones.
const html = render({
target: fullDataTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).toMatch(
/data-slot="target-edit-cog"[^>]*class="[^"]*min-h-11[^"]*"/,
);
expect(html).toMatch(
/data-slot="target-edit-cog"[^>]*class="[^"]*min-w-11[^"]*"/,
);
});
});
});
@@ -0,0 +1,45 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { TargetCoachButton } from "../target-coach-button";
/**
* v1.4.25 W3e — gate test for the per-card Coach CTA. The button
* MUST disappear when `aiEnabled` is false (Marc directive: no
* broken-button state for users with no AI provider configured).
*/
function render(props: Parameters<typeof TargetCoachButton>[0]) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<TargetCoachButton {...props} />
</I18nProvider>,
);
}
describe("<TargetCoachButton>", () => {
const baseProps = {
prefill: "How am I doing on weight?",
sources: ["weight"] as const,
onAskCoach: vi.fn(),
};
it("renders the button when aiEnabled is true", () => {
const html = render({ ...baseProps, aiEnabled: true });
expect(html).toContain('data-slot="target-coach-cta"');
expect(html).toContain("Ask Coach");
});
it("renders NOTHING when aiEnabled is false (no broken-button state)", () => {
const html = render({ ...baseProps, aiEnabled: false });
expect(html).toBe("");
});
it("does not call onAskCoach during SSR", () => {
const onAskCoach = vi.fn();
render({ ...baseProps, onAskCoach, aiEnabled: true });
// Server-side render does not fire click handlers.
expect(onAskCoach).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,198 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { TargetEditSheet } from "../target-edit-sheet";
/**
* v1.4.25 W3f — target-edit dialog. SSR-style assertions because the
* Radix Dialog body is portalled at runtime; we only check the
* outer Dialog wiring + the body-mount toggle.
*
* Branches covered:
* 1. open=false → renders no portal markup at all (Dialog content
* not mounted; query hooks never instantiated).
* 2. open=true (editable metric) → the Dialog wrapper is present;
* the inner body would render the input rows if it weren't
* portalled (we can't see inside but we CAN assert the body
* mount path doesn't throw).
* 3. open=true (derived metric like BMI) → same, with the derived
* hint path exercised.
*
* A separate `focus-management` test asserts the open=true mount
* doesn't crash under React's strict-mode render.
*/
function withProviders(node: React.ReactNode) {
const client = new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0 },
mutations: { retry: false },
},
});
return (
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">{node}</I18nProvider>
</QueryClientProvider>
);
}
describe("<TargetEditSheet>", () => {
it("renders no Dialog content when open=false (hooks never instantiate)", () => {
// Closed dialog: zero markup beyond the Radix root container.
const html = renderToStaticMarkup(
withProviders(
<TargetEditSheet
targetType="WEIGHT"
targetLabel="Weight"
unit="kg"
initialRange={{ min: 60, max: 80 }}
open={false}
onOpenChange={vi.fn()}
/>,
),
);
// Body is not mounted while closed — no data-slot for the body.
expect(html).not.toContain('data-slot="target-edit-sheet"');
});
it("mounts the body without throwing for an editable metric (WEIGHT)", () => {
// Radix portals the DialogContent so it's not in SSR markup, but
// mounting the body must not throw — the QueryClientProvider above
// provides the necessary context.
expect(() =>
renderToStaticMarkup(
withProviders(
<TargetEditSheet
targetType="WEIGHT"
targetLabel="Weight"
unit="kg"
initialRange={{ min: 60, max: 80 }}
open={true}
onOpenChange={vi.fn()}
/>,
),
),
).not.toThrow();
});
it("mounts the body without throwing for a BP target (two range pairs)", () => {
// BP gets BOTH sys + dia input rows.
expect(() =>
renderToStaticMarkup(
withProviders(
<TargetEditSheet
targetType="BLOOD_PRESSURE"
targetLabel="Blood pressure"
unit="mmHg"
initialRange={{ min: 110, max: 130 }}
initialDiastolicRange={{ min: 70, max: 85 }}
open={true}
onOpenChange={vi.fn()}
/>,
),
),
).not.toThrow();
});
it("mounts the body without throwing for a derived metric (BMI)", () => {
// BMI is derived from weight + height — the body shows the
// explanatory hint instead of the editable inputs.
expect(() =>
renderToStaticMarkup(
withProviders(
<TargetEditSheet
targetType="BMI"
targetLabel="BMI"
unit=""
initialRange={{ min: 18.5, max: 24.9 }}
open={true}
onOpenChange={vi.fn()}
/>,
),
),
).not.toThrow();
});
it("re-renders cleanly when open flips from false → true", () => {
// Verifies the lazy-mount: closed render produces zero body
// markup; opening it instantiates the body without conflicting
// with the prior render.
const client = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
});
const closedHtml = renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<TargetEditSheet
targetType="PULSE"
targetLabel="Resting pulse"
unit="bpm"
initialRange={{ min: 60, max: 100 }}
open={false}
onOpenChange={vi.fn()}
/>
</I18nProvider>
</QueryClientProvider>,
);
expect(closedHtml).not.toContain('data-slot="target-edit-sheet"');
const openHtml = renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<TargetEditSheet
targetType="PULSE"
targetLabel="Resting pulse"
unit="bpm"
initialRange={{ min: 60, max: 100 }}
open={true}
onOpenChange={vi.fn()}
/>
</I18nProvider>
</QueryClientProvider>,
);
// No crash; the Radix Dialog root is in the markup.
expect(openHtml).toBeTypeOf("string");
});
/**
* v1.4.25 W3f — focus-management contract. The dialog's
* `onOpenAutoFocus` handler must steal focus from Radix's default
* (the close X button) and place it on the first numeric input so a
* keyboard user lands on the editable field. We verify the handler
* is wired up via the SSR output: Radix renders Dialog content
* lazily, so we check that the component compiles + the ref pattern
* doesn't throw under render (a defensive smoke; the actual focus
* shift is exercised by Playwright in the v1.4.25 verification
* phase).
*/
describe("focus management (v1.4.25 W3f)", () => {
it("does not throw when the dialog opens with a valid ref target", () => {
// The body's onOpenAutoFocus handler reads firstInputRef.current
// — this is null at SSR time. The handler is guarded by an
// `if (firstInputRef.current)` check so the SSR render never
// dereferences null. This test pins that contract: the open
// mount must not throw, even though the DOM ref isn't set yet.
const client = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
});
expect(() =>
renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<TargetEditSheet
targetType="BODY_FAT"
targetLabel="Body fat"
unit="%"
initialRange={{ min: 10, max: 22 }}
open={true}
onOpenChange={vi.fn()}
/>
</I18nProvider>
</QueryClientProvider>,
),
).not.toThrow();
});
});
});
@@ -0,0 +1,63 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { TargetsSummaryHeader } from "../targets-summary-header";
/**
* v1.4.25 W3e — page-level summary line. Three load-bearing cases:
* 1. Partial: "4 of 6 targets met this week"
* 2. Full: "All 6 targets met this week" + check mark
* 3. With streak highlight chip
*/
function render(props: Parameters<typeof TargetsSummaryHeader>[0]) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">
<TargetsSummaryHeader {...props} />
</I18nProvider>,
);
}
describe("<TargetsSummaryHeader>", () => {
it("renders the partial-count headline when met < total", () => {
const html = render({
targetsMetThisWeek: 4,
totalTargets: 6,
streakHighlight: null,
});
expect(html).toContain('data-slot="targets-summary-title"');
expect(html).toContain("4 of 6 targets met this week");
// Check mark should NOT render in the partial state.
expect(html).not.toContain("lucide-check");
});
it("renders the all-met headline + check mark when every target is met", () => {
const html = render({
targetsMetThisWeek: 6,
totalTargets: 6,
streakHighlight: null,
});
expect(html).toContain("All 6 targets met this week");
expect(html).toContain("text-[var(--dracula-green)]");
});
it("renders the streak highlight chip when present", () => {
const html = render({
targetsMetThisWeek: 4,
totalTargets: 6,
streakHighlight: { metric: "BLOOD_PRESSURE", days: 5 },
});
expect(html).toContain('data-slot="targets-summary-streak"');
expect(html).toContain("5-day streak: Blood pressure");
});
it("renders nothing when there are no targets at all", () => {
const html = render({
targetsMetThisWeek: 0,
totalTargets: 0,
streakHighlight: null,
});
expect(html).toBe("");
});
});
@@ -0,0 +1,145 @@
"use client";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
/**
* v1.4.25 W3e — 7-day consistency strip.
*
* Renders one dot per Berlin-tz day in `days` (oldest → newest, index 6
* is today). Each dot's appearance encodes both whether the day was
* logged and whether the day's mean reading landed in the target's
* green band:
*
* • Solid green — `"in"` : day's mean was in the target band
* • Solid amber — `"near"` : day's mean was in the orange band
* • Solid red — `"out"` : day's mean was outside both bands
* • Hollow ring — `null` : day had no readings (dim border only)
*
* Cap to the right: "5 of 7 in range" (or the user's locale's
* equivalent). The cap reads off `daysInRange` and `daysLogged`. When
* the cap would be misleading on thin data (≤ 2 days logged) we surface
* "X of 7 logged" instead so the user sees the cadence problem, not the
* misleading range count.
*
* Hidden by the parent when the target's `insufficientData` flag is
* true — there is no "— not enough data" empty-state mode here; the
* card surfaces that copy in a different slot per Marc's "no empty hint
* inside the strip" directive.
*
* Visual rationale (frontend-design skill): seven dots over the v1.4.22
* 24-px sparkline trades a continuous-but-distorted signal for seven
* honest atomic answers. The hollow-ring "no data" state means the
* gap is visible without leaving the user wondering whether the
* sparkline simply ended there.
*/
export type ConsistencyBand = "in" | "near" | "out" | null;
export interface ConsistencyStripProps {
/**
* Seven entries, index 0 = six days ago, index 6 = today. Anything
* other than 7 is rendered as-is (so callers can pass a short array
* for tests), but the live API always sends exactly 7.
*/
days: ReadonlyArray<ConsistencyBand>;
daysInRange: number;
daysLogged: number;
className?: string;
}
// An arbitrary shadow utility with an opacity modifier (a "/20" suffix
// on the bracketed value) hits the same Turbopack CSS-parser issue as
// the bracket-form CSS-variable utilities — see the comment in
// target-card.tsx for the full diagnosis. The shadow's alpha is now
// encoded inside the value via color-mix so the opacity modifier is
// no longer needed and the bracketed form parses cleanly.
const BAND_STYLES: Record<NonNullable<ConsistencyBand>, string> = {
in: "bg-(--dracula-green) border-(--dracula-green) shadow-[0_0_0_1px_color-mix(in_oklab,var(--dracula-green)_20%,transparent)]",
near: "bg-(--dracula-orange) border-(--dracula-orange)",
out: "bg-(--dracula-red) border-(--dracula-red)",
};
const BAND_ARIA: Record<NonNullable<ConsistencyBand>, string> = {
in: "targets.consistency.dotInRange",
near: "targets.consistency.dotNearRange",
out: "targets.consistency.dotOutOfRange",
};
const RELATIVE_DAY_KEYS = [
"targets.consistency.relativeDay.sixDaysAgo",
"targets.consistency.relativeDay.fiveDaysAgo",
"targets.consistency.relativeDay.fourDaysAgo",
"targets.consistency.relativeDay.threeDaysAgo",
"targets.consistency.relativeDay.twoDaysAgo",
"targets.consistency.relativeDay.yesterday",
"targets.consistency.relativeDay.today",
];
export function ConsistencyStrip({
days,
daysInRange,
daysLogged,
className,
}: ConsistencyStripProps) {
const { t } = useTranslations();
// Cap rule: if very few days logged, surface the cadence problem
// ("X of 7 logged") rather than the misleading range count. The
// threshold matches the server's `insufficientData < 3 readings`
// guard one tier lower so the strip can still render gracefully
// when the parent decided to mount it.
const showLoggedCap = daysLogged <= 2;
const cap = showLoggedCap
? t("targets.consistency.daysLogged", {
count: String(daysLogged),
total: "7",
})
: t("targets.consistency.daysInRange", {
count: String(daysInRange),
total: "7",
});
return (
<div
data-slot="consistency-strip"
className={cn(
"flex items-center justify-between gap-3 text-xs",
className,
)}
>
<ul
role="list"
aria-label={t("targets.consistency.ariaLabel")}
className="flex items-center gap-1.5"
>
{days.map((band, index) => {
const relativeKey =
RELATIVE_DAY_KEYS[
index + (RELATIVE_DAY_KEYS.length - days.length)
] ?? RELATIVE_DAY_KEYS[RELATIVE_DAY_KEYS.length - 1];
const dayLabel = t(relativeKey);
const statusLabel = band
? t(BAND_ARIA[band])
: t("targets.consistency.dotNotLogged");
return (
<li
key={`${index}-${band ?? "none"}`}
aria-label={`${dayLabel}: ${statusLabel}`}
data-band={band ?? "none"}
className={cn(
"size-2.5 rounded-full border transition-colors",
band ? BAND_STYLES[band] : "border-border bg-transparent",
)}
/>
);
})}
</ul>
<span
className="text-muted-foreground tabular-nums"
data-slot="consistency-cap"
>
{cap}
</span>
</div>
);
}
+176
View File
@@ -0,0 +1,176 @@
"use client";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useTranslations } from "@/lib/i18n/context";
/**
* v1.4.25 W3e — extracted from `src/app/targets/page.tsx` (the page
* was 790 lines; the redesign breaks it into focused primitives so
* each component carries its own contract + test suite).
*
* A horizontal range bar with green/yellow/red zones showing where
* the current value falls relative to a target range. The marker dot
* carries a tooltip with the current value + the target range + a
* delta sentence (e.g. "6 mmHg above target band").
*
* Behaviour is unchanged from the v1.4.22 inline version; only the
* file boundary moves.
*/
export interface RangeBarProps {
value: number;
min: number;
max: number;
unit: string;
orangeMin?: number;
orangeMax?: number;
}
export function RangeBar({
value,
min,
max,
unit,
orangeMin,
orangeMax,
}: RangeBarProps) {
const { t } = useTranslations();
const span = max - min;
const defaultOrangeWidth = span * 0.3;
const computedOrangeMin = min - defaultOrangeWidth;
const computedOrangeMax = max + defaultOrangeWidth;
const effectiveOrangeMin =
orangeMin != null ? Math.min(orangeMin, min) : computedOrangeMin;
const effectiveOrangeMax =
orangeMax != null ? Math.max(orangeMax, max) : computedOrangeMax;
const orangeSpan = Math.max(1, effectiveOrangeMax - effectiveOrangeMin);
const sidePadding = Math.max(1, orangeSpan * 0.18);
const visualMin = effectiveOrangeMin - sidePadding;
const visualMax = effectiveOrangeMax + sidePadding;
const visualSpan = visualMax - visualMin;
const clampedValue = Math.max(visualMin, Math.min(visualMax, value));
const rawPosition = ((clampedValue - visualMin) / visualSpan) * 100;
const EDGE_PADDING_PERCENT = 4;
const position = Math.max(
EDGE_PADDING_PERCENT,
Math.min(100 - EDGE_PADDING_PERCENT, rawPosition),
);
// Zone boundaries (percent of visual bar)
const greenStart = Math.max(0, ((min - visualMin) / visualSpan) * 100);
const greenEnd = Math.min(100, ((max - visualMin) / visualSpan) * 100);
const yellowLeftStart = Math.max(
0,
((effectiveOrangeMin - visualMin) / visualSpan) * 100,
);
const yellowRightEnd = Math.min(
100,
((effectiveOrangeMax - visualMin) / visualSpan) * 100,
);
// Determine marker color
const inGreen = value >= min && value <= max;
const inYellow =
!inGreen && value >= effectiveOrangeMin && value <= effectiveOrangeMax;
const markerColor = inGreen
? "var(--dracula-green)"
: inYellow
? "var(--dracula-orange)"
: "var(--dracula-red)";
const minLabelPosition = Math.max(5, Math.min(95, greenStart));
const maxLabelPosition = Math.max(5, Math.min(95, greenEnd));
// Delta to target range
const delta = value < min ? min - value : value > max ? value - max : 0;
const deltaText =
delta > 0
? value < min
? t("targets.belowTarget", { delta: delta.toFixed(1), unit })
: t("targets.aboveTarget", { delta: delta.toFixed(1), unit })
: t("targets.inTarget");
return (
<div className="space-y-1.5" data-slot="target-range-bar">
<div className="bg-muted/50 relative h-3 w-full overflow-hidden rounded-full">
{/* Red background (full bar) — Dracula `--dracula-red` so the
chart palette stays aligned with PR-badge, alerts, and the
marker dot itself. Raw Tailwind palettes drift from the
theme over time and never get dark-mode tuned. */}
<div className="bg-dracula-red/10 absolute inset-0 rounded-full" />
{/* Orange (caution) side zones — `--dracula-orange` matches the
marker's out-of-band tint. */}
<div
className="bg-dracula-orange/15 absolute top-0 h-full"
style={{
left: `${yellowLeftStart}%`,
width: `${greenStart - yellowLeftStart}%`,
}}
/>
<div
className="bg-dracula-orange/15 absolute top-0 h-full"
style={{
left: `${greenEnd}%`,
width: `${yellowRightEnd - greenEnd}%`,
}}
/>
{/* In-band green zone — `--dracula-green`. */}
<div
className="bg-dracula-green/20 absolute top-0 h-full"
style={{
left: `${greenStart}%`,
width: `${greenEnd - greenStart}%`,
}}
/>
{/* Current value marker with tooltip */}
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<div
className="absolute top-1/2 h-5 w-5 -translate-x-1/2 -translate-y-1/2 cursor-pointer rounded-full border-2 shadow-sm"
style={{
left: `${position}%`,
backgroundColor: markerColor,
borderColor: markerColor,
}}
/>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs font-medium">
{t("targets.currentValue", { value: String(value), unit })}
</p>
<p className="text-xs">
{t("targets.targetRangeValue", {
min: String(min),
max: String(max),
unit,
})}
</p>
<p className="text-xs font-medium">{deltaText}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<div className="text-muted-foreground relative h-4 text-xs">
<span
className="absolute -translate-x-1/2"
style={{ left: `${minLabelPosition}%` }}
>
{min} {unit}
</span>
<span
className="absolute -translate-x-1/2"
style={{ left: `${maxLabelPosition}%` }}
>
{max} {unit}
</span>
</div>
</div>
);
}
+707
View File
@@ -0,0 +1,707 @@
"use client";
import { useState } from "react";
import {
AlertCircle,
Activity,
Droplet,
ExternalLink,
Heart,
Minus,
Moon,
Percent,
Scale,
Settings2,
Smile,
TrendingDown,
TrendingUp,
} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
import { moodStabilityLabel } from "@/lib/targets/mood-stability-label";
import { ConsistencyStrip } from "./consistency-strip";
import { RangeBar } from "./range-bar";
import { TargetCoachButton } from "./target-coach-button";
import { TargetEditSheet } from "./target-edit-sheet";
import { buildTargetPrompt } from "@/lib/ai/coach/target-prompts";
import { coachScopeForTarget } from "@/lib/ai/coach/target-scope";
import type { CoachScope } from "@/lib/ai/coach/types";
/**
* v1.4.25 W3e — `<TargetCard>` extracted from `src/app/targets/page.tsx`
* with a Marc-directive redesign. Visual rationale:
*
* • Headline row pairs the metric label with a verbal status pill —
* Q1 ("am I on track right now?") answered before the user's eye
* moves below the title.
* • Big value with the unit small + muted; the inline trend chevron
* sits next to the value, not in a separate row.
* • Range bar carries the precise placement; the bar is the
* "spatial" answer to Q2 (delta to goal).
* • Consistency strip beneath the bar answers Q7 ("how consistent
* am I?"). Hidden when `insufficientData` is true so cold-start
* accounts don't see a dead-grey row.
* • Recency caption ("last met goal: 2 days ago") + streak chip
* when ≥ 3 days. Both are conditional on real data — no empty
* placeholders.
* • Footer row: per-card Coach CTA on the left (only when the user
* has an AI provider configured), guideline-source link on the
* right.
*
* Per Marc's "muss nicht so sein wie die KI Sache": the card stays
* quiet. No gradients, no chips with emoji, no animation. Editorial
* spacing rhythm; one decisive number and one decisive status pill.
*/
const TYPE_ICONS: Record<string, LucideIcon> = {
WEIGHT: Scale,
BLOOD_PRESSURE: Heart,
BLOOD_PRESSURE_IN_TARGET: Heart,
PULSE: Activity,
SLEEP_DURATION: Moon,
BODY_FAT: Percent,
BMI: Scale,
MOOD_SCORE: Smile,
MOOD_STABILITY: Smile,
BLOOD_GLUCOSE_FASTING: Droplet,
BLOOD_GLUCOSE_POSTPRANDIAL: Droplet,
BLOOD_GLUCOSE_RANDOM: Droplet,
BLOOD_GLUCOSE_BEDTIME: Droplet,
};
const TYPE_COLORS: Record<string, string> = {
WEIGHT: "text-dracula-purple",
BLOOD_PRESSURE: "text-dracula-pink",
BLOOD_PRESSURE_IN_TARGET: "text-dracula-pink",
PULSE: "text-dracula-green",
SLEEP_DURATION: "text-dracula-cyan",
BODY_FAT: "text-dracula-orange",
BMI: "text-dracula-yellow",
MOOD_SCORE: "text-dracula-lavender",
MOOD_STABILITY: "text-dracula-lavender",
BLOOD_GLUCOSE_FASTING: "text-dracula-red",
BLOOD_GLUCOSE_POSTPRANDIAL: "text-dracula-red",
BLOOD_GLUCOSE_RANDOM: "text-dracula-red",
BLOOD_GLUCOSE_BEDTIME: "text-dracula-red",
};
const STATUS_CATEGORY_KEY: Record<string, string> = {
Underweight: "underweight",
Normal: "normal",
Overweight: "overweight",
"Obesity Grade I": "obesityGrade1",
"Obesity Grade II": "obesityGrade2",
"Obesity Grade III": "obesityGrade3",
Optimal: "optimal",
"High-normal": "highNormal",
"Hypertension Grade 1": "hypertensionGrade1",
"Hypertension Grade 2": "hypertensionGrade2",
"Hypertension Grade 3": "hypertensionGrade3",
Bradycardia: "bradycardia",
Elevated: "elevated",
Tachycardia: "tachycardia",
"Significantly low": "significantlyLow",
"Slightly low": "slightlyLow",
"On target": "onTarget",
"Slightly elevated": "slightlyElevated",
"Significantly elevated": "significantlyElevated",
"Far too short": "farTooShort",
"Too short": "tooShort",
"Slightly long": "slightlyLong",
"Far too long": "farTooLong",
"Below essential": "belowEssential",
Essential: "essential",
Athletic: "athletic",
Fitness: "fitness",
Acceptable: "acceptable",
Obese: "obese",
"Very low": "veryLow",
"Low active": "lowActive",
"Moderately active": "moderatelyActive",
Active: "active",
"Very active": "veryActive",
Good: "good",
Moderate: "moderate",
Low: "low",
High: "high",
"Very good": "veryGood",
"Very stable": "veryStable",
Stable: "stable",
Fluctuating: "fluctuating",
};
/** Resolve a server-emitted classification.category to its translated label. */
function translateStatus(
category: string,
t: (key: string, vars?: Record<string, string>) => string,
): string {
const key = STATUS_CATEGORY_KEY[category];
if (!key) return category;
return t(`targets.status.${key}`);
}
/**
* Map an in-band classification category to one of three semantic
* groups. Used to drive the status-pill style without re-classifying
* the value from scratch; the server's category is canonical.
*
* "in" = inside the green band ("On target", "Normal", "Optimal", …).
* "near" = inside the orange band ("Slightly elevated", "Overweight",
* …) or a step inside an obesity / hypertension grade-1 band.
* "out" = outside all bands ("Hypertension Grade 3", "Obesity Grade
* III", "Tachycardia" away from the target band, …).
*
* When the category is unmapped we fall back to "near" — the safe
* middle, which paints the pill in the neutral amber tone rather than
* lighting up a false-positive green/red.
*/
function statusGroupForCategory(category: string): "in" | "near" | "out" {
const greenCategories = new Set([
"Normal",
"Optimal",
"On target",
"Good",
"Very good",
"Very stable",
"Stable",
"Athletic",
"Fitness",
"Acceptable",
"Active",
"Very active",
"Moderately active",
"Essential",
]);
const redCategories = new Set([
"Obesity Grade III",
"Hypertension Grade 3",
"Significantly elevated",
"Significantly low",
"Far too short",
"Far too long",
"Tachycardia",
"Bradycardia",
"Low",
"High",
"Fluctuating",
"Below essential",
"Very low",
]);
if (greenCategories.has(category)) return "in";
if (redCategories.has(category)) return "out";
return "near";
}
// Use the Tailwind v4 parenthesised CSS-variable shorthand
// (bg-VAR-PAREN-FORM-/N) instead of the legacy bracketed VAR-form. The
// bracketed form combined with an opacity modifier emits an escaped
// class selector that Turbopack's CSS parser rejects with
// "Unexpected token Delim('.')" because the scanner picks the literal
// string out of source files (including this comment) and emits a CSS
// rule for it. The parenthesised shorthand produces a clean selector
// that parses cleanly. See the Tailwind v4 upgrade guide for the
// migration from bracket-form to paren-form for CSS-variable values.
const STATUS_PILL_STYLES: Record<"in" | "near" | "out", string> = {
in: "bg-(--dracula-green)/12 text-(--dracula-green) ring-(--dracula-green)/30",
near: "bg-(--dracula-orange)/14 text-(--dracula-orange) ring-(--dracula-orange)/30",
out: "bg-(--dracula-red)/12 text-(--dracula-red) ring-(--dracula-red)/30",
};
interface TargetClassification {
category: string;
color: string;
}
interface BpDiastolic {
current: number | null;
average30: number | null;
range: { min: number; max: number } | null;
}
export interface TargetCardData {
type: string;
label: string;
current: number | null;
average30: number | null;
trend: "up" | "down" | "stable" | null;
unit: string;
range: { min: number; max: number } | null;
classification: TargetClassification | null;
source: string;
daysInRange7d?: number;
daysLogged7d?: number;
lastMetGoalAt?: string | null;
streakDays?: number;
insufficientData?: boolean;
consistency7d?: ReadonlyArray<"in" | "near" | "out" | null>;
details?: {
medications?: Array<{
name: string;
compliance7: number;
compliance30: number;
}>;
};
}
export interface TargetCardProps {
target: TargetCardData;
bpDiastolic?: BpDiastolic;
/**
* AI gate. When false, the per-card Coach CTA is suppressed entirely
* (no greyed-out button, no tooltip placeholder). The parent reads
* `/api/insights/provider-chain` and threads this flag.
*/
aiEnabled: boolean;
/**
* Drawer handoff. Receives the pre-formatted prefill + the
* narrowed scope (single source for 1:1 metrics, derived source
* for BMI / mood stability, all sources for the rest).
*/
onAskCoach: (payload: { prefill: string; scope: CoachScope }) => void;
/**
* Optional source URL for the guideline link. Threaded from the
* page rather than computed in the card so the resolution stays
* declarative + testable.
*/
sourceLink?: string | null;
}
function TrendIcon({ trend }: { trend: "up" | "down" | "stable" | null }) {
if (trend === "up") {
return (
<TrendingUp
className="text-dracula-orange size-4"
aria-hidden="true"
data-slot="target-trend-icon"
data-trend="up"
/>
);
}
if (trend === "down") {
return (
<TrendingDown
className="text-dracula-cyan size-4"
aria-hidden="true"
data-slot="target-trend-icon"
data-trend="down"
/>
);
}
if (trend === "stable") {
return (
<Minus
className="text-dracula-green size-4"
aria-hidden="true"
data-slot="target-trend-icon"
data-trend="stable"
/>
);
}
return null;
}
function formatRelativeDay(
isoDate: string,
t: (key: string, vars?: Record<string, string>) => string,
): string {
// `isoDate` is a Berlin-tz day key (YYYY-MM-DD). Compare to today's
// Berlin-tz day by parsing both as local Date midnight; we only need
// a day-resolution delta so timezone math is unnecessary.
const today = new Date();
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
if (isoDate === todayKey) return t("targets.relativeDay.today");
const [y, m, d] = isoDate.split("-").map(Number);
const target = new Date(y, (m ?? 1) - 1, d ?? 1);
const todayMid = new Date(
today.getFullYear(),
today.getMonth(),
today.getDate(),
);
const diffDays = Math.round(
(todayMid.getTime() - target.getTime()) / (24 * 60 * 60 * 1000),
);
if (diffDays === 1) return t("targets.relativeDay.yesterday");
if (diffDays < 0) return t("targets.relativeDay.today"); // future, shouldn't happen
return t("targets.relativeDay.daysAgo", { count: String(diffDays) });
}
export function TargetCard({
target,
bpDiastolic,
aiEnabled,
onAskCoach,
sourceLink,
}: TargetCardProps) {
const { t, locale } = useTranslations();
// v1.4.25 W3f — per-card edit affordance. Cog top-right of every
// card opens the edit dialog; the dialog handles the read-only path
// for derived metrics (BMI, MOOD_*, MEDICATION_COMPLIANCE,
// BLOOD_PRESSURE_IN_TARGET) by showing an explanatory caption.
const [editOpen, setEditOpen] = useState(false);
const Icon = TYPE_ICONS[target.type] ?? Activity;
const iconColor = TYPE_COLORS[target.type] ?? "text-primary";
const isBp = target.type === "BLOOD_PRESSURE";
const isMedicationCompliance = target.type === "MEDICATION_COMPLIANCE";
const medicationBreakdown = target.details?.medications ?? [];
const localisedLabel = t(`targets.label.${target.type}`);
const titleLabel =
localisedLabel === `targets.label.${target.type}`
? target.label
: localisedLabel;
const statusGroup = target.classification
? statusGroupForCategory(target.classification.category)
: "near";
const statusPillStyle = STATUS_PILL_STYLES[statusGroup];
const statusLabel = target.classification
? translateStatus(target.classification.category, t)
: null;
// MOOD_STABILITY headline switches from numeric σ to a verbal label.
// The numeric stays as a tooltip behind the pill so power users can
// still see the σ value.
const moodStabilityValue =
target.type === "MOOD_STABILITY" && target.current != null
? moodStabilityLabel(target.current)
: null;
const moodStabilityCopy =
moodStabilityValue != null
? t(`targets.mood.stability.${moodStabilityValue}`)
: null;
const showConsistency =
!target.insufficientData &&
target.consistency7d != null &&
target.consistency7d.length > 0;
const showLastMet = target.lastMetGoalAt != null && !target.insufficientData;
const showStreak =
target.streakDays != null &&
target.streakDays >= 3 &&
!target.insufficientData;
// Coach prefill is built from the live state of the card; the helper
// file owns the per-metric template + locale resolution.
const coachPrefill = buildTargetPrompt({
type: target.type,
locale,
current: target.current,
range: target.range,
unit: target.unit,
status: statusLabel ?? null,
streakDays: target.streakDays ?? 0,
daysInRange7d: target.daysInRange7d ?? 0,
});
const coachSources = coachScopeForTarget(target.type);
return (
<Card
data-slot="target-card"
data-target-type={target.type}
data-status={statusGroup}
className="flex h-full flex-col"
>
<CardHeader className="gap-2 pb-3 sm:gap-3">
{/* Row 1: icon + label (left) ⋯ status pill + edit-cog (right
on sm+, stacked on mobile). Stacking on mobile keeps the
headline number visible at sub-380px viewports where an
inline pill would push the value below the fold.
v1.4.25 W3f — the per-card cog renders on EVERY card
(consistency rule across Dashboard → Insights → Zielwerte),
with no insufficient-data gate. */}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-2">
<Icon
className={cn("size-4 shrink-0", iconColor)}
aria-hidden="true"
/>
<h3
className="text-muted-foreground text-[0.6875rem] font-medium tracking-[0.08em] uppercase"
data-slot="target-card-title"
>
{titleLabel}
</h3>
</div>
<div className="flex items-center gap-2 self-end sm:self-auto">
{statusLabel ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span
data-slot="target-status-pill"
data-status={statusGroup}
className={cn(
"inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ring-1",
statusPillStyle,
)}
>
{statusLabel}
</span>
</TooltipTrigger>
<TooltipContent>
{target.range && (
<p className="text-xs">
{t("targets.targetRangeValue", {
min: String(target.range.min),
max: String(target.range.max),
unit: target.unit,
})}
</p>
)}
<p className="text-xs">
{t("targets.sourceLabel", { source: target.source })}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : null}
<Button
type="button"
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-foreground -mr-2 min-h-11 min-w-11 px-0"
onClick={() => setEditOpen(true)}
aria-label={t("targets.edit.openLabel", {
metric: titleLabel,
})}
data-slot="target-edit-cog"
data-target-type={target.type}
>
<Settings2 className="h-3.5 w-3.5" aria-hidden="true" />
</Button>
</div>
</div>
</CardHeader>
<CardContent className="flex h-full flex-col gap-4">
{/* Row 2: big-number headline + trend chevron + unit */}
{target.current != null ? (
<div className="flex flex-col gap-1">
<div className="flex items-baseline gap-2">
{moodStabilityValue && moodStabilityCopy ? (
// v1.4.25 W3e — verbal label is the headline; the raw σ
// moves into a tooltip so power users keep the precise
// number one hover away without forcing every visitor
// to read "0.42 σ" and decode it.
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span
className="text-foreground cursor-help text-2xl leading-none font-semibold capitalize sm:text-3xl"
data-slot="target-headline-value"
data-mood-stability={moodStabilityValue}
>
{moodStabilityCopy}
</span>
</TooltipTrigger>
<TooltipContent>
<p className="text-xs">
σ ={" "}
{target.current != null
? target.current.toFixed(2)
: "—"}
</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : isBp && bpDiastolic?.current != null ? (
<span
className="text-foreground flex items-baseline gap-1 text-2xl leading-none font-semibold sm:text-3xl"
data-slot="target-headline-value"
>
<span>{Math.round(target.current)}</span>
<span className="text-muted-foreground text-lg">/</span>
<span>{Math.round(bpDiastolic.current)}</span>
</span>
) : (
<span
className="text-foreground text-2xl leading-none font-semibold sm:text-3xl"
data-slot="target-headline-value"
>
{target.type === "BODY_FAT"
? target.current.toFixed(1)
: Math.round(target.current * 10) / 10}
</span>
)}
{!moodStabilityValue && (
<span className="text-muted-foreground text-sm">
{target.unit}
</span>
)}
<span className="ml-auto">
<TrendIcon trend={target.trend} />
</span>
</div>
{target.average30 != null && (
<p className="text-muted-foreground text-xs">
{t("targets.average30d")}{" "}
{isBp && bpDiastolic?.average30 != null
? `${Math.round(target.average30)}/${Math.round(bpDiastolic.average30)}`
: Math.round(target.average30 * 10) / 10}{" "}
{target.unit}
</p>
)}
</div>
) : (
<div className="text-muted-foreground flex items-center gap-2">
<AlertCircle className="size-4" aria-hidden="true" />
<span className="text-sm">{t("targets.noMeasurementYet")}</span>
</div>
)}
{/* Row 3: primary range bar (only for cards whose underlying
metric has a defined band — the helper drops the bar
gracefully for derived ones without a range). */}
{target.range && target.current != null && (
<RangeBar
value={target.current}
min={target.range.min}
max={target.range.max}
unit={target.unit}
orangeMin={isMedicationCompliance ? 70 : undefined}
orangeMax={isMedicationCompliance ? 100 : undefined}
/>
)}
{/* Row 3b: BP diastolic range bar */}
{isBp && bpDiastolic?.range && bpDiastolic.current != null && (
<div className="space-y-1">
<p className="text-muted-foreground text-xs">
{t("targets.diastolic")}
</p>
<RangeBar
value={bpDiastolic.current}
min={bpDiastolic.range.min}
max={bpDiastolic.range.max}
unit="mmHg"
/>
</div>
)}
{/* Row 4: consistency strip (hidden when insufficient data) */}
{showConsistency && target.consistency7d ? (
<ConsistencyStrip
days={target.consistency7d}
daysInRange={target.daysInRange7d ?? 0}
daysLogged={target.daysLogged7d ?? 0}
/>
) : target.insufficientData ? (
<p
className="text-muted-foreground text-xs italic"
data-slot="target-insufficient-data"
>
{t("targets.consistency.insufficientData")}
</p>
) : null}
{/* Row 5: recency + streak chips. Both conditional. */}
{(showLastMet || showStreak) && (
<div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
{showLastMet && target.lastMetGoalAt && (
<span data-slot="target-last-met">
{t("targets.card.lastMet", {
when: formatRelativeDay(target.lastMetGoalAt, t),
})}
</span>
)}
{showStreak && (
<span
className="text-foreground inline-flex items-center gap-1.5 rounded-full bg-(--dracula-green)/12 px-2 py-0.5 font-medium ring-1 ring-(--dracula-green)/30"
data-slot="target-streak"
>
<span
className="size-1.5 rounded-full bg-(--dracula-green)"
aria-hidden="true"
/>
{t("targets.card.streak", { count: String(target.streakDays) })}
</span>
)}
</div>
)}
{/* Medication breakdown (regimen-specific detail) */}
{isMedicationCompliance && medicationBreakdown.length > 0 && (
<div className="space-y-1.5">
<p className="text-muted-foreground text-xs">
{t("targets.compliancePerMedication")}
</p>
<div className="space-y-1">
{medicationBreakdown.map((medication) => (
<div
key={medication.name}
className="text-muted-foreground flex items-center justify-between gap-2 text-xs"
>
<span className="truncate">{medication.name}</span>
<span className="shrink-0">
{medication.compliance7.toFixed(1)}% (7T) ·{" "}
{medication.compliance30.toFixed(1)}% (30T)
</span>
</div>
))}
</div>
</div>
)}
{/* Row 6: footer. Mobile-first reflow:
- default (<640px): stack vertically; the Coach CTA
spans full width so the touch target is generous, the
source link sits beneath it right-aligned.
- sm+ (≥640px): horizontal row, Coach left + source right.
`mt-auto` pins to card bottom so grid cells align. */}
<div className="mt-auto flex flex-col items-stretch gap-2 pt-1 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
{aiEnabled && (
<TargetCoachButton
prefill={coachPrefill}
sources={coachSources}
onAskCoach={onAskCoach}
aiEnabled={aiEnabled}
className="w-full justify-center sm:-ml-2 sm:w-auto sm:justify-start"
/>
)}
{sourceLink ? (
<a
href={sourceLink}
target="_blank"
rel="noopener noreferrer"
className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 self-end text-xs sm:ml-auto sm:self-auto"
>
<span>{target.source}</span>
<ExternalLink className="size-3" aria-hidden="true" />
</a>
) : (
<span className="text-muted-foreground self-end text-xs sm:ml-auto sm:self-auto">
{target.source}
</span>
)}
</div>
</CardContent>
{/* v1.4.25 W3f — edit dialog mounted alongside the card. The
dialog is portalled by Radix so it isn't constrained by the
card's overflow / z-index. Only one card's dialog ever opens
at a time (each card owns its own boolean state). */}
<TargetEditSheet
targetType={target.type}
targetLabel={titleLabel}
unit={target.unit}
initialRange={target.range}
initialDiastolicRange={bpDiastolic?.range ?? null}
open={editOpen}
onOpenChange={setEditOpen}
/>
</Card>
);
}
@@ -0,0 +1,75 @@
"use client";
import { Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import type { CoachScope, CoachScopeSource } from "@/lib/ai/coach/types";
/**
* v1.4.25 W3e — per-card "Ask Coach about this" CTA.
*
* Only renders when the parent passes `aiEnabled === true`. The gate
* lives one level up (the `TargetsPage` reads `/api/insights/provider-chain`
* and threads the flag down); this component is dumb on purpose so
* tests can pin both branches.
*
* On click the button fires `onAskCoach({ prefill, scope })`. The
* parent owns the `CoachDrawer` state; this button doesn't know about
* the drawer at all.
*/
export interface TargetCoachButtonProps {
/**
* Pre-formatted question to seed the Coach drawer's composer. Locale
* pre-resolved by the caller (per `buildTargetPrompt(targetType,
* locale)` in `src/lib/ai/coach/target-prompts.ts`).
*/
prefill: string;
/**
* The single CoachScope.sources entry to narrow the snapshot to this
* metric. Empty array means "do not narrow"; the caller decides.
*/
sources: ReadonlyArray<CoachScopeSource>;
onAskCoach: (payload: { prefill: string; scope: CoachScope }) => void;
/**
* Renders ONLY when this is true. The parent gates on
* `chainData?.activeProvider != null` so a user with no AI provider
* configured never sees a button that opens an empty drawer.
*/
aiEnabled: boolean;
className?: string;
}
export function TargetCoachButton({
prefill,
sources,
onAskCoach,
aiEnabled,
className,
}: TargetCoachButtonProps) {
const { t } = useTranslations();
if (!aiEnabled) return null;
return (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() =>
onAskCoach({
prefill,
scope: {
sources: [...sources],
window: "last30days",
},
})
}
data-slot="target-coach-cta"
className={className}
>
<Sparkles className="size-3.5" aria-hidden="true" />
<span>{t("targets.coach.cta")}</span>
</Button>
);
}
@@ -0,0 +1,463 @@
"use client";
import { useId, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { RotateCcw } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useTranslations } from "@/lib/i18n/context";
import {
METRIC_BOUNDS,
type ThresholdMetric,
type EffectiveRange,
} from "@/lib/analytics/effective-range";
/**
* v1.4.25 W3f — per-card edit affordance for the Zielwerte cards.
*
* Marc directive 2026-05-14: the per-card cog pattern (Dashboard charts →
* Insights sub-pages → now Zielwerte) must be consistent. After the W3e
* redesign the target cards lost their edit entry point — this dialog
* closes that gap. Tapping the cog top-right of any TargetCard opens
* this sheet; the user adjusts the min/max for the underlying threshold
* metric, hits Save, and every surface that consumes
* `getEffectiveRange()` (dashboard bands, doctor-report, /targets
* itself) updates on the next query refetch.
*
* Server contract: PUT /api/user/thresholds with a partial map
* `{ [metric]: { min, max } }`. The endpoint validates the values
* against `METRIC_BOUNDS` and persists them under
* `User.thresholdsJson`. The cached query `["user", "thresholds"]` is
* invalidated on success so the same dialog re-opens with the new
* values.
*
* Visual contract: a small Dialog (not a Sheet drawer) so the
* interaction reads as "I'm editing one specific metric, not a global
* settings page". Mobile-first: full-width buttons under sm:, inline
* row from sm: up.
*
* Mapping target-card type → ThresholdMetric:
* BLOOD_PRESSURE_IN_TARGET / BMI / MOOD_SCORE / MOOD_STABILITY /
* MEDICATION_COMPLIANCE / BLOOD_GLUCOSE_RANDOM
* → no editable threshold (the metric is a derived score). The
* cog still renders (consistency rule) but disables the Save
* button + shows an explanatory caption that this card derives
* from other metrics.
* BLOOD_PRESSURE
* → edits BOTH BLOOD_PRESSURE_SYS and BLOOD_PRESSURE_DIA in a
* single Save round-trip; the parent page receives the
* diastolic range from the targets API.
* Everything else maps 1:1 to the same enum literal.
*/
const TARGET_TYPE_TO_METRIC: Record<string, ThresholdMetric | null> = {
WEIGHT: "WEIGHT",
PULSE: "PULSE",
SLEEP_DURATION: "SLEEP_DURATION",
BODY_FAT: "BODY_FAT",
ACTIVITY_STEPS: "ACTIVITY_STEPS",
BLOOD_GLUCOSE_FASTING: "BLOOD_GLUCOSE_FASTING",
BLOOD_GLUCOSE_POSTPRANDIAL: "BLOOD_GLUCOSE_POSTPRANDIAL",
BLOOD_GLUCOSE_RANDOM: "BLOOD_GLUCOSE_RANDOM",
BLOOD_GLUCOSE_BEDTIME: "BLOOD_GLUCOSE_BEDTIME",
// BLOOD_PRESSURE handled specially with both sys + dia.
// BMI / MOOD_SCORE / MOOD_STABILITY / MEDICATION_COMPLIANCE /
// BLOOD_PRESSURE_IN_TARGET — derived, no editable threshold.
};
interface CurrentRange {
min: number;
max: number;
}
interface ThresholdsApiResponse {
effective: Record<ThresholdMetric, EffectiveRange>;
overrides: Partial<Record<ThresholdMetric, CurrentRange>>;
}
export interface TargetEditSheetProps {
targetType: string;
targetLabel: string;
unit: string;
/**
* Current sys/dia ranges for BP. Threaded from the page; the dialog
* uses them to seed BOTH inputs when target.type === BLOOD_PRESSURE.
*/
initialRange: CurrentRange | null;
initialDiastolicRange?: CurrentRange | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function TargetEditSheet(props: TargetEditSheetProps) {
// v1.4.25 W3f — only mount the body (and its TanStack Query hooks)
// when the dialog is open. This keeps the parent <TargetCard>
// test-friendly: existing tests can render the card without
// standing up a QueryClientProvider, and the hooks only execute
// once the user actually clicks the cog.
return (
<Dialog open={props.open} onOpenChange={props.onOpenChange}>
{props.open ? <TargetEditSheetBody {...props} /> : null}
</Dialog>
);
}
function TargetEditSheetBody({
targetType,
targetLabel,
unit,
initialRange,
initialDiastolicRange,
onOpenChange,
}: TargetEditSheetProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const isBp = targetType === "BLOOD_PRESSURE";
const metric = TARGET_TYPE_TO_METRIC[targetType] ?? null;
const isDerivedMetric = !isBp && metric == null;
// Lazy-load the thresholds payload so the dialog also catches any
// already-persisted override even when the seeded `initialRange`
// came from the targets API (which can paint a different in-band
// tone vs. the persisted override). The body only mounts when the
// dialog is open, so we don't need a separate `enabled` flag.
const { data: thresholdsData } = useQuery({
queryKey: ["user", "thresholds"],
queryFn: async () => {
const res = await fetch("/api/user/thresholds");
if (!res.ok) throw new Error("failed");
const json = await res.json();
return json.data as ThresholdsApiResponse;
},
});
// Seed input strings from override → initialRange → default bound.
// We use strings so the user can type a partial number (e.g. "12") without
// the input snapping back to a parsed value.
const seedRange = (
m: ThresholdMetric | null,
fallback: CurrentRange | null,
) => {
if (m && thresholdsData?.overrides?.[m]) {
return thresholdsData.overrides[m]!;
}
if (fallback) return fallback;
if (m) {
const bounds = METRIC_BOUNDS[m];
return { min: bounds.min, max: bounds.max };
}
return { min: 0, max: 100 };
};
const primary = seedRange(isBp ? "BLOOD_PRESSURE_SYS" : metric, initialRange);
const secondary = isBp
? seedRange("BLOOD_PRESSURE_DIA", initialDiastolicRange ?? null)
: null;
// The body only mounts when open=true (see the wrapper above), so
// the initial useState seed is already correct — no setState-inside-
// useEffect dance needed. When `thresholdsData` arrives async, we
// use it as the *displayed* fallback whenever the user hasn't typed
// anything yet, via the `??` chain below.
const [minStr, setMinStr] = useState<string | null>(null);
const [maxStr, setMaxStr] = useState<string | null>(null);
const [diaMinStr, setDiaMinStr] = useState<string | null>(null);
const [diaMaxStr, setDiaMaxStr] = useState<string | null>(null);
// Display values: user-edited string (if any) wins, otherwise we
// surface the freshest seeded value derived from the
// `thresholdsData` query + the parent-provided `initialRange`.
const displayMin = minStr ?? String(primary.min);
const displayMax = maxStr ?? String(primary.max);
const displayDiaMin = diaMinStr ?? (secondary ? String(secondary.min) : "");
const displayDiaMax = diaMaxStr ?? (secondary ? String(secondary.max) : "");
// Focus management — the first input gets focus when the dialog
// opens, matching the Dashboard chart cog's open-on-focus pattern.
const firstInputRef = useRef<HTMLInputElement | null>(null);
const dialogContentId = useId();
const updateMutation = useMutation({
mutationFn: async (
payload: Partial<Record<ThresholdMetric, CurrentRange>>,
) => {
const res = await fetch("/api/user/thresholds", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
const err = await res.json().catch(() => null);
throw new Error(err?.error ?? "save failed");
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user", "thresholds"] });
queryClient.invalidateQueries({ queryKey: ["insights", "targets"] });
queryClient.invalidateQueries({ queryKey: ["analytics"] });
queryClient.invalidateQueries({ queryKey: ["insights"] });
toast.success(t("targets.edit.saveSuccess"));
onOpenChange(false);
},
onError: (err) =>
toast.error(
err instanceof Error ? err.message : t("targets.edit.saveError"),
),
});
const resetMutation = useMutation({
mutationFn: async () => {
if (isBp) {
// Reset BOTH sys + dia.
for (const m of ["BLOOD_PRESSURE_SYS", "BLOOD_PRESSURE_DIA"] as const) {
const res = await fetch(`/api/user/thresholds?metric=${m}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("reset failed");
}
return;
}
if (!metric) return;
const res = await fetch(`/api/user/thresholds?metric=${metric}`, {
method: "DELETE",
});
if (!res.ok) throw new Error("reset failed");
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["user", "thresholds"] });
queryClient.invalidateQueries({ queryKey: ["insights", "targets"] });
queryClient.invalidateQueries({ queryKey: ["analytics"] });
queryClient.invalidateQueries({ queryKey: ["insights"] });
toast.success(t("targets.edit.resetSuccess"));
onOpenChange(false);
},
onError: () => toast.error(t("targets.edit.saveError")),
});
const busy = updateMutation.isPending || resetMutation.isPending;
const minNum = parseFloat(displayMin);
const maxNum = parseFloat(displayMax);
const diaMinNum = parseFloat(displayDiaMin);
const diaMaxNum = parseFloat(displayDiaMax);
const primaryBounds = isBp
? METRIC_BOUNDS.BLOOD_PRESSURE_SYS
: metric
? METRIC_BOUNDS[metric]
: null;
const secondaryBounds = isBp ? METRIC_BOUNDS.BLOOD_PRESSURE_DIA : null;
const primaryValid =
primaryBounds != null &&
Number.isFinite(minNum) &&
Number.isFinite(maxNum) &&
minNum >= primaryBounds.min &&
maxNum <= primaryBounds.max &&
minNum < maxNum;
const secondaryValid =
!isBp ||
(secondaryBounds != null &&
Number.isFinite(diaMinNum) &&
Number.isFinite(diaMaxNum) &&
diaMinNum >= secondaryBounds.min &&
diaMaxNum <= secondaryBounds.max &&
diaMinNum < diaMaxNum);
const canSave = !isDerivedMetric && primaryValid && secondaryValid && !busy;
const handleSave = () => {
if (!canSave) return;
if (isBp) {
updateMutation.mutate({
BLOOD_PRESSURE_SYS: { min: minNum, max: maxNum },
BLOOD_PRESSURE_DIA: { min: diaMinNum, max: diaMaxNum },
});
return;
}
if (!metric) return;
updateMutation.mutate({ [metric]: { min: minNum, max: maxNum } });
};
const hasOverride = isBp
? Boolean(
thresholdsData?.overrides?.BLOOD_PRESSURE_SYS ||
thresholdsData?.overrides?.BLOOD_PRESSURE_DIA,
)
: metric
? Boolean(thresholdsData?.overrides?.[metric])
: false;
return (
<DialogContent
className="sm:max-w-md"
data-slot="target-edit-sheet"
data-target-type={targetType}
onOpenAutoFocus={(event) => {
// Defer to the first input ref so the user lands on the min
// field rather than the close X (default Radix behaviour
// focuses the first focusable child).
if (firstInputRef.current) {
event.preventDefault();
firstInputRef.current.focus();
firstInputRef.current.select();
}
}}
aria-describedby={dialogContentId}
>
<DialogHeader>
<DialogTitle>
{t("targets.edit.title", { metric: targetLabel })}
</DialogTitle>
<DialogDescription id={dialogContentId}>
{isDerivedMetric
? t("targets.edit.derivedHint")
: t("targets.edit.description", { unit })}
</DialogDescription>
</DialogHeader>
{!isDerivedMetric && primaryBounds && (
<div className="space-y-4">
<div
className="grid grid-cols-1 gap-3 sm:grid-cols-2"
data-slot="target-edit-primary-row"
>
<div className="space-y-1">
<Label htmlFor="target-edit-min" className="text-xs">
{isBp
? t("targets.edit.systolicMin")
: t("targets.edit.minLabel")}
</Label>
<Input
id="target-edit-min"
ref={firstInputRef}
type="number"
step={targetType === "ACTIVITY_STEPS" ? 100 : 0.1}
min={primaryBounds.min}
max={primaryBounds.max}
value={displayMin}
onChange={(e) => setMinStr(e.target.value)}
disabled={busy}
data-slot="target-edit-min-input"
/>
</div>
<div className="space-y-1">
<Label htmlFor="target-edit-max" className="text-xs">
{isBp
? t("targets.edit.systolicMax")
: t("targets.edit.maxLabel")}
</Label>
<Input
id="target-edit-max"
type="number"
step={targetType === "ACTIVITY_STEPS" ? 100 : 0.1}
min={primaryBounds.min}
max={primaryBounds.max}
value={displayMax}
onChange={(e) => setMaxStr(e.target.value)}
disabled={busy}
data-slot="target-edit-max-input"
/>
</div>
</div>
{isBp && secondaryBounds && (
<div
className="grid grid-cols-1 gap-3 sm:grid-cols-2"
data-slot="target-edit-secondary-row"
>
<div className="space-y-1">
<Label htmlFor="target-edit-dia-min" className="text-xs">
{t("targets.edit.diastolicMin")}
</Label>
<Input
id="target-edit-dia-min"
type="number"
step={0.1}
min={secondaryBounds.min}
max={secondaryBounds.max}
value={displayDiaMin}
onChange={(e) => setDiaMinStr(e.target.value)}
disabled={busy}
data-slot="target-edit-dia-min-input"
/>
</div>
<div className="space-y-1">
<Label htmlFor="target-edit-dia-max" className="text-xs">
{t("targets.edit.diastolicMax")}
</Label>
<Input
id="target-edit-dia-max"
type="number"
step={0.1}
min={secondaryBounds.min}
max={secondaryBounds.max}
value={displayDiaMax}
onChange={(e) => setDiaMaxStr(e.target.value)}
disabled={busy}
data-slot="target-edit-dia-max-input"
/>
</div>
</div>
)}
<p className="text-muted-foreground text-xs">
{t("targets.edit.boundsHint", {
min: String(primaryBounds.min),
max: String(primaryBounds.max),
unit: primaryBounds.unit,
})}
</p>
</div>
)}
<DialogFooter className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
{hasOverride ? (
<Button
variant="ghost"
size="sm"
onClick={() => resetMutation.mutate()}
disabled={busy}
data-slot="target-edit-reset"
>
<RotateCcw className="mr-2 h-3.5 w-3.5" />
{t("targets.edit.resetToDefault")}
</Button>
) : (
<span aria-hidden="true" />
)}
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:gap-2">
<Button
variant="outline"
size="sm"
onClick={() => onOpenChange(false)}
disabled={busy}
>
{t("common.cancel")}
</Button>
<Button
size="sm"
onClick={handleSave}
disabled={!canSave}
data-slot="target-edit-save"
>
{t("common.save")}
</Button>
</div>
</DialogFooter>
</DialogContent>
);
}
@@ -0,0 +1,91 @@
"use client";
import { CheckCircle2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
/**
* v1.4.25 W3e — page-level summary line.
*
* "4 of 6 targets met this week" (DE: "4 von 6 Zielwerten diese Woche
* erreicht"). When every target hits the bar we surface a calm check
* mark + "All N targets met this week" copy — no animation, no
* celebration. Marc directive: stay quieter than the v1.4.20 Insights
* hero.
*
* Optional streak highlight chip when one metric has a current ≥ 3 day
* streak; the metric label is resolved from the targets.label.* i18n
* map so it renders in the user's locale.
*/
export interface TargetsSummaryHeaderProps {
targetsMetThisWeek: number;
totalTargets: number;
streakHighlight: { metric: string; days: number } | null;
className?: string;
}
export function TargetsSummaryHeader({
targetsMetThisWeek,
totalTargets,
streakHighlight,
className,
}: TargetsSummaryHeaderProps) {
const { t } = useTranslations();
if (totalTargets === 0) return null;
const allMet = targetsMetThisWeek === totalTargets;
const headline = allMet
? t("targets.summary.weekTitleAll", { total: String(totalTargets) })
: t("targets.summary.weekTitle", {
met: String(targetsMetThisWeek),
total: String(totalTargets),
});
let highlightCopy: string | null = null;
if (streakHighlight && streakHighlight.days >= 3) {
const metricLabel = t(`targets.label.${streakHighlight.metric}`);
const resolvedMetric =
metricLabel === `targets.label.${streakHighlight.metric}`
? streakHighlight.metric
: metricLabel;
highlightCopy = t("targets.summary.streakHighlight", {
count: String(streakHighlight.days),
metric: resolvedMetric,
});
}
return (
<section
data-slot="targets-summary-header"
className={cn(
"flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3",
className,
)}
>
<div className="flex items-center gap-2">
{allMet && (
<CheckCircle2
className="size-4 shrink-0 text-[var(--dracula-green)]"
aria-hidden="true"
/>
)}
<p
className="text-foreground text-sm font-medium"
data-slot="targets-summary-title"
>
{headline}
</p>
</div>
{highlightCopy && (
<span
className="text-muted-foreground text-xs sm:before:mx-1 sm:before:content-['·']"
data-slot="targets-summary-streak"
>
{highlightCopy}
</span>
)}
</section>
);
}