mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
refactor(targets): retire the standalone Targets page
The standalone /targets (Zielwerte) page is retired. Target editing moved inline onto the Insights metric pages in v1.8.6 — each metric's reference panel mounts the editor and writes the same PUT /api/user/thresholds, reading the same /api/insights/targets payload. The page carried a deprecation notice and had already dropped out of the navigation, so removing it is a UI-only change: no data model, API route, or inline editor moves. Remove the page and its tests, the components reachable only from it (target card, per-card coach button, summary header, target prompt / scope helpers, coach-handoff hook), the now-dead /zielwerte→/targets proxy redirect, and the orphaned targets.* i18n keys across all six locales. Repoint the handful of code comments that pointed readers at the page to the inline Insights panel, and prune the two coach gate-inventory allowlists plus the queryKey factory guard root that named the removed files. The reference panel keeps the range bar, consistency strip, status pill, edit sheet, and source-link helpers — those are the live editing surface now. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit 7f842c5620087127e980fe22a56133135b7c0531)
This commit is contained in:
1 parent
8c316ee3b0
commit
d880385635
33 files changed
+51
-2886
No files matched your search
@@ -423,8 +423,8 @@ export function TrendCard({
|
||||
{/* v1.4.28 FB-C2 — the all-time third sub-value retired
|
||||
alongside the `avgAllTime*` props. The BD-Zielbereich
|
||||
tile was the only consumer; the same number stays
|
||||
visible on the `/targets` Blutdruck card with full
|
||||
context. Every dashboard tile now ships the same two
|
||||
visible on the Insights blood-pressure target panel with
|
||||
full context. Every dashboard tile now ships the same two
|
||||
sub-rows. */}
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -18,18 +18,16 @@ import { getTargetSourceLink } from "@/lib/targets/source-link";
|
||||
* v1.8.0 → v1.8.5 — surface the per-metric target reference panel on each
|
||||
* insights category page, directly beneath the chart / assessment.
|
||||
*
|
||||
* The data is the same `/api/insights/targets` payload that powers the
|
||||
* `/targets` editing surface — this component reads the shared
|
||||
* `queryKeys.insightsTargets()` cache, so on a session that has already
|
||||
* visited `/targets` the read is free, and on a cold sub-page it warms a
|
||||
* cache the `/targets` page then reuses. We never recompute the ranges
|
||||
* here: the route is the single source of truth for the age-based ESH
|
||||
* blood-pressure band, the WHO weight / BMI band, the Karvonen pulse
|
||||
* band, the AASM sleep band, the ADA / DDG glucose bands, and the
|
||||
* medication / mood targets.
|
||||
* The data is the `/api/insights/targets` payload, read through the
|
||||
* shared `queryKeys.insightsTargets()` cache so warm sessions pay
|
||||
* nothing and a cold sub-page warms the cache its siblings reuse. We
|
||||
* never recompute the ranges here: the route is the single source of
|
||||
* truth for the age-based ESH blood-pressure band, the WHO weight / BMI
|
||||
* band, the Karvonen pulse band, the AASM sleep band, the ADA / DDG
|
||||
* glucose bands, and the medication / mood targets.
|
||||
*
|
||||
* v1.8.5 W5 — the panel grew from a one-line range card into a compact
|
||||
* reference panel that ports the context the `/targets` card carries:
|
||||
* The panel is a compact reference panel carrying the full target
|
||||
* context:
|
||||
*
|
||||
* • Row 1: target range string + `<TargetStatusPill>` + source link
|
||||
* (the "what is the band / what is it based on" answer).
|
||||
@@ -38,13 +36,13 @@ import { getTargetSourceLink } from "@/lib/targets/source-link";
|
||||
* • Row 3: in-target share % + the 30-day average.
|
||||
* • Row 4: `<ConsistencyStrip>` — the last seven days at a glance.
|
||||
* • Footer: an "Adjust target range" button that opens the
|
||||
* `<TargetEditSheet>` inline (v1.8.6 — the `/targets` page is
|
||||
* deprecated, so the editor mounts here rather than routing).
|
||||
* `<TargetEditSheet>` inline — this panel is the home of
|
||||
* target editing.
|
||||
*
|
||||
* Each insights slug maps to one target `type`, except blood glucose
|
||||
* which maps to up to four per-context cards (fasting / postprandial /
|
||||
* random / bedtime) — those carry mg/dL canonical values that we convert
|
||||
* to the user's display unit exactly like the `/targets` page does.
|
||||
* to the user's display unit.
|
||||
*/
|
||||
|
||||
interface TargetRange {
|
||||
@@ -146,8 +144,8 @@ export function MetricTargetSummary({ slug }: MetricTargetSummaryProps) {
|
||||
if ((!targetType && !isGlucose) || !data) return null;
|
||||
|
||||
// Glucose: one panel per logged context, converting the canonical
|
||||
// mg/dL values to the user's display unit exactly like the /targets
|
||||
// page. The route's per-context labels are i18n keys, so resolve them.
|
||||
// mg/dL values to the user's display unit. The route's per-context
|
||||
// labels are i18n keys, so resolve them.
|
||||
if (isGlucose) {
|
||||
const displayUnit = resolveGlucoseUnit(data.profile?.glucoseUnit ?? null);
|
||||
const convert = (v: number | null) =>
|
||||
@@ -222,11 +220,10 @@ function TargetReferencePanel({
|
||||
}: TargetReferencePanelProps) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
// v1.8.6 — the `/targets` page is deprecated; the per-metric editor
|
||||
// moved here. The button below opens the same self-contained
|
||||
// `<TargetEditSheet>` the targets card mounts, seeded with this
|
||||
// metric's type / unit / range (and the diastolic range for BP). The
|
||||
// sheet writes `PUT /api/user/thresholds` and invalidates the
|
||||
// The per-metric editor lives here. The button below opens a
|
||||
// self-contained `<TargetEditSheet>`, seeded with this metric's
|
||||
// type / unit / range (and the diastolic range for BP). The sheet
|
||||
// writes `PUT /api/user/thresholds` and invalidates the
|
||||
// `insightsTargets()` cache on save, so the panel repaints in place.
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
|
||||
@@ -261,7 +258,7 @@ function TargetReferencePanel({
|
||||
|
||||
// In-target share: fraction of logged days in the green band over the
|
||||
// last 30. Suppressed when the route flagged insufficient data so the
|
||||
// sub-page mirrors the `/targets` strip exactly.
|
||||
// sub-page suppresses the share line.
|
||||
const showShare = !target.insufficientData && target.daysLogged30d > 0;
|
||||
const sharePct = showShare
|
||||
? Math.round((target.daysInRange30d / target.daysLogged30d) * 100)
|
||||
|
||||
@@ -39,10 +39,9 @@ interface NavLink {
|
||||
// Order is preserved relative to the v1.4.15 bottom-nav so muscle
|
||||
// memory keeps working for the four core actions.
|
||||
//
|
||||
// v1.8.6 — the Targets (Zielwerte) page is deprecated: target editing
|
||||
// moved inline into Insights, so its overflow entry is gone. The page
|
||||
// stays routable (the `/zielwerte`→`/targets` proxy redirect remains)
|
||||
// but no longer appears in the menu.
|
||||
// v1.9.0 — the standalone Targets (Zielwerte) page is retired. Target
|
||||
// editing lives inline on the Insights metric pages (the per-metric
|
||||
// reference panel mounts the target editor), so there is no nav entry.
|
||||
const PRIMARY: ReadonlyArray<NavLink> = [
|
||||
{ href: "/", tKey: "nav.dashboard", icon: Home },
|
||||
{ href: "/measurements", tKey: "nav.measurements", icon: Activity },
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
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";
|
||||
import { DEFAULT_ASSISTANT_FLAGS } from "@/hooks/use-feature-flags";
|
||||
|
||||
// v1.4.37 W4a item 9 — when the operator disables the Coach feature
|
||||
// flag globally, the per-card CTA must disappear. The hook reads from
|
||||
// QueryClientContext but falls back to the all-on default in SSR;
|
||||
// the flag-off path needs an explicit mock so the test can drive the
|
||||
// negative case without a QueryClientProvider.
|
||||
vi.mock("@/hooks/use-feature-flags", async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import("@/hooks/use-feature-flags")
|
||||
>("@/hooks/use-feature-flags");
|
||||
return {
|
||||
...actual,
|
||||
useFeatureFlags: vi.fn(() => actual.DEFAULT_ASSISTANT_FLAGS),
|
||||
};
|
||||
});
|
||||
|
||||
const { useFeatureFlags } = await import("@/hooks/use-feature-flags");
|
||||
|
||||
/**
|
||||
* 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"');
|
||||
});
|
||||
|
||||
// v1.4.37 W4a item 9 — operator-level feature flag.
|
||||
it("suppresses the Coach CTA when the global Coach flag is OFF", () => {
|
||||
// Swap the mock for this case only — flag-off should hide the
|
||||
// CTA regardless of the user-level aiEnabled state. Restore the
|
||||
// all-on default so the rest of the suite doesn't see a leaked
|
||||
// mock state.
|
||||
vi.mocked(useFeatureFlags).mockReturnValueOnce({
|
||||
...DEFAULT_ASSISTANT_FLAGS,
|
||||
coach: false,
|
||||
});
|
||||
const html = render({
|
||||
target: fullDataTarget,
|
||||
aiEnabled: true,
|
||||
onAskCoach: vi.fn(),
|
||||
});
|
||||
expect(html).not.toContain('data-slot="target-coach-cta"');
|
||||
});
|
||||
|
||||
it("renders the Coach CTA when both aiEnabled AND the global Coach flag are ON", () => {
|
||||
// Positive control: the default-mock returns the all-on flag set,
|
||||
// so the CTA should mount when aiEnabled is also true.
|
||||
const html = render({
|
||||
target: fullDataTarget,
|
||||
aiEnabled: true,
|
||||
onAskCoach: vi.fn(),
|
||||
});
|
||||
expect(html).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[^"]*"/,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
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 (the maintainer's rule:
|
||||
* no broken-button state for users with no 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"');
|
||||
// v1.4.28 FB-L1 — the affordance is now icon-only; the label
|
||||
// survives as an aria-label + title so screen readers + tooltips
|
||||
// still surface "Ask Coach" / "Coach fragen".
|
||||
expect(html).toContain('aria-label="Ask Coach"');
|
||||
expect(html).toContain('title="Ask Coach"');
|
||||
// No visible text label — only the Sparkles glyph.
|
||||
expect(html).not.toMatch(/>Ask Coach</);
|
||||
// UI-H2 — the Coach-launch glyph is one Sparkles vocabulary
|
||||
// across hero strip, inline pill, layout FAB and per-card icon.
|
||||
expect(html).toMatch(/lucide-sparkles/i);
|
||||
expect(html).not.toMatch(/lucide-message-circle/i);
|
||||
});
|
||||
|
||||
it("lifts the tap target to the 44 px WCAG 2.5.5 floor", () => {
|
||||
// The icon variant alone ships `size-10` (40 px); the per-card
|
||||
// Coach button rides `min-h-11 min-w-11` on top so the hit
|
||||
// surface matches the medication-history and Coach drawer
|
||||
// buttons. Pinning the class so a future refactor can't drop
|
||||
// back to the 40 px shadcn default.
|
||||
const html = render({ ...baseProps, aiEnabled: true });
|
||||
const trigger = html.match(
|
||||
/<button[^>]*data-slot="target-coach-cta"[^>]*>/,
|
||||
);
|
||||
expect(trigger).not.toBeNull();
|
||||
expect(trigger?.[0]).toContain("min-h-11");
|
||||
expect(trigger?.[0]).toContain("min-w-11");
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
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("");
|
||||
});
|
||||
});
|
||||
@@ -9,10 +9,6 @@ import {
|
||||
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
|
||||
|
||||
@@ -1,578 +0,0 @@
|
||||
"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 { useFeatureFlags } from "@/hooks/use-feature-flags";
|
||||
import { moodStabilityLabel } from "@/lib/targets/mood-stability-label";
|
||||
import { ConsistencyStrip } from "./consistency-strip";
|
||||
import { RangeBar } from "./range-bar";
|
||||
import {
|
||||
TargetStatusPill,
|
||||
statusGroupForCategory,
|
||||
translateStatus,
|
||||
} from "./target-status-pill";
|
||||
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",
|
||||
};
|
||||
|
||||
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.37 W4a item 9 — when the operator disables the Coach
|
||||
// feature flag globally, every per-card "Ask the coach" CTA must
|
||||
// disappear (not greyed-out, not a placeholder). The card's
|
||||
// existing `aiEnabled` gate guards on the user-level provider
|
||||
// chain; this flag guards on the operator-level feature switch.
|
||||
// Both must be ON for the CTA to mount.
|
||||
const flags = useFeatureFlags();
|
||||
|
||||
// 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 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}
|
||||
// v1.4.37 W4a item 3 — override the Card primitive's default
|
||||
// `gap-4 md:gap-6` to `gap-3 md:gap-4`. The default gap stacked
|
||||
// on top of the CardHeader's `pb-3` rendered a ~36 px dead
|
||||
// space between "Blutdruck optimal" and the headline number;
|
||||
// the tighter rhythm pulls the value back under the label so
|
||||
// the card reads as one unit instead of two separated blocks.
|
||||
className="flex h-full flex-col gap-3 md:gap-4"
|
||||
>
|
||||
<CardHeader className="gap-2 pb-0 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">
|
||||
{target.classification ? (
|
||||
<TargetStatusPill
|
||||
classification={target.classification}
|
||||
range={target.range}
|
||||
unit={target.unit}
|
||||
source={target.source}
|
||||
/>
|
||||
) : 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. v1.4.28 FB-L1 — the Coach CTA is now an
|
||||
icon-only affordance (chat-bubble glyph + aria-label), so
|
||||
the row stays horizontal at every breakpoint: icon left,
|
||||
source link right. `mt-auto` pins to card bottom so grid
|
||||
cells align. */}
|
||||
<div className="mt-auto flex flex-row items-center justify-between gap-3 pt-1">
|
||||
{aiEnabled && flags.coach && (
|
||||
<TargetCoachButton
|
||||
prefill={coachPrefill}
|
||||
sources={coachSources}
|
||||
onAskCoach={onAskCoach}
|
||||
aiEnabled={aiEnabled}
|
||||
className="-ml-2"
|
||||
/>
|
||||
)}
|
||||
{sourceLink ? (
|
||||
<a
|
||||
href={sourceLink}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground hover:text-foreground ml-auto inline-flex items-center gap-1 text-xs"
|
||||
>
|
||||
<span>{target.source}</span>
|
||||
<ExternalLink className="size-3" aria-hidden="true" />
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground ml-auto text-xs">
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { Sparkles } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
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.
|
||||
*
|
||||
* v1.4.28 R3c FB-L1 — collapsed to an icon-only affordance. The card
|
||||
* footer was carrying a labelled pill ("Coach fragen"); on a card with
|
||||
* a status pill, range bar, consistency strip, headline number, edit
|
||||
* cog and a source link, the labelled pill dominated the visual
|
||||
* hierarchy. Dropping the label retains the affordance via the
|
||||
* Sparkles glyph + `aria-label` while shrinking the optical weight
|
||||
* to a per-card icon button. UI-H2 — the glyph is the same Sparkles
|
||||
* the hero strip, the inline pill and the layout-level FAB use, so
|
||||
* the per-card Coach launch reads on one icon vocabulary across the
|
||||
* app.
|
||||
*/
|
||||
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 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;
|
||||
|
||||
const accessibleLabel = t("targets.coach.cta");
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
onAskCoach({
|
||||
prefill,
|
||||
scope: {
|
||||
sources: [...sources],
|
||||
window: "last30days",
|
||||
},
|
||||
})
|
||||
}
|
||||
data-slot="target-coach-cta"
|
||||
aria-label={accessibleLabel}
|
||||
title={accessibleLabel}
|
||||
// Lift the icon button to the 44 px WCAG 2.5.5 floor. The
|
||||
// shadcn `icon` variant ships `size-10` (40 px); the project
|
||||
// floor is 44 px (matches the medication-history button and the
|
||||
// Coach drawer cluster). Glyph stays `size-4`.
|
||||
className={cn("min-h-11 min-w-11", className)}
|
||||
>
|
||||
<Sparkles className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -18,16 +18,12 @@ import {
|
||||
} 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.
|
||||
* Per-metric target editor, mounted inline on the Insights metric
|
||||
* reference panel (`<MetricTargetSummary>`). The user adjusts the
|
||||
* min/max for the underlying threshold metric, hits Save, and every
|
||||
* surface that consumes `getEffectiveRange()` (dashboard bands,
|
||||
* doctor-report, the Insights panels themselves) updates on the next
|
||||
* query refetch.
|
||||
*
|
||||
* Server contract: PUT /api/user/thresholds with a partial map
|
||||
* `{ [metric]: { min, max } }`. The endpoint validates the values
|
||||
@@ -95,11 +91,11 @@ export interface TargetEditSheetProps {
|
||||
}
|
||||
|
||||
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.
|
||||
// Only mount the body (and its TanStack Query hooks) when the dialog
|
||||
// is open. This keeps the parent reference panel test-friendly:
|
||||
// callers can render the panel without standing up a
|
||||
// QueryClientProvider, and the hooks only execute once the user
|
||||
// actually opens the editor.
|
||||
//
|
||||
// v1.4.27 R4 RC2 — migrated raw <Dialog> → <ResponsiveSheet> so the
|
||||
// bottom-sheet branch sticky-pins reset + cancel + save above the
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
"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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user