Files
HealthLog/src/components/charts/medication-compliance-chart.tsx
T
Marc-André BombeckandClaude Opus 4.7 c3451a4c06 fix(a11y): 44px tap targets + focus-visible on rec-feedback, chart range tabs, export switch (H1/H2/H6/H7)
WCAG 2.5.5 minimum hit-area is 44×44 CSS px and the Wave-C polish set
that as the project floor. Several v1.4.16 surfaces missed it:

- Recommendation thumbs (h-7 = 28 px) — `<RecommendationFeedback>` up
  + down both bumped to `min-h-11 min-w-11` with focus-visible ring.
- Recommendation chevron expand toggle (~24 px, no focus state) —
  `<RecommendationCard>` rec-expand-toggle bumped to `min-h-11
  min-w-11` with focus-visible ring.
- Chart range tabs (7d/30d/90d/All) — `min-h-9 px-2.5` ≈ 36×28 px on
  Pixel 5; bumped to `min-h-11 px-3` across HealthChart, MoodChart,
  MedicationComplianceChart, ComplianceCharts, ComplianceLineChart.
- Medication CSV "include intake history" raw `<input
  type="checkbox">` (16×16, system-blue on iOS Safari) — replaced
  with shadcn `<Switch>` inside a `min-h-11` label so the row is
  properly tappable and visually consistent with every other
  settings toggle.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 03:01:45 +02:00

