mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
feat(insights): time-range pills with period-over-period deltas on metric pages
Add a 7d / 30d / 90d / 1y segmented control to every HealthKit metric page, between the stat strip and the chart, with a sentiment-coloured "vs prior period" delta caption beside it. New route GET /api/analytics/range?type=<MeasurementType>&range=<7d|30d|90d|1y> returns the current-window aggregate, the previous comparable window, and the composed delta. Single metric type by construction, so the read is one rollup-tier call covering the trailing 2N days sliced into the two halves — no per-type fan-out, no Prisma-pool burst. Reuses the WMY readers (readBestGranularityRollups + aggregateWmyBuckets) and the two-window pattern the year-ago baseline already uses; count/min/max/mean/sum compose across buckets, SD/slope/r2 stay out (not composable). The cached summaries slice is untouched so the hottest dashboard cache key never fragments. The delta caption reuses the dashboard's metric-aware up-good/up-bad colour logic — extracted from trend-card into a shared trend-sentiment module — with the metric's good direction sourced from the metric-status registry (target-band metrics render neutral, matching deviation framing). When the prior window has no data the caption shows "no prior-period data" rather than a misleading 0%. The range choice persists across metrics via a localStorage seam and defaults to 30d so nothing regresses. Cache keyed per (type, range) through the query-key factory. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit eac87a9f8b144f4d8e7a8b950528a19d5dcf8726)
This commit is contained in:
1 parent
f1145c0e91
commit
03925ddece
21 files changed
+1151
-65
No files matched your search
@@ -11,6 +11,17 @@ import {
|
||||
} from "@/components/ui/tooltip";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import type { ComparisonBaseline } from "@/lib/dashboard-layout";
|
||||
import {
|
||||
getTrendSentiment,
|
||||
sentimentColorClass,
|
||||
type TrendDirectionSentiment,
|
||||
type TrendSentimentDirection,
|
||||
} from "@/lib/insights/trend-sentiment";
|
||||
|
||||
// v1.9.0 — the metric-aware sentiment mapping moved to a shared module so the
|
||||
// range-delta caption paints the same colour for the same signal. Re-exported
|
||||
// here so existing `@/components/charts/trend-card` importers keep the type.
|
||||
export type { TrendDirectionSentiment, TrendSentimentDirection };
|
||||
|
||||
interface SecondaryMetric {
|
||||
/** Sub-value latest reading (e.g. diastolic when latest is systolic). */
|
||||
@@ -19,70 +30,6 @@ interface SecondaryMetric {
|
||||
avg30: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a metric's "up means" direction to colour sentiment for the small
|
||||
* trend arrow on each tile. v1.4.6 P4 stripped the colour entirely after
|
||||
* the original up=red / down=green mapping was wrong for half the metrics
|
||||
* (mood up = good, BP up = bad, pulse up = neutral). v1.5 phase-5 restores
|
||||
* the colour but per-metric:
|
||||
*
|
||||
* - `up-good` — higher value is better (mood, sleep hours, steps).
|
||||
* ↑ green, ↓ orange.
|
||||
* - `up-bad` — higher value is worse (BP, weight, body fat).
|
||||
* ↑ orange, ↓ green.
|
||||
* - `neutral` — direction doesn't carry a value judgement (pulse,
|
||||
* "BP in target %" — those have their own range
|
||||
* colouring on the avg7/avg30 numbers already).
|
||||
*
|
||||
* Strictly affects the ↑/↓/→ arrow next to the latest reading. Chart
|
||||
* lines, axes, and the avg7/avg30 colour classes are untouched.
|
||||
*/
|
||||
export type TrendDirectionSentiment = "up-good" | "up-bad" | "neutral";
|
||||
|
||||
/**
|
||||
* v1.4.33 F5 — single sentiment helper so the headline arrow, the 7-day
|
||||
* delta value, and the comparison-overlay caption all paint the same
|
||||
* colour for the same signal. Before this helper each consumer ran its
|
||||
* own branch — the arrow read `slope30.direction`, the delta value read
|
||||
* `trend7Delta > 0`, and the comparison caption read `compareDelta > 0`.
|
||||
* When the 30-day regression and the 7-day delta disagreed (weight down
|
||||
* over a month, up over a week) the tile painted a green arrow next to
|
||||
* an orange value, which read as "two metrics in one tile".
|
||||
*
|
||||
* `change` is a signed magnitude of the movement under inspection (the
|
||||
* 7-day delta in units, or the slope-projected-over-7-days for tiles
|
||||
* with only `slope30`). `sentiment` is the metric's improvement
|
||||
* direction.
|
||||
*
|
||||
* - `'positive'` — the change moves the metric toward its goal
|
||||
* (e.g. weight on `up-bad` going down, mood on `up-good` going up).
|
||||
* Renders green.
|
||||
* - `'negative'` — the change moves away from the goal. Renders orange.
|
||||
* - `'neutral'` — either the sentiment is neutral (pulse, BP-in-target),
|
||||
* or the change is below the noise floor (|change| < 0.05). Renders
|
||||
* muted.
|
||||
*/
|
||||
export type TrendSentimentDirection = "positive" | "negative" | "neutral";
|
||||
|
||||
function getTrendSentiment(
|
||||
change: number | null | undefined,
|
||||
sentiment: TrendDirectionSentiment,
|
||||
): TrendSentimentDirection {
|
||||
if (change == null || Math.abs(change) < 0.05) return "neutral";
|
||||
if (sentiment === "neutral") return "neutral";
|
||||
const isUp = change > 0;
|
||||
const isGood =
|
||||
(sentiment === "up-good" && isUp) ||
|
||||
(sentiment === "up-bad" && !isUp);
|
||||
return isGood ? "positive" : "negative";
|
||||
}
|
||||
|
||||
function sentimentColorClass(direction: TrendSentimentDirection): string {
|
||||
if (direction === "positive") return "text-dracula-green";
|
||||
if (direction === "negative") return "text-dracula-orange";
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
|
||||
interface TrendCardProps {
|
||||
label: string;
|
||||
latest: number | null;
|
||||
|
||||
@@ -33,6 +33,13 @@ vi.mock("@/hooks/use-auth", () => ({
|
||||
|
||||
vi.mock("@/hooks/use-insights-layout-prefs", () => ({
|
||||
useInsightsLayoutPrefs: () => ({ layout: null, compareBaseline: false }),
|
||||
useInsightsRangePref: () => ({ range: "30d", setRange: () => {} }),
|
||||
}));
|
||||
|
||||
// v1.9.0 — the page reads the period-over-period range delta; mock the hook
|
||||
// so the test stays deterministic and never touches `fetch`.
|
||||
vi.mock("@/hooks/use-analytics-range", () => ({
|
||||
useAnalyticsRange: () => ({ data: undefined, isLoading: false }),
|
||||
}));
|
||||
|
||||
const analyticsMock = vi.fn();
|
||||
|
||||
@@ -7,11 +7,21 @@ import { Sparkles } from "lucide-react";
|
||||
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useInsightsAnalytics } from "@/hooks/use-insights-analytics";
|
||||
import { useInsightsLayoutPrefs } from "@/hooks/use-insights-layout-prefs";
|
||||
import {
|
||||
useInsightsLayoutPrefs,
|
||||
useInsightsRangePref,
|
||||
} from "@/hooks/use-insights-layout-prefs";
|
||||
import { useAnalyticsRange } from "@/hooks/use-analytics-range";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import type { InsightMetric } from "@/lib/insights/metric-availability";
|
||||
import {
|
||||
getMetricStatusMeta,
|
||||
metricIdForMeasurementType,
|
||||
} from "@/lib/insights/metric-status-registry";
|
||||
import type { MetricStatusMetricId } from "@/lib/insights/metric-status-registry";
|
||||
import { sentimentFromMetricDirection } from "@/lib/insights/trend-sentiment";
|
||||
import type { ChartOverlayKey } from "@/lib/dashboard-layout";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { HealthChartDynamic } from "@/components/charts/health-chart-dynamic";
|
||||
import { MetricStatusCard } from "@/components/insights/metric-status-card";
|
||||
@@ -19,6 +29,8 @@ import { MetricEmptyState } from "@/components/insights/metric-empty-state";
|
||||
import { MetricStatStrip } from "@/components/insights/metric-stat-strip";
|
||||
import { MeasurementDiversityNudge } from "@/components/insights/measurement-diversity-nudge";
|
||||
import { MetricTargetSummary } from "@/components/insights/metric-target-summary";
|
||||
import { TimeRangePills } from "@/components/insights/time-range-pills";
|
||||
import { MetricRangeDelta } from "@/components/insights/metric-range-delta";
|
||||
import { SubPageShell } from "@/components/insights/sub-page-shell";
|
||||
|
||||
/**
|
||||
@@ -139,9 +151,30 @@ export function HealthKitMetricPage({
|
||||
const { user, isAuthenticated } = useAuth();
|
||||
const { t } = useTranslations();
|
||||
const { compareBaseline } = useInsightsLayoutPrefs(isAuthenticated);
|
||||
const { range, setRange } = useInsightsRangePref();
|
||||
|
||||
const { data: analytics, isEmpty } = useInsightsAnalytics(insightMetric);
|
||||
|
||||
// v1.9.0 — period-over-period range read. Single-metric, additive route;
|
||||
// gated off the empty-data branch so a brand-new metric never fires it.
|
||||
const { data: rangeData, isLoading: isRangeLoading } = useAnalyticsRange(
|
||||
measurementType,
|
||||
range,
|
||||
!isEmpty,
|
||||
);
|
||||
|
||||
// The delta's sentiment colour follows the metric's "good direction" from
|
||||
// the metric-status registry (higher-better → up-good, lower-better →
|
||||
// up-bad, target-band → neutral). Every HealthKit metric page is backed by
|
||||
// a registry entry; a metric absent from the registry falls back to neutral.
|
||||
const registryMeta = (() => {
|
||||
const id = metricIdForMeasurementType(measurementType as MeasurementType);
|
||||
return id ? getMetricStatusMeta(id) : null;
|
||||
})();
|
||||
const directionSentiment = registryMeta
|
||||
? sentimentFromMetricDirection(registryMeta.direction)
|
||||
: "neutral";
|
||||
|
||||
const rawSummary = analytics?.summaries?.[measurementType] ?? null;
|
||||
// The stat strip renders display-unit values. The summary holds stored
|
||||
// values, so when the page renders a scaled unit (e.g. WALKING_SPEED
|
||||
@@ -207,6 +240,21 @@ export function HealthKitMetricPage({
|
||||
coachLaunch
|
||||
showAllValuesType={measurementType}
|
||||
>
|
||||
{/* v1.9.0 — time-range pills + period-over-period delta, between the
|
||||
stat strip and the chart. The selected range persists across metrics
|
||||
via `useInsightsRangePref`. */}
|
||||
<div
|
||||
data-slot="metric-range-controls"
|
||||
className="flex flex-wrap items-center justify-between gap-2"
|
||||
>
|
||||
<TimeRangePills value={range} onChange={setRange} />
|
||||
<MetricRangeDelta
|
||||
data={rangeData}
|
||||
range={range}
|
||||
directionSentiment={directionSentiment}
|
||||
isLoading={isRangeLoading}
|
||||
/>
|
||||
</div>
|
||||
<HealthChartDynamic
|
||||
chartKey={chartKey}
|
||||
types={[measurementType]}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDown, ArrowUp } from "lucide-react";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
getTrendSentiment,
|
||||
sentimentColorClass,
|
||||
type TrendDirectionSentiment,
|
||||
} from "@/lib/insights/trend-sentiment";
|
||||
import type { AnalyticsRangeData } from "@/hooks/use-analytics-range";
|
||||
import type { AnalyticsRange } from "@/lib/analytics/range-delta";
|
||||
|
||||
/**
|
||||
* v1.9.0 — period-over-period delta caption beside the time-range pills.
|
||||
*
|
||||
* Renders "+3 % vs prior 30d" with the metric-aware sentiment colour the
|
||||
* dashboard tiles use (up-good vs up-bad). When the prior window has no data
|
||||
* it shows a neutral "no prior-period data" line instead of a misleading 0 %
|
||||
* (the `deltaPct` is null in that case). For `target-band` metrics the
|
||||
* sentiment is neutral, so the delta still shows magnitude + direction but
|
||||
* carries no good/bad colour — matching Oura's deviation framing for metrics
|
||||
* with no single good direction.
|
||||
*/
|
||||
export function MetricRangeDelta({
|
||||
data,
|
||||
range,
|
||||
directionSentiment,
|
||||
isLoading,
|
||||
}: {
|
||||
data: AnalyticsRangeData | undefined;
|
||||
range: AnalyticsRange;
|
||||
directionSentiment: TrendDirectionSentiment;
|
||||
isLoading: boolean;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<span
|
||||
data-slot="metric-range-delta-pending"
|
||||
className="bg-muted/60 inline-block h-3.5 w-28 animate-pulse rounded motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const priorLabel = t(`insights.range.priorLabel.${range}`);
|
||||
|
||||
// No comparison available — prior window empty, or current window empty.
|
||||
if (!data || data.delta === null || data.deltaPct === null) {
|
||||
return (
|
||||
<span
|
||||
data-slot="metric-range-delta-empty"
|
||||
className="text-muted-foreground text-xs"
|
||||
>
|
||||
{t("insights.range.noPriorData")}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const direction = getTrendSentiment(data.delta, directionSentiment);
|
||||
const colorClass = sentimentColorClass(direction);
|
||||
const isUp = data.delta > 0;
|
||||
const pct = Math.round(Math.abs(data.deltaPct) * 100);
|
||||
const sign = isUp ? "+" : "−";
|
||||
|
||||
return (
|
||||
<span
|
||||
data-slot="metric-range-delta"
|
||||
data-direction={direction}
|
||||
className={cn("inline-flex items-center gap-1 text-xs", colorClass)}
|
||||
>
|
||||
{isUp ? (
|
||||
<ArrowUp className="h-3 w-3" aria-hidden="true" />
|
||||
) : (
|
||||
<ArrowDown className="h-3 w-3" aria-hidden="true" />
|
||||
)}
|
||||
<span>
|
||||
{sign}
|
||||
{pct}% {priorLabel}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
ANALYTICS_RANGES,
|
||||
type AnalyticsRange,
|
||||
} from "@/lib/analytics/range-delta";
|
||||
|
||||
/**
|
||||
* v1.9.0 — `7d / 30d / 90d / 1y` segmented control for the Insights metric
|
||||
* pages. The interaction model Apple Health / Oura users already know (a
|
||||
* range selector across the top of a metric chart). Built as an accessible
|
||||
* `radiogroup` of pills over the existing zinc/shadcn primitives rather than
|
||||
* pulling a new Radix dependency — the project's tab strip uses the same
|
||||
* custom-pill approach. The selected range drives the period-over-period
|
||||
* delta caption and (where wired) the chart window.
|
||||
*/
|
||||
export function TimeRangePills({
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
}: {
|
||||
value: AnalyticsRange;
|
||||
onChange: (range: AnalyticsRange) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
|
||||
return (
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={t("insights.range.label")}
|
||||
data-slot="time-range-pills"
|
||||
className={cn(
|
||||
"bg-muted/50 inline-flex items-center gap-0.5 rounded-lg p-0.5",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{ANALYTICS_RANGES.map((range) => {
|
||||
const selected = range === value;
|
||||
return (
|
||||
<button
|
||||
key={range}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
data-range={range}
|
||||
data-selected={selected}
|
||||
onClick={() => onChange(range)}
|
||||
className={cn(
|
||||
"focus-visible:ring-ring rounded-md px-2.5 py-1 text-xs font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none",
|
||||
selected
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{t(`insights.range.option.${range}`)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user