feat(dashboard): configure Today highlights

This commit is contained in:
Marc-André Bombeck committed 2026-07-28 13:22:08 +02:00
1 parent a2f2a30ac2
commit a689329e79
30 files changed
+951 -1098

No files matched your search

@@ -143,6 +143,29 @@ describe("<TodayHero>", () => {
expect(html).toBe("");
});
it("shows all-clear when layout filtering removes every candidate", () => {
const html = render(
<TodayHero
digest={digest({
score: null,
topSignal: null,
briefingLead: null,
line: "Nothing needs your attention today — everything's tracking normally.",
worthALook: [],
reactionLine: null,
justIn: null,
})}
renderFilteredAllClear
/>,
);
expect(html).toContain('data-slot="today-hero"');
expect(html).toContain('data-slot="today-hero-all-clear"');
expect(html).not.toContain('data-slot="today-hero-rail"');
expect(html).not.toContain('data-slot="today-hero-signal"');
expect(html).not.toContain('data-slot="today-hero-just-in"');
});
// v1.29.1 — the v1.29.0 selected-score-ring cluster was removed from the web
// hero (Marc, live-use: uneven, wasted tile space). Only the main
// health-score ring paints now; the cluster's data-slots are gone.
+10 -1
View File
@@ -90,7 +90,13 @@ function formatJustInTime(iso: string): string | null {
}
}
export function TodayHero({ digest }: { digest: DailyDigest }) {
export function TodayHero({
digest,
renderFilteredAllClear = false,
}: {
digest: DailyDigest;
renderFilteredAllClear?: boolean;
}) {
const { t } = useTranslations();
// Gates ONLY the chip's time string — never the chip's presence. The hero
// itself is deliberately NOT mount-gated (v1.30.9: it is the LCP element and
@@ -134,7 +140,10 @@ export function TodayHero({ digest }: { digest: DailyDigest }) {
// below. A fresh marker counts as content even when line generation was
// unavailable: the deterministic digest line still gives the hero an honest
// lead, and hiding the marker would lose the arrival moment entirely.
// A filtered layout is the one explicit exception: its empty digest means
// "the hidden canonical candidates are quiet here", so retain all-clear.
if (
!renderFilteredAllClear &&
!hasScore &&
!hasItems &&
!digest.briefingLead &&
@@ -1,17 +1,15 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import {
DEFAULT_DASHBOARD_LAYOUT,
serializeDashboardLayout,
DASHBOARD_IOS_ONLY_WIDGET_IDS,
DASHBOARD_WIDGET_IDS,
IOS_PIN_ONLY_WIDGET_IDS,
buildRingMutationPayload,
widgetWritesBusy,
type DashboardLayout,
} from "@/lib/dashboard-layout";
import { PRIORITY_ITEM_KINDS } from "@/lib/daily/priority-item";
import { NATIVE_ONLY_WIDGET_LABEL_KEYS } from "@/lib/dashboard/widget-modules";
// v1.11.2 HIGH-1 — the web Settings list renders one row per WRITABLE id
@@ -75,6 +73,7 @@ import { I18nProvider } from "@/lib/i18n/context";
import {
DashboardLayoutSection,
reorderWidgets,
setHeroItemKindEnabled,
} from "../dashboard-layout-section";
function render(node: React.ReactElement, locale: "en" | "de" = "en") {
@@ -165,13 +164,8 @@ describe("<DashboardLayoutSection> — drag-and-drop reorder", () => {
it("keeps the arrow buttons present after the drag handle lands (a11y fallback)", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
// Move up + Move down translation keys resolve to the English
// strings — counted once per row. Both the widget rows and the
// score-ring reorder rows (health-score anchor + selected rings)
// carry the same arrow pair, so the total is one per row of either
// kind.
const ringRows = (html.match(/data-slot="score-ring-row"/g) ?? []).length;
const expected = WEB_RENDERABLE_ROW_COUNT + ringRows;
// Move up + Move down translation keys resolve once per widget row.
const expected = WEB_RENDERABLE_ROW_COUNT;
const moveUpCount = (html.match(/aria-label="Move up"/g) ?? []).length;
const moveDownCount = (html.match(/aria-label="Move down"/g) ?? []).length;
expect(moveUpCount).toBe(expected);
@@ -495,237 +489,125 @@ describe("<DashboardLayoutSection> — disabled-module widget toggles", () => {
});
});
/**
* v1.27.7 — hero score-ring picker. Renders whenever the layout loads
* (it configures the server-computed score rings the dashboard snapshot
* carries); offers only rings whose owning module is enabled; caps the
* selection at three via disabled switches. SSR smoke assertions,
* matching the rest of this suite.
*/
describe("<DashboardLayoutSection> — hero score-ring picker (v1.27.7)", () => {
it("renders for the default layout", () => {
describe("<DashboardLayoutSection> — hero content", () => {
it("keeps the removed score and comparison controls out of the UI", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
expect(html).toContain('data-slot="score-rings-picker"');
for (const removedLabel of [
"Compare to",
"Last month",
"Last year",
"Readiness",
"Recovery score",
"Sleep score",
]) {
expect(html).not.toContain(removedLabel);
}
});
it("renders one switch per ring (fail-open module map)", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
it("renders one switch for every current priority-item kind", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
expect(html).toContain('data-slot="score-rings-picker"');
// v1.27.27 — one switch per score ring (4) plus the always-present
// health-score anchor row = 5.
const switches = html.match(/data-slot="score-ring-switch"/g) ?? [];
expect(switches).toHaveLength(5);
// The default selection (MED_COMPLIANCE) reads checked.
const compliance = html.match(
/<button[^>]*data-slot="score-ring-switch"[^>]*data-ring="MED_COMPLIANCE"[^>]*>/,
);
expect(compliance).not.toBeNull();
expect(compliance![0]).toContain('data-state="checked"');
expect(html).toContain('data-slot="hero-content-settings"');
const switches = html.match(/data-slot="hero-item-switch"/g) ?? [];
expect(switches).toHaveLength(PRIORITY_ITEM_KINDS.length);
for (const kind of PRIORITY_ITEM_KINDS) {
const control = html.match(
new RegExp(
`<button[^>]*data-slot="hero-item-switch"[^>]*data-kind="${kind}"[^>]*>`,
),
);
expect(control, kind).not.toBeNull();
expect(control![0]).toContain('data-state="checked"');
}
});
it("hides rings whose owning module is disabled (anchor stays)", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
authState.modules = { recovery: false, sleep: false };
it("treats a missing API field as every current kind enabled", () => {
const layoutWithoutHeroKinds: DashboardLayout = {
...DEFAULT_DASHBOARD_LAYOUT,
};
delete layoutWithoutHeroKinds.enabledHeroItemKinds;
queryState.layout = layoutWithoutHeroKinds;
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const switches = html.match(/data-slot="score-ring-switch"/g) ?? [];
// READINESS + RECOVERY_SCORE (recovery) and SLEEP_SCORE (sleep) are
// gone; the adherence ring plus the health-score anchor remain = 2.
expect(switches).toHaveLength(2);
expect(html).toContain('data-ring="MED_COMPLIANCE"');
expect(html).toContain('data-ring="HEALTH_SCORE"');
const switches =
html.match(/<button[^>]*data-slot="hero-item-switch"[^>]*>/g) ?? [];
expect(switches).toHaveLength(PRIORITY_ITEM_KINDS.length);
for (const control of switches) {
expect(control).toContain('data-state="checked"');
}
});
it("hides the derived rings when the insights module is off (anchor stays)", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
authState.modules = { insights: false };
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const switches = html.match(/data-slot="score-ring-switch"/g) ?? [];
// Adherence ring + health-score anchor.
expect(switches).toHaveLength(2);
expect(html).toContain('data-ring="MED_COMPLIANCE"');
});
it("disables the remaining switches at the three-ring cap", () => {
it("permits an explicit all-off layout", () => {
queryState.layout = {
...DEFAULT_DASHBOARD_LAYOUT,
selectedScoreRings: ["READINESS", "RECOVERY_SCORE", "SLEEP_SCORE"],
enabledHeroItemKinds: [],
};
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const compliance = html.match(
/<button[^>]*data-slot="score-ring-switch"[^>]*data-ring="MED_COMPLIANCE"[^>]*>/,
const switches = html.match(
/<button[^>]*data-slot="hero-item-switch"[^>]*>/g,
);
expect(compliance).not.toBeNull();
// The rendered `disabled` HTML attribute — not the Tailwind
// `disabled:` variant prefixes that every switch class list carries.
expect(compliance![0]).toContain('disabled=""');
// The three selected rings stay enabled (unchecking must stay possible).
const readiness = html.match(
/<button[^>]*data-slot="score-ring-switch"[^>]*data-ring="READINESS"[^>]*>/,
);
expect(readiness).not.toBeNull();
expect(readiness![0]).not.toContain('disabled=""');
});
});
/**
* v1.27.27 — the health-score ring is a first-class, always-present,
* reorderable member of the hero ring row. The picker renders it as a
* pinned row (no on/off toggle — a disabled, checked switch) that leads by
* default and reorders with the same drag-handle + arrow-button pair as the
* score rings and the widget list.
*/
describe("<DashboardLayoutSection> — health-score anchor + reorder (v1.27.27)", () => {
it("renders the health-score anchor as a reorderable row, leading by default", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
// A sortable ring row exists for the health-score anchor.
expect(html).toContain('data-slot="score-ring-row"');
const anchorRow = html.match(
/<div[^>]*data-slot="score-ring-row"[^>]*data-ring="HEALTH_SCORE"[^>]*>/,
);
expect(anchorRow).not.toBeNull();
// Default order leads with the anchor: its row precedes the adherence
// ring's row.
const anchorIdx = html.indexOf('data-ring="HEALTH_SCORE"');
const medIdx = html.indexOf(
'data-slot="score-ring-row" data-ring="MED_COMPLIANCE"',
);
expect(anchorIdx).toBeGreaterThan(-1);
// The anchor row appears before any selected score-ring row.
expect(anchorIdx).toBeLessThan(html.indexOf('data-ring="MED_COMPLIANCE"'));
expect(medIdx === -1 || anchorIdx < medIdx).toBe(true);
expect(switches).toHaveLength(PRIORITY_ITEM_KINDS.length);
for (const control of switches ?? []) {
expect(control).toContain('data-state="unchecked"');
expect(control).not.toContain('disabled=""');
}
expect(html).toContain("Custom layout active");
});
it("the anchor switch is checked and disabled (locked-on, no toggle-off)", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const anchorSwitch = html.match(
/<button[^>]*data-slot="score-ring-switch"[^>]*data-ring="HEALTH_SCORE"[^>]*>/,
it("switches off the last enabled kind and persists an explicit empty array", () => {
const lastEnabled = ["coach_checkin"] as const;
const enabledHeroItemKinds = setHeroItemKindEnabled(
lastEnabled,
"coach_checkin",
false,
);
expect(anchorSwitch).not.toBeNull();
expect(anchorSwitch![0]).toContain('data-state="checked"');
expect(anchorSwitch![0]).toContain('disabled=""');
});
expect(enabledHeroItemKinds).toEqual([]);
expect(lastEnabled).toEqual(["coach_checkin"]);
it("the anchor carries a drag handle + move arrows (reorderable)", () => {
queryState.layout = DEFAULT_DASHBOARD_LAYOUT;
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
// The health-score row is a full sortable row: its drag handle exists.
const handles = html.match(/data-slot="score-ring-drag-handle"/g) ?? [];
// One handle per hero-order row = anchor + default MED_COMPLIANCE = 2.
expect(handles.length).toBeGreaterThanOrEqual(2);
});
it("honours a persisted order that moves the anchor off the lead", () => {
queryState.layout = {
const serialized = serializeDashboardLayout({
...DEFAULT_DASHBOARD_LAYOUT,
selectedScoreRings: ["READINESS", "MED_COMPLIANCE"],
heroRingOrder: ["READINESS", "HEALTH_SCORE", "MED_COMPLIANCE"],
enabledHeroItemKinds,
});
expect(serialized.enabledHeroItemKinds).toEqual([]);
});
it("labels the switch collection and associates both explanatory texts", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const fieldset = html.match(
/<fieldset[^>]*data-slot="hero-content-settings"[^>]*>/,
);
expect(fieldset).not.toBeNull();
expect(fieldset![0]).toContain("rounded-lg");
const describedBy = fieldset![0].match(/aria-describedby="([^"]+)"/);
expect(describedBy).not.toBeNull();
const descriptionIds = describedBy![1].split(" ");
expect(descriptionIds).toHaveLength(2);
for (const descriptionId of descriptionIds) {
expect(html).toContain(`id="${descriptionId}"`);
}
expect(html).toContain("<legend");
expect(html).toContain("Today highlights");
});
it("keeps every kind visible when unrelated modules are disabled", () => {
authState.modules = {
coach: false,
medications: false,
insights: false,
};
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const readinessRow = html.indexOf(
'data-slot="score-ring-row" data-ring="READINESS"',
);
const anchorRow = html.indexOf(
'data-slot="score-ring-row" data-ring="HEALTH_SCORE"',
);
const medRow = html.indexOf(
'data-slot="score-ring-row" data-ring="MED_COMPLIANCE"',
);
expect(readinessRow).toBeGreaterThan(-1);
expect(anchorRow).toBeGreaterThan(readinessRow);
expect(medRow).toBeGreaterThan(anchorRow);
const switches = html.match(/data-slot="hero-item-switch"/g) ?? [];
expect(switches).toHaveLength(PRIORITY_ITEM_KINDS.length);
});
it("the ring mutation PUTs both selectedScoreRings and heroRingOrder (source pin)", () => {
const src = readFileSync(
join(
process.cwd(),
"src/components/settings/dashboard-layout-section.tsx",
),
"utf8",
);
expect(src).toContain("selectedScoreRings: next.selectedScoreRings");
expect(src).toContain("heroRingOrder: next.heroRingOrder");
// The order is the single source of truth: selection is derived from it.
expect(src).toMatch(/id !== HEALTH_SCORE_RING_ID/);
it("renders localized Today-highlight labels", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />, "de");
expect(html).toContain("Highlights für heute");
expect(html).toContain("Medikamentendosen");
expect(html).toContain("Neue EKG-Aufzeichnungen");
});
it("the ring mutation builds its body via buildRingMutationPayload, not a `...remote` spread (regression #581 source pin)", () => {
const src = readFileSync(
join(
process.cwd(),
"src/components/settings/dashboard-layout-section.tsx",
),
"utf8",
);
// v1.32.16 — the ring body is built via `buildRingMutationPayload`,
// now also threading the optimistic-concurrency base token.
expect(src).toContain("buildRingMutationPayload({ ...next, baseUpdatedAt");
// The pre-fix shape must never come back: spreading a query-cache
// snapshot into the ring PUT body is exactly the stale-`widgets`
// race issue #581 reported.
expect(src).not.toMatch(/\.\.\.remote,/);
});
});
/**
* v1.32.16 (issue #581) — a committed Save must stay authoritative against a
* concurrent instant hero-ring write. The full DOM interaction (fire a ring
* write, then a Save, assert the disabled/pending gate) can't run under this
* suite's SSR-only convention, so the load-bearing client contract is pinned
* as pure exported units plus source pins for the wiring the JSX depends on.
*/
describe("dashboard layout — Save cannot be clobbered by a ring write (#581)", () => {
it("buildRingMutationPayload never carries widgets and threads the base token", () => {
const payload = buildRingMutationPayload({
selectedScoreRings: ["READINESS"],
heroRingOrder: ["HEALTH_SCORE", "READINESS"],
baseUpdatedAt: "2026-07-24T10:00:00.000Z",
});
// None of the fields a stale snapshot could carry and use to overwrite
// a fresher Save.
expect(payload).not.toHaveProperty("widgets");
expect(payload).not.toHaveProperty("comparisonBaseline");
expect(payload).not.toHaveProperty("chartOverlayPrefs");
// The ring selection + the guard token DO ride.
expect(payload.selectedScoreRings).toEqual(["READINESS"]);
expect(payload.baseUpdatedAt).toBe("2026-07-24T10:00:00.000Z");
});
it("buildRingMutationPayload omits the base-token key when none is known", () => {
const payload = buildRingMutationPayload({
selectedScoreRings: [],
heroRingOrder: ["HEALTH_SCORE"],
});
expect(payload).not.toHaveProperty("baseUpdatedAt");
});
it("widgetWritesBusy gates off EITHER write being in flight", () => {
expect(widgetWritesBusy(false, false)).toBe(false);
expect(widgetWritesBusy(true, false)).toBe(true); // Save pending
expect(widgetWritesBusy(false, true)).toBe(true); // ring pending
expect(widgetWritesBusy(true, true)).toBe(true);
});
it("the Save + ring controls bind the shared busy gate and serialise via one scope (source pin)", () => {
const src = readFileSync(
join(
process.cwd(),
"src/components/settings/dashboard-layout-section.tsx",
),
"utf8",
);
// Save button + ring controls both read `widgetWritesBusy(...)` so the
// gate is one source of truth — the button can never disable on
// `saveMutation.isPending` alone (the pre-fix hole).
expect(src).toContain("widgetWritesBusy(");
// Both writes share a mutation scope so they run serially at the client.
expect(src).toContain("scope: { id: DASHBOARD_WIDGETS_MUTATION_SCOPE }");
// Each write sends the optimistic-concurrency base token.
expect(src).toContain("baseUpdatedAt: readBaseToken()");
// A 409 is handled (refetch + gentle nudge), not swallowed as a hard error.
expect(src).toContain("err.status === 409");
it("states that notification settings are managed separately", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
expect(html).toContain("Notification settings are managed separately.");
});
});
@@ -131,18 +131,17 @@ describe("dashboard layout save — every layout source is covered (source pins)
"utf8",
);
it("all three snapshot invalidations (save / reset / rings) refetch inactive cells", () => {
const calls =
sectionSrc.match(
/invalidateQueries\(\{\s*queryKey: queryKeys\.dashboardSnapshot\(\),\s*refetchType: "all",\s*\}\)/g,
) ?? [];
expect(calls).toHaveLength(3);
// No leftover default-refetchType snapshot invalidation.
const anySnapshotInvalidation =
sectionSrc.match(
/invalidateQueries\(\{\s*queryKey: queryKeys\.dashboardSnapshot\(\)/g,
) ?? [];
expect(anySnapshotInvalidation).toHaveLength(3);
it("save and reset refetch inactive snapshot and daily-digest cells", () => {
for (const key of ["dashboardSnapshot", "dailyDigest"]) {
const calls =
sectionSrc.match(
new RegExp(
`invalidateQueries\\(\\{\\s*queryKey: queryKeys\\.${key}\\(\\),\\s*refetchType: "all",\\s*\\}\\)`,
"g",
),
) ?? [];
expect(calls).toHaveLength(2);
}
});
it("the legacy dashboardWidgets cell is written directly with the server response", () => {
@@ -30,37 +30,24 @@ import { CSS } from "@dnd-kit/utilities";
import { Button } from "@/components/ui/button";
import { ConfirmButton } from "@/components/ui/confirm-button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
import { useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import {
type DashboardLayout,
type DashboardWidgetId,
type ComparisonBaseline,
type ScoreRingId,
type HeroRingId,
COMPARISON_BASELINES,
DEFAULT_DASHBOARD_LAYOUT,
DASHBOARD_WIDGET_IDS,
DASHBOARD_IOS_ONLY_WIDGET_IDS,
IOS_PIN_ONLY_WIDGET_IDS,
type DashboardWidgetCatalogueId,
SCORE_RING_IDS,
SCORE_RING_MODULE,
MAX_SELECTED_SCORE_RINGS,
HEALTH_SCORE_RING_ID,
resolveHeroRingOrder,
buildRingMutationPayload,
widgetWritesBusy,
type DashboardLayoutWithToken,
} from "@/lib/dashboard-layout";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
PRIORITY_ITEM_KINDS,
type PriorityItemKind,
} from "@/lib/daily/priority-item";
import { apiDelete, apiGet, apiPut, ApiError } from "@/lib/api/api-fetch";
import { useAuth } from "@/hooks/use-auth";
import {
@@ -98,6 +85,17 @@ export function reorderWidgets(
return next.map((w, i) => ({ ...w, order: i }));
}
export function setHeroItemKindEnabled(
enabledKinds: readonly PriorityItemKind[] | undefined,
kind: PriorityItemKind,
enabled: boolean,
): PriorityItemKind[] {
const next = new Set(enabledKinds ?? PRIORITY_ITEM_KINDS);
if (enabled) next.add(kind);
else next.delete(kind);
return PRIORITY_ITEM_KINDS.filter((itemKind) => next.has(itemKind));
}
/**
* v1.4.48 M6a — merge the `{ id, order }` shape returned by
* `reorderWidgets()` back into the full `DashboardWidgetConfig[]` so
@@ -135,14 +133,7 @@ function mergeReorderIntoLayout(
});
}
/**
* v1.32.16 (issue #581) — the normal layout Save and the instant hero-ring
* PUT both write the whole `/api/dashboard/widgets` layout. Sharing one
* TanStack mutation `scope` serialises them: a second write in this scope
* waits for the first to settle, so the two PUTs can never overlap at the
* server and a committed Save cannot be reverted by a ring write that
* started from the pre-Save snapshot.
*/
/** Serialise layout saves and resets against the same endpoint. */
const DASHBOARD_WIDGETS_MUTATION_SCOPE = "dashboard-widgets" as const;
const WIDGET_LABEL_KEYS: Record<DashboardWidgetId, string> = {
@@ -185,27 +176,15 @@ const WIDGET_LABEL_KEYS: Record<DashboardWidgetId, string> = {
waterIntake: "nutrients.names.water",
};
/**
* v1.27.7 — option labels for the hero score-ring picker. The three
* derived rings reuse their wellness-strip titles; the dose ring names
* today's tally (the exact thing the ring shows since it moved off the
* 7-day adherence percentage).
*/
const SCORE_RING_LABEL_KEYS: Record<ScoreRingId, string> = {
READINESS: "insights.derived.composite.READINESS.title",
RECOVERY_SCORE: "insights.derived.scores.recovery",
SLEEP_SCORE: "insights.derived.composite.SLEEP_SCORE.title",
MED_COMPLIANCE: "dashboard.hero.ringDoses",
};
/**
* v1.27.27 — label key for any hero ring id, including the always-present
* health-score anchor ring. Reuses the hero's own "Health Score" label so
* the picker row and the hero ring name match verbatim.
*/
const HERO_RING_LABEL_KEYS: Record<HeroRingId, string> = {
[HEALTH_SCORE_RING_ID]: "dashboard.hero.scoreLabel",
...SCORE_RING_LABEL_KEYS,
const HERO_ITEM_LABEL_KEYS: Record<PriorityItemKind, string> = {
coach_checkin: "dashboard.heroItems.coach_checkin",
dose_window: "dashboard.heroItems.dose_window",
preventive_care: "dashboard.heroItems.preventive_care",
sync_issue: "dashboard.heroItems.sync_issue",
milestone: "dashboard.heroItems.milestone",
ecg_new_recording: "dashboard.heroItems.ecg_new_recording",
tension_window: "dashboard.heroItems.tension_window",
same_time_baseline: "dashboard.heroItems.same_time_baseline",
};
export function DashboardLayoutSection({ id }: { id: string }) {
@@ -223,6 +202,8 @@ export function DashboardLayoutSection({ id }: { id: string }) {
// tooltip. One hint paragraph is rendered once at the bottom of the list
// and referenced by every drag handle in this section.
const dragHintId = useId();
const heroDescriptionId = useId();
const heroNotificationNoteId = useId();
// v1.4.47 W4 — sensors: pointer for mouse/touch, keyboard for Tab + Space
// + arrow-key reordering. The KeyboardSensor still works for users who
@@ -280,8 +261,6 @@ export function DashboardLayoutSection({ id }: { id: string }) {
const layout = draft ?? remote ?? null;
const saveMutation = useMutation({
// v1.32.16 (issue #581) — shared scope serialises this against the
// instant ring PUT so they can never overlap at the server.
scope: { id: DASHBOARD_WIDGETS_MUTATION_SCOPE },
mutationFn: async (next: DashboardLayout) => {
return apiPut<DashboardLayoutWithToken>("/api/dashboard/widgets", {
@@ -312,15 +291,17 @@ export function DashboardLayoutSection({ id }: { id: string }) {
queryKey: queryKeys.dashboardSnapshot(),
refetchType: "all",
});
queryClient.invalidateQueries({
queryKey: queryKeys.dailyDigest(),
refetchType: "all",
});
setDraft(null);
toast.success(t("dashboard.layoutSaveSuccess"));
},
onError: (err) => {
// v1.32.16 (issue #581) — a 409 means someone else (another tab, or
// an interleaved ring write) committed since this edit was based.
// Refetch the winning layout so the base token advances, KEEP the
// draft so the user can re-apply, and nudge gently instead of a hard
// error — nothing was lost, the change just needs re-saving.
// A 409 means another client committed since this edit was based.
// Refetch the winning layout so the base token advances, keep the draft,
// and let the user save the change again.
if (err instanceof ApiError && err.status === 409) {
queryClient.invalidateQueries({
queryKey: queryKeys.dashboardWidgets(),
@@ -333,7 +314,6 @@ export function DashboardLayoutSection({ id }: { id: string }) {
});
const resetMutation = useMutation({
// v1.32.16 — same scope so a reset can't race the layout / ring writes.
scope: { id: DASHBOARD_WIDGETS_MUTATION_SCOPE },
mutationFn: async () => {
return apiDelete<DashboardLayoutWithToken>("/api/dashboard/widgets");
@@ -348,6 +328,10 @@ export function DashboardLayoutSection({ id }: { id: string }) {
queryKey: queryKeys.dashboardSnapshot(),
refetchType: "all",
});
queryClient.invalidateQueries({
queryKey: queryKeys.dailyDigest(),
refetchType: "all",
});
setDraft(null);
toast.success(t("dashboard.layoutResetSuccess"));
},
@@ -383,179 +367,16 @@ export function DashboardLayoutSection({ id }: { id: string }) {
});
}
/**
* v1.4.16 phase B8 — comparison baseline picker. The toggle persists
* via the same `/api/dashboard/widgets` PUT the existing layout
* controls already use; saving rides through the same `Save` button.
*/
function setComparisonBaseline(value: ComparisonBaseline) {
function toggleHeroItem(kind: PriorityItemKind, enabled: boolean) {
if (!layout) return;
setDraft({ ...layout, comparisonBaseline: value });
}
/**
* v1.27.8 — the ring choices apply INSTANTLY, outside the draft/Save
* machine the rest of the section keeps. The first cut routed ring
* toggles through the draft, and the combination of an unflushed
* draft, the server snapshot cache, and client staleness read as
* "flipping does nothing, rings appear later". The mutation
* optimistically updates the widgets query and invalidates the
* dashboard snapshot on settle so the hero reflects the choice on the
* next visit.
*
* v1.32.1 — the PUT body used to be the FULL server layout copy,
* spreading this component's `remote` query-cache snapshot in ahead of
* the two ring fields. That snapshot can be stale by the time the
* request actually lands: if the normal
* tile/chart Save button committed a newer layout first, this
* request's explicit — present, not omitted — stale `widgets` (and
* `comparisonBaseline` / `chartOverlayPrefs`) still won on write and
* silently reverted the just-saved layout (issue #581). The payload
* now carries ONLY the ring fields; the server's preserve-when-absent
* merge (`LAYOUT_FIELD_MERGE_DISPOSITION` — `widgets` joined it in the
* same release) carries every omitted field forward from whatever is
* CURRENTLY stored, so this request can no longer race a concurrent
* Save no matter which one lands last.
*/
const ringMutation = useMutation({
// v1.32.16 (issue #581) — shared scope serialises this against the full
// layout Save so the two writes can never overlap at the server.
scope: { id: DASHBOARD_WIDGETS_MUTATION_SCOPE },
mutationFn: async (next: {
selectedScoreRings: ScoreRingId[];
heroRingOrder: HeroRingId[];
}) => {
return apiPut<DashboardLayoutWithToken>(
"/api/dashboard/widgets",
// Carries ONLY the ring fields (never `widgets`) plus the base
// token, so it can neither clobber a saved layout nor win a stale
// race — a conflict 409s instead.
buildRingMutationPayload({ ...next, baseUpdatedAt: readBaseToken() }),
);
},
onMutate: async (next) => {
await queryClient.cancelQueries({
queryKey: queryKeys.dashboardWidgets(),
});
const previous = queryClient.getQueryData<DashboardLayout>(
queryKeys.dashboardWidgets(),
);
if (previous) {
queryClient.setQueryData(queryKeys.dashboardWidgets(), {
...previous,
selectedScoreRings: next.selectedScoreRings,
heroRingOrder: next.heroRingOrder,
});
}
return { previous };
},
onError: (err, _next, context) => {
if (context?.previous) {
queryClient.setQueryData(
queryKeys.dashboardWidgets(),
context.previous,
);
}
// v1.32.16 (issue #581) — a 409 means a concurrent write landed
// first. Roll back the optimistic ring change (above), refetch the
// winning layout so the token advances, drop this now-stale delta,
// and nudge gently so the user can re-toggle against fresh state.
if (err instanceof ApiError && err.status === 409) {
queryClient.invalidateQueries({
queryKey: queryKeys.dashboardWidgets(),
});
toast.message(t("dashboard.layoutConflictReloaded"));
return;
}
toast.error(t("dashboard.layoutSaveError"));
},
onSuccess: (saved) => {
queryClient.setQueryData(queryKeys.dashboardWidgets(), saved);
// `refetchType: "all"` for the same reason as the save path: the
// unmounted snapshot cell must refetch NOW, not on its next poll.
queryClient.invalidateQueries({
queryKey: queryKeys.dashboardSnapshot(),
refetchType: "all",
});
},
});
/**
* v1.27.27 — apply a new hero ring ORDER instantly (see `ringMutation`).
* The order is the single source of truth: `selectedScoreRings` is
* derived from it (order minus the always-present health-score ring) so
* the server resolver and the hero read one consistent sequence.
*/
function applyHeroRingOrder(next: HeroRingId[]) {
// v1.32.16 (issue #581) — gate on the freshest layout (`draft ?? remote`)
// the rest of the section uses, not the `remote` server snapshot alone,
// so an open draft's edits stay the source of truth.
if (!layout) return;
const selectedScoreRings = next.filter(
(id): id is ScoreRingId => id !== HEALTH_SCORE_RING_ID,
);
// Keep an open draft's ring slice in sync so a later Save of the
// OTHER layout edits can't revert the instantly-applied choice.
if (draft) setDraft({ ...draft, selectedScoreRings, heroRingOrder: next });
ringMutation.mutate({ selectedScoreRings, heroRingOrder: next });
}
/** The reconciled hero ring order (health-score anchor + selected rings). */
function currentHeroOrder(l: DashboardLayout): HeroRingId[] {
return resolveHeroRingOrder(l.heroRingOrder, l.selectedScoreRings ?? []);
}
/**
* v1.27.7 — toggle one hero score ring on/off. Enabling appends to the
* order (capped at `MAX_SELECTED_SCORE_RINGS`; the remaining switches
* disable at the cap); disabling drops it from the order. The
* health-score ring has no toggle — it is the always-present anchor.
* v1.27.8 / v1.27.27 — applies instantly via `applyHeroRingOrder`.
*/
function toggleScoreRing(ringId: ScoreRingId, enabled: boolean) {
if (!layout) return;
const order = currentHeroOrder(layout);
if (enabled) {
if (order.includes(ringId)) return;
const selectedCount = order.filter(
(id) => id !== HEALTH_SCORE_RING_ID,
).length;
if (selectedCount >= MAX_SELECTED_SCORE_RINGS) return;
applyHeroRingOrder([...order, ringId]);
} else {
applyHeroRingOrder(order.filter((id) => id !== ringId));
}
}
/**
* v1.27.8 / v1.27.27 — reorder the hero rings (the array order IS the
* render order on the hero; the health-score anchor moves like any other
* ring). Same interaction pair as the widget rows below: drag handle +
* arrow buttons.
*/
function moveHeroRing(ringId: HeroRingId, delta: -1 | 1) {
if (!layout) return;
const order = currentHeroOrder(layout);
const idx = order.indexOf(ringId);
const target = idx + delta;
if (idx < 0 || target < 0 || target >= order.length) return;
const next = [...order];
[next[idx], next[target]] = [next[target], next[idx]];
applyHeroRingOrder(next);
}
function handleRingDragEnd(event: DragEndEvent) {
if (!layout) return;
const { active, over } = event;
if (!over || active.id === over.id) return;
const order = currentHeroOrder(layout);
const from = order.indexOf(active.id as HeroRingId);
const to = order.indexOf(over.id as HeroRingId);
if (from < 0 || to < 0) return;
const next = [...order];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved);
applyHeroRingOrder(next);
setDraft({
...layout,
enabledHeroItemKinds: setHeroItemKindEnabled(
layout.enabledHeroItemKinds,
kind,
enabled,
),
});
}
/**
@@ -631,170 +452,49 @@ export function DashboardLayoutSection({ id }: { id: string }) {
/>
}
/>
{/*
v1.4.22 D / F-32 — the surrounding `<DashboardSection>` page
already renders a `settings.sections.dashboard.description`
paragraph beneath the H1. The previous in-card help line
repeated the same idea ("Choose which cards appear …
Defaults work out of the box.") right next to the comparison
picker, giving the page three muted-foreground help blocks
stacked on top of each other. Removing this duplicate keeps
the comparison picker as the only thing between the header
and the widget table.
*/}
{/* v1.4.16 phase B8 — comparison baseline picker. Lives at the top
of the section because it changes how every chart + tile below
renders, not just one. v1.4.19 A6: height standardised to the
shared 36-px input contract used by every other Settings input
/ select; the previous `min-h-11` (44 px) made this trigger
look like an outlier next to the 36-px Username/Email/Date-of-
birth fields one card up. */}
{layout && (
<div className="space-y-2">
<label
htmlFor="comparison-baseline"
className="text-foreground text-sm font-medium"
>
{t("comparison.toggleLabel")}
</label>
<Select
value={layout.comparisonBaseline ?? "none"}
onValueChange={(value) =>
setComparisonBaseline(value as ComparisonBaseline)
}
disabled={saveMutation.isPending}
>
<SelectTrigger
id="comparison-baseline"
className="w-full sm:w-72"
data-slot="comparison-baseline-trigger"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{COMPARISON_BASELINES.map((value) => (
<SelectItem
key={value}
value={value}
data-slot={`comparison-baseline-option-${value}`}
>
{t(`comparison.baseline.${value}`)}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-muted-foreground text-xs">
{t("comparison.toggleHint")}
</p>
</div>
)}
{/* v1.27.7 — hero score-ring picker. Configures the score rings the
server computes onto the dashboard snapshot (`selectedScoreRings`
/ `heroRingOrder`), consumed by the native client. Offers only
rings whose owning module is enabled — the WIDGET_MODULE_BY_ID
gating pattern; the three derived rings additionally sit behind
the insights module, mirroring the derived routes. Selection caps
at MAX_SELECTED_SCORE_RINGS; unchecked switches disable at the cap.
v1.27.8 — choices apply instantly (no Save round) and the
selected rings reorder with the same drag-handle + arrow pair
as the widget rows below; the array order is the ring order. */}
{layout && (
<div
data-slot="score-rings-picker"
className="border-border bg-background/30 space-y-3 rounded-md border px-3 py-2"
<fieldset
aria-describedby={`${heroDescriptionId} ${heroNotificationNoteId}`}
data-slot="hero-content-settings"
className="border-border bg-background/30 space-y-3 rounded-lg border px-3 py-3"
>
<div className="min-w-0">
<p className="text-foreground text-sm font-medium">
{t("dashboard.scoreRingsTitle")}
</p>
<p className="text-muted-foreground text-xs">
{t("dashboard.scoreRingsDescription")}
</p>
</div>
{(() => {
const available = SCORE_RING_IDS.filter((ringId) => {
if (modules?.[SCORE_RING_MODULE[ringId]] === false) return false;
if (ringId !== "MED_COMPLIANCE" && modules?.insights === false)
return false;
return true;
});
const selected = (layout.selectedScoreRings ?? []).filter(
(ringId) => available.includes(ringId),
);
// v1.27.27 — the reorderable list is the health-score anchor
// ring plus the selected score rings, in the persisted order
// (health-score first by default). The health-score row has no
// on/off switch — it is always present — but drags/moves like
// any other ring.
const heroOrder = resolveHeroRingOrder(
layout.heroRingOrder,
selected,
);
const unselected = available.filter(
(ringId) => !heroOrder.includes(ringId),
);
const atCap = selected.length >= MAX_SELECTED_SCORE_RINGS;
// v1.32.16 (issue #581) — ring controls also lock while a Save
// is in flight, so the two writes can never overlap.
const busy = widgetWritesBusy(
saveMutation.isPending,
ringMutation.isPending,
);
return (
<div className="space-y-2">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleRingDragEnd}
<legend className="text-foreground text-sm font-medium">
{t("dashboard.heroItemsTitle")}
</legend>
<p id={heroDescriptionId} className="text-muted-foreground text-xs">
{t("dashboard.heroItemsDescription")}
</p>
<div className="divide-border divide-y">
{PRIORITY_ITEM_KINDS.map((kind) => {
const inputId = `hero-item-${kind}`;
const checked = (
layout.enabledHeroItemKinds ?? PRIORITY_ITEM_KINDS
).includes(kind);
return (
<div
key={kind}
className="flex min-h-11 items-center justify-between gap-3 py-2"
>
<SortableContext
items={heroOrder}
strategy={verticalListSortingStrategy}
>
{heroOrder.map((ringId, index) => (
<SortableRingRow
key={ringId}
ringId={ringId}
label={t(HERO_RING_LABEL_KEYS[ringId])}
index={index}
total={heroOrder.length}
dragHintId={dragHintId}
disabled={busy}
// The health-score ring is the anchor — no toggle.
pinned={ringId === HEALTH_SCORE_RING_ID}
moveUpLabel={t("dashboard.moveUp")}
moveDownLabel={t("dashboard.moveDown")}
dragHandleLabel={t("dashboard.dragHandle")}
onToggle={toggleScoreRing}
onMove={moveHeroRing}
/>
))}
</SortableContext>
</DndContext>
{unselected.map((ringId) => (
<div
key={ringId}
className="flex min-h-9 items-center justify-between gap-3 px-1"
>
<span className="text-foreground truncate text-sm">
{t(SCORE_RING_LABEL_KEYS[ringId])}
</span>
<Switch
checked={false}
onCheckedChange={(v) => toggleScoreRing(ringId, v)}
disabled={busy || atCap}
aria-label={t(SCORE_RING_LABEL_KEYS[ringId])}
data-slot="score-ring-switch"
data-ring={ringId}
/>
</div>
))}
</div>
);
})()}
</div>
<Label htmlFor={inputId} className="text-sm font-medium">
{t(HERO_ITEM_LABEL_KEYS[kind])}
</Label>
<Switch
id={inputId}
checked={checked}
onCheckedChange={(value) => toggleHeroItem(kind, value)}
disabled={saveMutation.isPending}
aria-label={t(HERO_ITEM_LABEL_KEYS[kind])}
data-slot="hero-item-switch"
data-kind={kind}
/>
</div>
);
})}
</div>
<p id={heroNotificationNoteId} className="text-foreground text-sm">
{t("dashboard.heroItemsNotificationNote")}
</p>
</fieldset>
)}
{isLoading || !layout ? (
@@ -997,10 +697,7 @@ export function DashboardLayoutSection({ id }: { id: string }) {
size="sm"
className="min-h-11 sm:min-h-9"
onClick={() => setDraft(null)}
disabled={widgetWritesBusy(
saveMutation.isPending,
ringMutation.isPending,
)}
disabled={saveMutation.isPending}
>
{t("common.cancel")}
</Button>
@@ -1008,12 +705,7 @@ export function DashboardLayoutSection({ id }: { id: string }) {
size="sm"
className="min-h-11 sm:min-h-9"
onClick={() => layout && saveMutation.mutate(layout)}
// v1.32.16 (issue #581) — disabled while EITHER write is in
// flight so a Save can't be issued mid ring-write and vice versa.
disabled={widgetWritesBusy(
saveMutation.isPending,
ringMutation.isPending,
)}
disabled={saveMutation.isPending}
>
{saveMutation.isPending && (
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
@@ -1027,7 +719,9 @@ export function DashboardLayoutSection({ id }: { id: string }) {
<p className="text-muted-foreground text-xs">
{layout &&
JSON.stringify(layout.widgets) ===
JSON.stringify(DEFAULT_DASHBOARD_LAYOUT.widgets)
JSON.stringify(DEFAULT_DASHBOARD_LAYOUT.widgets) &&
JSON.stringify(layout.enabledHeroItemKinds ?? PRIORITY_ITEM_KINDS) ===
JSON.stringify(DEFAULT_DASHBOARD_LAYOUT.enabledHeroItemKinds)
? t("dashboard.layoutUsingDefaults")
: t("dashboard.layoutCustomized")}
</p>
@@ -1251,121 +945,3 @@ function StaticWidgetRow({
</div>
);
}
/**
* v1.27.8 — sortable row for one SELECTED hero score ring. Mirrors the
* `SortableWidgetRow` interaction exactly (drag handle + arrow buttons +
* switch) so the two lists in this section share one sorting language;
* only the payload differs — the ring order is the `selectedScoreRings`
* array itself, applied instantly through the ring mutation.
*/
function SortableRingRow({
ringId,
label,
index,
total,
dragHintId,
disabled,
pinned = false,
moveUpLabel,
moveDownLabel,
dragHandleLabel,
onToggle,
onMove,
}: {
ringId: HeroRingId;
label: string;
index: number;
total: number;
dragHintId: string;
disabled: boolean;
/**
* v1.27.27 — the health-score anchor ring: always present, no on/off
* switch (a disabled, checked switch communicates the locked-on state),
* but reorderable like any other ring.
*/
pinned?: boolean;
moveUpLabel: string;
moveDownLabel: string;
dragHandleLabel: string;
onToggle: (id: ScoreRingId, value: boolean) => void;
onMove: (id: HeroRingId, delta: -1 | 1) => void;
}) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: ringId });
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform),
transition: prefersReducedMotion() ? "none" : transition,
};
return (
<div
ref={setNodeRef}
style={style}
data-slot="score-ring-row"
data-ring={ringId}
data-dragging={isDragging ? "true" : undefined}
className={`border-border bg-background/30 flex min-h-12 items-center gap-2 rounded-md border px-3 py-2 ${
isDragging ? "ring-primary z-10 opacity-90 shadow-lg ring-2" : ""
}`}
>
<button
type="button"
{...attributes}
{...listeners}
aria-label={`${dragHandleLabel} — ${label}`}
aria-describedby={dragHintId}
title={dragHandleLabel}
disabled={disabled}
data-slot="score-ring-drag-handle"
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring focus-visible:ring-offset-background relative -m-1 inline-flex h-7 w-7 cursor-grab touch-none items-center justify-center rounded transition-colors before:absolute before:inset-[-8px] before:content-[''] focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none"
>
<GripVertical className="h-4 w-4" />
</button>
<span className="flex-1 truncate text-sm" title={label}>
{label}
</span>
<Switch
checked
onCheckedChange={
pinned ? undefined : (v) => onToggle(ringId as ScoreRingId, v)
}
// The health-score anchor cannot be switched off — a disabled,
// checked switch reads as "always on, locked".
disabled={disabled || pinned}
aria-label={label}
data-slot="score-ring-switch"
data-ring={ringId}
/>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => onMove(ringId, -1)}
disabled={index === 0 || disabled}
aria-label={moveUpLabel}
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => onMove(ringId, 1)}
disabled={index === total - 1 || disabled}
aria-label={moveDownLabel}
>
<ArrowDown className="h-4 w-4" />
</Button>
</div>
);
}