439 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
/**
* Dashboard medication-compliance chart.
*
* Wired to the `medications` toggle in Settings → Dashboard. Up to v1.4.14
* the toggle existed but the dashboard slot only rendered a static
* placeholder (an icon + the section title), so flipping it on did nothing
* visible. This wrapper shows daily compliance % across all of the user's
* scheduled medications for the last N days, matching the same visual
* pattern the other dashboard charts use (Card surface, Dracula tokens,
* range chips in the header, ReferenceLine target at 100 % goal +
* 80 % minimum-acceptable threshold).
*
* v1.4.16 A6 — feature-parity with the other charts:
* - Computes a 7-day trend chip in the header (signed delta, metric-
* aware sentiment colour: rising compliance → green, falling →
* orange).
* - Adds a 100 % goal ReferenceLine (in addition to the existing 80 %
* minimum-acceptable threshold) so the target range is explicitly
* visualised the way BP/weight charts paint their target zones.
*
* Data source: `GET /api/medications/intake?scope=compliance&days=N`
* already returns `{ date, scheduled, taken }[]`. We aggregate to
* `taken / scheduled * 100` per day; days without any scheduled doses
* are skipped (compliance is undefined for a day with no expected
* intakes — drawing a 0 % point on those would mis-represent the data).
*
* IMPORTANT: keep the recharts primitives as static imports inside
* this wrapper. Phase 4 visual-verify (v1.4.14) proved that wrapping
* individual primitives in `next/dynamic` breaks Recharts'
* `findAllByType` reconciliation; the dashboard's `next/dynamic` for
* the wrapper itself stays intact.
*/
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import {
ResponsiveContainer,
ComposedChart,
Area,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ReferenceLine,
} from "recharts";
import { ArrowDown, ArrowRight, ArrowUp, Loader2, Pill } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/use-auth";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { formatDateShort } from "@/lib/format";
import { cn } from "@/lib/utils";
import { ChartLinearGradient, chartGradientFill } from "./chart-gradient";
import { RichChartTooltip, type RichTooltipRow } from "./chart-tooltip";
import { ChartEmptyState } from "./chart-empty-state";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
interface DailyCompliancePoint {
/** Berlin calendar day, "YYYY-MM-DD". */
date: string;
scheduled: number;
taken: number;
}
interface ChartPoint {
date: string;
rate: number;
timestamp: number;
}
const COLOR_LINE = "var(--dracula-purple)";
const COLOR_GOAL = "var(--dracula-green)";
const COLOR_THRESHOLD = "var(--dracula-yellow)";
/** Days for the range buttons. v1.4.15 keeps this in sync with the
* health-chart range presets so the dashboard reads consistently. */
const RANGE_DAYS = [7, 30, 90] as const;
type RangeDays = (typeof RANGE_DAYS)[number];
/**
* Aggregate daily-compliance points from the `/api/medications/intake`
* compliance scope into chart-ready rows. Days without any expected
* intakes are skipped — compliance is undefined when nothing was due.
*
* Pure & deterministic so the unit test pins exact rates.
*/
export function aggregateMedicationCompliance(
points: DailyCompliancePoint[],
): ChartPoint[] {
return points
.filter((p) => p.scheduled > 0)
.sort((a, b) => a.date.localeCompare(b.date))
.map((p) => {
const [y, m, d] = p.date.split("-").map(Number);
// Anchor the timestamp at noon UTC of the Berlin day so a tooltip
// and tick formatter never disagree across DST boundaries.
const ts = Date.UTC(y, m - 1, d, 12);
const rate = Math.min(100, Math.round((p.taken / p.scheduled) * 100));
return {
date: formatDateShort(new Date(ts), true),
rate,
timestamp: ts,
};
});
}
/**
* Compute the 7-day compliance trend over the last 14 days of data —
* mean of the most-recent 7 daily rates minus the mean of the prior 7
* (or fewer if the user has fewer than 14 days).
*
* Returns `null` when fewer than 2 daily points exist (a single point
* has no trend), or when both halves of the window collapse to < 2
* points (insufficient signal).
*
* Pure & deterministic so unit tests pin the exact delta.
*
* Why "second-half mean − first-half mean" instead of slope-of-line:
* the dashboard tile reports a *delta in percentage points* — a slope
* over 7 days expressed in pp/day would multiply by 7 anyway, and the
* mean-difference variant is more robust to a single outlier day.
*/
export function computeMedicationTrend7d(
points: ChartPoint[],
): { delta: number; direction: "up" | "down" | "stable" } | null {
if (points.length < 2) return null;
// Take the most recent 14 points (sorted ascending in the input
// because aggregateMedicationCompliance sorts by date).
const recent = points.slice(-14);
if (recent.length < 2) return null;
const mid = Math.floor(recent.length / 2);
const firstHalf = recent.slice(0, mid);
const secondHalf = recent.slice(mid);
if (firstHalf.length === 0 || secondHalf.length === 0) return null;
const meanOf = (arr: ChartPoint[]) =>
arr.reduce((s, p) => s + p.rate, 0) / arr.length;
const delta = Math.round((meanOf(secondHalf) - meanOf(firstHalf)) * 10) / 10;
// Same threshold the trend-arrow on tiles uses (~1 pp shift counts
// as movement; below that is "stable" so we don't celebrate noise).
const direction: "up" | "down" | "stable" =
Math.abs(delta) < 1 ? "stable" : delta > 0 ? "up" : "down";
return { delta, direction };
}
interface MedicationComplianceChartProps {
/** Override the visible label, primarily for tests. */
title?: string;
}
export function MedicationComplianceChart({
title,
}: MedicationComplianceChartProps) {
const { isAuthenticated } = useAuth();
const { t } = useTranslations();
const fmt = useFormatters();
const [days, setDays] = useState<RangeDays>(30);
const { data, isLoading } = useQuery({
queryKey: ["medication-compliance-chart", days],
queryFn: async (): Promise<DailyCompliancePoint[]> => {
const res = await fetch(
`/api/medications/intake?scope=compliance&days=${days}`,
);
if (!res.ok) throw new Error("failed to fetch medication compliance");
const json = await res.json();
return json.data as DailyCompliancePoint[];
},
enabled: isAuthenticated,
});
const chartData = useMemo(
() => (data ? aggregateMedicationCompliance(data) : []),
[data],
);
// v1.4.16 A6 — 7-day trend chip. Computed off the *full* range so a
// user toggled to "7 days" still sees a trend (which would otherwise
// be empty if we only used the visible window). The 14-day cap inside
// computeMedicationTrend7d() bounds the comparison window.
const trend = useMemo(() => computeMedicationTrend7d(chartData), [chartData]);
// v1.4.16 A6 — metric-aware sentiment for medication compliance:
// up-good (rising compliance is the desired direction). Mirrors the
// `directionSentiment="up-good"` rule used by the trend-card pulse +
// mood tiles.
const trendColor = ((): string => {
if (!trend || trend.direction === "stable") return "text-muted-foreground";
return trend.direction === "up"
? "text-dracula-green"
: "text-dracula-orange";
})();
const TrendIcon = !trend
? null
: trend.direction === "up"
? ArrowUp
: trend.direction === "down"
? ArrowDown
: ArrowRight;
const formatTrendDelta = (delta: number): string => {
if (Math.abs(delta) < 0.05) return "±0";
const sign = delta > 0 ? "+" : "−";
return `${sign}${fmt.number(Math.abs(delta), 1)}`;
};
const displayTitle = title ?? t("dashboard.medications");
const yAxisFormatter = (value: number) => `${fmt.integer(value)} %`;
const animationsEnabled = !prefersReducedMotion();
// Empty-state guard: if the user has zero scheduled doses across the
// whole window we render the title + a "no data" hint, mirroring how
// the other charts handle the empty case (HealthChart returns null
// entirely; here we keep the surface visible because the toggle is
// explicit user opt-in — silence would feel like a bug).
const hasData = chartData.length > 0;
return (
<div
className="bg-card border-border rounded-xl border p-4 md:p-6"
data-slot="medication-compliance-chart"
>
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-2">
<Pill className="text-muted-foreground h-4 w-4" />
<h3 className="text-sm font-semibold">{displayTitle}</h3>
{/* v1.4.16 A6 — 7-day trend chip (mirror of the BP/weight
chart's bucket-chip). Painted only when the trend is
computable (>= 2 daily points). */}
{trend && TrendIcon ? (
<span
className={cn(
"bg-muted/40 inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium tracking-wide uppercase",
trendColor,
)}
data-slot="medication-trend-chip"
aria-label={`${t("charts.trend7dShort")} ${formatTrendDelta(trend.delta)}`}
>
<TrendIcon className="h-3 w-3" aria-hidden="true" />
<span>{t("charts.trend7dShort")}</span>
<span className="tabular-nums">
{formatTrendDelta(trend.delta)} pp
</span>
</span>
) : null}
</div>
<div className="flex flex-wrap justify-end gap-1">
{RANGE_DAYS.map((r) => (
<Button
key={r}
variant={days === r ? "default" : "ghost"}
size="sm"
className="min-h-11 px-3 text-xs"
onClick={() => setDays(r)}
>
{r}T
</Button>
))}
</div>
</div>
{/* v1.4.16 B1a — sibling SVG <defs> block for SSR-discoverable
gradient. */}
<svg
width={0}
height={0}
aria-hidden="true"
style={{ position: "absolute", pointerEvents: "none" }}
data-slot="chart-gradient-defs"
>
<ChartLinearGradient
id="chart-gradient-medication"
colorVar="--dracula-purple"
/>
</svg>
{isLoading ? (
<div className="flex h-48 items-center justify-center">
<Loader2 className="text-primary h-6 w-6 animate-spin" />
</div>
) : !hasData ? (
<div className="text-muted-foreground flex h-48 items-center justify-center text-sm">
{t("charts.noData")}
</div>
) : chartData.length < 3 ? (
// v1.4.16 B1a — sparse-data placeholder consistent with the
// BP/weight/pulse/mood charts.
<ChartEmptyState
title={t("charts.emptyStateTitle")}
description={t("charts.emptyStateDescription")}
/>
) : (
<div className="h-[240px] touch-pan-y">
<ResponsiveContainer width="100%" height="100%">
<ComposedChart
data={chartData}
margin={{ top: 10, right: 8, bottom: 8, left: 8 }}
>
<defs>
<linearGradient
id="chart-gradient-medication-inline"
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop offset="0%" stopColor={COLOR_LINE} stopOpacity={0.35} />
<stop offset="100%" stopColor={COLOR_LINE} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray="3 3"
stroke="var(--border)"
opacity={0.5}
/>
<XAxis
dataKey="date"
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
interval="preserveStartEnd"
/>
<YAxis
domain={[0, 100]}
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
tickLine={false}
axisLine={false}
width={48}
tickFormatter={yAxisFormatter}
/>
<Tooltip
cursor={{
stroke: "var(--muted-foreground)",
strokeOpacity: 0.3,
strokeDasharray: "3 3",
}}
content={(props) => {
const { active, payload } = props as unknown as {
active?: boolean;
payload?: Array<{
value?: number;
color?: string;
payload?: ChartPoint;
}>;
};
if (!active || !payload?.length) return null;
const ts = payload[0]?.payload?.timestamp;
const dateLabel = ts
? formatDateShort(new Date(ts), true)
: "";
const rate = payload[0]?.value;
if (typeof rate !== "number") return null;
// Delta vs. the 100 % goal — a positive delta means
// "100 % target hit" and reads as success; a
// negative delta is the gap to close.
const gap = 100 - rate;
let delta: string | undefined;
if (gap < 0.5) {
delta = t("charts.deltaUnchanged");
} else {
const formatted = `−${fmt.integer(gap)} pp`;
delta = t("charts.deltaVsTarget").replace(
"{delta}",
formatted,
);
}
const rows: RichTooltipRow[] = [
{
name: t("dashboard.compliance7d"),
value: `${fmt.integer(rate)} %`,
color: payload[0]?.color ?? COLOR_LINE,
delta,
},
];
return (
<RichChartTooltip active label={dateLabel} rows={rows} />
);
}}
/>
{/* v1.4.16 A6 — minimum-acceptable threshold (yellow,
paler dash) and 100 % goal line (green, solid-ish).
Two lines together visualise "target range" the way
HealthChart's targetZone band does for BP/weight. */}
<ReferenceLine
y={80}
stroke={COLOR_THRESHOLD}
strokeDasharray="3 5"
strokeOpacity={0.6}
data-slot="medication-threshold-line"
/>
<ReferenceLine
y={100}
stroke={COLOR_GOAL}
strokeDasharray="5 5"
strokeOpacity={0.85}
data-slot="medication-goal-line"
/>
{/* v1.4.16 B1a — gradient-filled Area painted under the
line. Animated on first render unless the user opts
for reduced motion. */}
<Area
type="monotone"
dataKey="rate"
stroke="transparent"
fill={chartGradientFill("chart-gradient-medication-inline")}
fillOpacity={1}
isAnimationActive={animationsEnabled}
animationDuration={animationsEnabled ? 600 : 0}
animationEasing="ease-out"
connectNulls
legendType="none"
/>
<Line
type="monotone"
dataKey="rate"
stroke={COLOR_LINE}
strokeWidth={2}
dot={{ r: 2, fill: COLOR_LINE }}
activeDot={{ r: 4 }}
connectNulls
isAnimationActive={animationsEnabled}
animationDuration={animationsEnabled ? 600 : 0}
animationEasing="ease-out"
/>
</ComposedChart>
</ResponsiveContainer>
</div>
)}
</div>
);
}