feat(charts): persist per-chart overlay prefs (default off; clean line)

Hook the overlay-controls dropdown into a TanStack Query mutation so
each chart's three toggle states (7-day trend / Trend arrow / Target
range) save per user and survive reloads. The prefs piggy-back on the
existing User.dashboardWidgetsJson blob with a `chartOverlayPrefs`
keyed by chart id, mirroring the v1.4.16 phase B8 comparison-baseline
pattern — no Prisma migration needed.

Wires up:
  - GET /api/dashboard/widgets surfaces the resolved prefs in its
    response so a fresh dashboard load knows which overlays to paint.
  - PUT /api/dashboard/chart-overlay-prefs replaces a single chart's
    prefs without round-tripping the whole layout.
  - Existing PUT /api/dashboard/widgets preserves any chartOverlayPrefs
    the client doesn't send, so saving widget visibility doesn't wipe
    chart prefs.
  - useChartOverlayPrefs hook reads + optimistically updates the cache.
  - HealthChart, MoodChart, MedicationComplianceChart all consume the
    hook, render the controls dropdown next to the range tabs, and gate
    their three overlays behind the persisted toggles.

Default state for every chart, every flag: false. The clean line is
the new default; users opt into overlays they care about per chart.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.7 committed 2026-05-10 10:34:08 +02:00
1 parent 75f340e82b
commit d70a9b1ee9
17 files changed
+761 -132

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
"use client";
import { useCallback, useMemo } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
DEFAULT_CHART_OVERLAY_PREFS,
type ChartOverlayKey,
type ChartOverlayPrefs,
type ChartOverlayPrefsMap,
type DashboardLayout,
} from "@/lib/dashboard-layout";
/**
* v1.4.18 — TanStack Query hook that returns a single chart's overlay
* prefs and a setter that persists them via the new
* `PUT /api/dashboard/chart-overlay-prefs` endpoint.
*
* Reads from the existing dashboard-widgets cache (queryKey
* `["dashboard-layout"]`) so a chart on the dashboard doesn't fire a
* second network request — the layout already lands once on initial
* dashboard render.
*
* The mutation is optimistic: we update the cached layout immediately
* so the chart re-renders with the new toggle state before the network
* round-trip resolves. On error the cache is rolled back to its
* previous value.
*/
export function useChartOverlayPrefs(chartKey: ChartOverlayKey): {
prefs: ChartOverlayPrefs;
setPrefs: (next: ChartOverlayPrefs) => void;
isSaving: boolean;
} {
const queryClient = useQueryClient();
const { data: layout } = useQuery({
queryKey: ["dashboard-layout"],
queryFn: async (): Promise<DashboardLayout> => {
const res = await fetch("/api/dashboard/widgets");
if (!res.ok) throw new Error("Failed to load dashboard layout");
const json = await res.json();
return json.data as DashboardLayout;
},
// Keep the cache warm — the dashboard page mounts a query against
// the same key on first paint, so this hook just piggy-backs.
staleTime: 60_000,
});
const prefs = useMemo<ChartOverlayPrefs>(() => {
return (
layout?.chartOverlayPrefs?.[chartKey] ?? DEFAULT_CHART_OVERLAY_PREFS
);
}, [layout, chartKey]);
const mutation = useMutation({
mutationFn: async (next: ChartOverlayPrefs): Promise<void> => {
const res = await fetch("/api/dashboard/chart-overlay-prefs", {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify({ chartKey, prefs: next }),
});
if (!res.ok) {
throw new Error("Failed to save chart overlay prefs");
}
},
onMutate: async (next) => {
await queryClient.cancelQueries({ queryKey: ["dashboard-layout"] });
const previous = queryClient.getQueryData<DashboardLayout>([
"dashboard-layout",
]);
if (previous) {
const nextLayout: DashboardLayout = {
...previous,
chartOverlayPrefs: {
...(previous.chartOverlayPrefs ?? {}),
[chartKey]: next,
} as ChartOverlayPrefsMap,
};
queryClient.setQueryData(["dashboard-layout"], nextLayout);
}
return { previous };
},
onError: (_err, _next, ctx) => {
const context = ctx as { previous?: DashboardLayout } | undefined;
if (context?.previous) {
queryClient.setQueryData(["dashboard-layout"], context.previous);
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["dashboard-layout"] });
},
});
const setPrefs = useCallback(
(next: ChartOverlayPrefs): void => {
mutation.mutate(next);
},
[mutation],
);
return {
prefs,
setPrefs,
isSaving: mutation.isPending,
};
}