mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
feat(medications): adapt the compliance display to cadence density
A rolling 7-/30-day percentage is meaningful for daily and weekday medications but noise for sparse cadences: a med dosed every few weeks has at most one expected dose in a 7-day window, so the bar swings between 0 and 100 off a single sample. Decide the display server-side from expected-dose density. When the 30-day window holds at least four expected doses the percentage bars stay; below that the card swaps to an uptime-style per-dose timeline where each cell is one expected dose — taken, missed, skipped or upcoming — with a "last N doses" summary and a dose-indexed streak. The compliance route returns an additive complianceDisplay block (mode, expected7/30, the dose timeline, the summary) alongside the existing compliance7/30 fields, which the iOS client and the Health Score read unchanged. Read-path only; no schema change. - compliance.ts: add expectedSlotsBetween and buildComplianceDisplay over the canonical recurrence engine - dose-adherence-timeline: plain flex cells reusing the heatmap colour tokens and tap-to-pin tooltip - switch the standard and GLP-1 cards on the server-decided mode
This commit is contained in:
1 parent
93790aa043
commit
1fcc5ba96b
13 files changed
+967
-19
No files matched your search
@@ -0,0 +1,173 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Flame } from "lucide-react";
|
||||
|
||||
import { useFormatters, useTranslations } from "@/lib/i18n/context";
|
||||
|
||||
/**
|
||||
* v1.8.5 — uptime-style per-dose adherence strip for sparse cadences.
|
||||
*
|
||||
* The medication cards keep the 7-/30-day percentage bars for dense
|
||||
* cadences (daily / multi-daily / weekday meds) where the denominator is
|
||||
* large enough for the percentage to be stable. For sparse cadences
|
||||
* (weekly, bi-/tri-weekly, rolling 35-day injections) a rolling percentage
|
||||
* swings violently off one sample and tells the user nothing; the server
|
||||
* flips `complianceDisplay.mode` to `"timeline"` and this strip takes over.
|
||||
*
|
||||
* Each cell is one EXPECTED dose (not a calendar day), oldest → newest:
|
||||
* taken=green / missed=red / skipped=grey / upcoming=outline. The color
|
||||
* tokens and the tap-to-pin tooltip mirror the 90-day compliance heatmap
|
||||
* (`src/components/charts/compliance-heatmap.tsx`) so the two surfaces read
|
||||
* the same. Plain flex divs, not Recharts — a fixed-size status-cell row
|
||||
* needs no chart container, axis, or tooltip plumbing.
|
||||
*/
|
||||
|
||||
export type DoseStatus = "taken" | "missed" | "skipped" | "upcoming";
|
||||
export type DoseTiming = "early" | "on_time" | "late" | "very_late" | "missed";
|
||||
|
||||
export interface DoseAdherenceCell {
|
||||
scheduledFor: string;
|
||||
status: DoseStatus;
|
||||
takenAt: string | null;
|
||||
timing: DoseTiming | null;
|
||||
site: string | null;
|
||||
}
|
||||
|
||||
interface DoseAdherenceTimelineProps {
|
||||
doses: DoseAdherenceCell[];
|
||||
summary: { taken: number; total: number; doseStreak: number };
|
||||
}
|
||||
|
||||
// v1.4.27 MB7 / CF-10 precedent — clear the 14 px touch floor (with the
|
||||
// gap the row stays tap-friendly on narrow viewports). Mirrors the
|
||||
// heatmap's `CELL_FLOOR_PX`.
|
||||
const CELL_PX = 14;
|
||||
|
||||
/** Token mirror of the heatmap's status palette. */
|
||||
function cellColor(status: DoseStatus, timing: DoseTiming | null): string {
|
||||
if (status === "upcoming") return "transparent";
|
||||
if (status === "skipped") return "var(--secondary)";
|
||||
if (status === "missed") return "var(--dracula-red)";
|
||||
// taken — shade by punctuality, same ladder the heatmap uses.
|
||||
if (timing === "very_late") return "var(--dracula-orange)";
|
||||
if (timing === "late") return "var(--dracula-yellow)";
|
||||
return "var(--dracula-green)";
|
||||
}
|
||||
|
||||
export function DoseAdherenceTimeline({
|
||||
doses,
|
||||
summary,
|
||||
}: DoseAdherenceTimelineProps) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const [tooltip, setTooltip] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
text: string;
|
||||
pinned?: boolean;
|
||||
} | null>(null);
|
||||
|
||||
// Mirror the heatmap: an outside tap clears a pinned tooltip so a touch
|
||||
// user can dismiss the per-cell detail. Gated on `pinned` so the hover
|
||||
// flow never pays the indirection.
|
||||
useEffect(() => {
|
||||
if (!tooltip?.pinned) return;
|
||||
const handlePointer = (event: PointerEvent) => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
if (!container.contains(event.target as Node)) setTooltip(null);
|
||||
};
|
||||
document.addEventListener("pointerdown", handlePointer, true);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointer, true);
|
||||
};
|
||||
}, [tooltip?.pinned]);
|
||||
|
||||
function statusLabel(status: DoseStatus): string {
|
||||
if (status === "taken") return t("medications.doseTaken");
|
||||
if (status === "missed") return t("medications.doseMissed");
|
||||
if (status === "skipped") return t("medications.doseSkipped");
|
||||
return t("medications.doseUpcoming");
|
||||
}
|
||||
|
||||
function cellText(cell: DoseAdherenceCell): string {
|
||||
const when = fmt.dateTime(cell.scheduledFor);
|
||||
return `${when} — ${statusLabel(cell.status)}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2" ref={containerRef}>
|
||||
<div className="relative">
|
||||
<div
|
||||
className="flex flex-wrap gap-1"
|
||||
role="img"
|
||||
aria-label={t("medications.doseTimelineAriaLabel")}
|
||||
>
|
||||
{doses.map((cell, i) => {
|
||||
const isUpcoming = cell.status === "upcoming";
|
||||
return (
|
||||
<div
|
||||
key={`${cell.scheduledFor}-${i}`}
|
||||
className={`shrink-0 cursor-pointer rounded-sm ${
|
||||
isUpcoming ? "border-border border border-dashed" : ""
|
||||
}`}
|
||||
style={{
|
||||
width: CELL_PX,
|
||||
height: CELL_PX,
|
||||
backgroundColor: cellColor(cell.status, cell.timing),
|
||||
}}
|
||||
onPointerEnter={(e) => {
|
||||
if (e.pointerType === "touch") return;
|
||||
setTooltip({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
text: cellText(cell),
|
||||
});
|
||||
}}
|
||||
onPointerLeave={(e) => {
|
||||
if (e.pointerType === "touch") return;
|
||||
setTooltip((prev) => (prev?.pinned ? prev : null));
|
||||
}}
|
||||
onPointerDown={(e) => {
|
||||
if (e.pointerType !== "touch") return;
|
||||
setTooltip({
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
text: cellText(cell),
|
||||
pinned: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{tooltip && (
|
||||
<div
|
||||
className="bg-popover text-popover-foreground border-border pointer-events-none fixed z-50 rounded-md border px-2 py-1 text-xs shadow-md"
|
||||
style={{ left: tooltip.x + 10, top: tooltip.y - 30 }}
|
||||
>
|
||||
{tooltip.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="text-muted-foreground flex items-center gap-3 text-xs">
|
||||
<span>
|
||||
{t("medications.lastNDoses", {
|
||||
total: summary.total,
|
||||
taken: summary.taken,
|
||||
})}
|
||||
</span>
|
||||
{summary.doseStreak > 0 && (
|
||||
<span className="text-dracula-orange flex items-center gap-1 font-medium">
|
||||
<Flame className="h-3.5 w-3.5" />
|
||||
{t("medications.doseStreak", { count: summary.doseStreak })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,10 @@ import { MedicationCardMenu } from "@/components/medications/medication-card-men
|
||||
import { MedicationStateBadges } from "@/components/medications/card-parts/medication-state-badges";
|
||||
import { MedicationStatusPill } from "@/components/medications/card-parts/medication-status-pill";
|
||||
import { MedicationComplianceBars } from "@/components/medications/card-parts/medication-compliance-bars";
|
||||
import {
|
||||
DoseAdherenceTimeline,
|
||||
type DoseAdherenceCell,
|
||||
} from "@/components/medications/card-parts/dose-adherence-timeline";
|
||||
import { MedicationIntakeActions } from "@/components/medications/card-parts/medication-intake-actions";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import {
|
||||
@@ -91,9 +95,24 @@ export interface Glp1Medication {
|
||||
schedules: ScheduleLite[];
|
||||
}
|
||||
|
||||
interface ComplianceDisplay {
|
||||
mode: "percent" | "timeline";
|
||||
expected7: number;
|
||||
expected30: number;
|
||||
minStableDoses: number;
|
||||
doseTimeline: DoseAdherenceCell[];
|
||||
recentDoseSummary: { taken: number; total: number; doseStreak: number };
|
||||
}
|
||||
|
||||
interface ComplianceData {
|
||||
compliance7: { rate: number; streak: number };
|
||||
compliance30: { rate: number };
|
||||
/**
|
||||
* v1.8.5 — server-decided render mode. GLP-1 injections are commonly
|
||||
* weekly, so this card flips to the per-dose timeline more often than
|
||||
* the generic one. Additive — older mocks omit it.
|
||||
*/
|
||||
complianceDisplay?: ComplianceDisplay;
|
||||
}
|
||||
|
||||
interface DetailsResponse {
|
||||
@@ -420,15 +439,24 @@ export function Glp1MedicationCard({
|
||||
Glp1InventoryDTO slot on /api/medications/[id]/glp1 stays
|
||||
in the response shape; only the web mounts are gone. */}
|
||||
|
||||
{/* Compliance bars — shared with the generic card so the page
|
||||
grid stays harmonious. */}
|
||||
{medication.active && compliance && (
|
||||
<MedicationComplianceBars
|
||||
rate7={rate7}
|
||||
rate30={rate30}
|
||||
streak={streak}
|
||||
/>
|
||||
)}
|
||||
{/* Compliance region — shared decision with the generic card.
|
||||
Dense cadences keep the bars; sparse cadences (most weekly
|
||||
GLP-1 injections) swap to the per-dose uptime strip. Falls back
|
||||
to the bars when the older payload omits `complianceDisplay`. */}
|
||||
{medication.active &&
|
||||
compliance &&
|
||||
(compliance.complianceDisplay?.mode === "timeline" ? (
|
||||
<DoseAdherenceTimeline
|
||||
doses={compliance.complianceDisplay.doseTimeline}
|
||||
summary={compliance.complianceDisplay.recentDoseSummary}
|
||||
/>
|
||||
) : (
|
||||
<MedicationComplianceBars
|
||||
rate7={rate7}
|
||||
rate30={rate30}
|
||||
streak={streak}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Primary actions row — shared with the generic medication
|
||||
card. The GLP-1-specific side-effect quick-log lives in the
|
||||
|
||||
@@ -9,6 +9,10 @@ import { MedicationCardMenu } from "@/components/medications/medication-card-men
|
||||
import { MedicationStateBadges } from "@/components/medications/card-parts/medication-state-badges";
|
||||
import { MedicationStatusPill } from "@/components/medications/card-parts/medication-status-pill";
|
||||
import { MedicationComplianceBars } from "@/components/medications/card-parts/medication-compliance-bars";
|
||||
import {
|
||||
DoseAdherenceTimeline,
|
||||
type DoseAdherenceCell,
|
||||
} from "@/components/medications/card-parts/dose-adherence-timeline";
|
||||
import { MedicationIntakeActions } from "@/components/medications/card-parts/medication-intake-actions";
|
||||
import { formatTimeWindowRange } from "@/lib/time-window-format";
|
||||
import { formatDateTime, formatTime } from "@/lib/format";
|
||||
@@ -62,6 +66,15 @@ interface Medication {
|
||||
schedules: Schedule[];
|
||||
}
|
||||
|
||||
interface ComplianceDisplay {
|
||||
mode: "percent" | "timeline";
|
||||
expected7: number;
|
||||
expected30: number;
|
||||
minStableDoses: number;
|
||||
doseTimeline: DoseAdherenceCell[];
|
||||
recentDoseSummary: { taken: number; total: number; doseStreak: number };
|
||||
}
|
||||
|
||||
interface ComplianceData {
|
||||
compliance7: {
|
||||
totalExpected: number;
|
||||
@@ -74,6 +87,12 @@ interface ComplianceData {
|
||||
compliance30: {
|
||||
rate: number;
|
||||
};
|
||||
/**
|
||||
* v1.8.5 — server-decided render mode for the compliance region. Dense
|
||||
* cadences keep the 7-/30-day bars (`"percent"`); sparse cadences swap to
|
||||
* the per-dose uptime strip (`"timeline"`). Additive — older mocks omit it.
|
||||
*/
|
||||
complianceDisplay?: ComplianceDisplay;
|
||||
}
|
||||
|
||||
interface MedicationCardProps {
|
||||
@@ -327,14 +346,24 @@ export function MedicationCard({
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Compliance bar */}
|
||||
{medication.active && compliance && (
|
||||
<MedicationComplianceBars
|
||||
rate7={rate7}
|
||||
rate30={rate30}
|
||||
streak={streak}
|
||||
/>
|
||||
)}
|
||||
{/* Compliance region — the server decides whether the percentage
|
||||
bars stay (dense cadences) or the per-dose uptime strip takes
|
||||
over (sparse cadences). Falls back to the bars when the older
|
||||
payload omits `complianceDisplay`. */}
|
||||
{medication.active &&
|
||||
compliance &&
|
||||
(compliance.complianceDisplay?.mode === "timeline" ? (
|
||||
<DoseAdherenceTimeline
|
||||
doses={compliance.complianceDisplay.doseTimeline}
|
||||
summary={compliance.complianceDisplay.recentDoseSummary}
|
||||
/>
|
||||
) : (
|
||||
<MedicationComplianceBars
|
||||
rate7={rate7}
|
||||
rate30={rate30}
|
||||
streak={streak}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Quick actions — primary buttons of the medication card. */}
|
||||
{medication.active && (
|
||||
|
||||
Reference in new issue
Block a user