mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 16:12:11 +00:00
fix(design): on-surface comparison toggle on dashboard + insights (C3)
The B8 comparison overlay shipped behind a Settings → Dashboard Select buried 3 clicks deep. The brief asked for "mobile-friendly comparison toggle (not a fragile hover-only interaction)" and the toggle that shipped failed that bar — flipping Vormonat / Vorjahr meant a 5-step round-trip every time. New `<CompareToggle>` segmented control (None / Vormonat / Vorjahr) sits next to the dashboard greeting and on the insights page hero. Persists via the same `/api/dashboard/widgets` PUT the Settings section already uses, with optimistic update + cache invalidation so the chart overlays + tile callouts respond instantly. 44 px (min-h-11) tap targets, focus-visible ring, role=group + aria-label for screen readers, EN+DE i18n. 6 SSR tests pin segment count, persisted-active state, tap-target floor, EN+DE labels, and ARIA shape. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
c0c1284e27
commit
6e74d38213
4 files changed
+224
No files matched your search
@@ -43,6 +43,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import { InsightStatusCard } from "@/components/insights/insight-status-card";
|
||||
import { InsightsPageHero } from "@/components/insights/insights-page-hero";
|
||||
import { CompareToggle } from "@/components/comparison/compare-toggle";
|
||||
// Recharts is ~108 KiB Brotli — defer-load it via a self-contained scatter
|
||||
// wrapper so the bundle only lands once a correlation card actually renders.
|
||||
// Every scatter card sits inside a `length >= 5` gate and below the fold,
|
||||
@@ -894,6 +895,14 @@ export default function InsightsPage() {
|
||||
<div className="space-y-8">
|
||||
<InsightsPageHero updatedAt={heroUpdatedAt} />
|
||||
|
||||
{/* v1.4.16 phase D reconcile (CRITICAL C3) — on-surface comparison
|
||||
toggle. Mirrors the dashboard placement so flipping Vormonat /
|
||||
Vorjahr is one tap on the page that uses it, not 3 clicks
|
||||
via Settings → Dashboard. */}
|
||||
<div className="flex items-center justify-end">
|
||||
<CompareToggle />
|
||||
</div>
|
||||
|
||||
<InsightsSectionNav />
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-5">
|
||||
|
||||
@@ -45,6 +45,7 @@ import { summaryToTrend7Delta } from "@/lib/analytics/trend-delta";
|
||||
import { GettingStartedChecklist } from "@/components/onboarding/getting-started-checklist";
|
||||
import { TourLauncher } from "@/components/onboarding/tour-launcher";
|
||||
import { RecentAchievementsCard } from "@/components/gamification/recent-achievements-card";
|
||||
import { CompareToggle } from "@/components/comparison/compare-toggle";
|
||||
|
||||
const HealthChart = dynamic(
|
||||
() =>
|
||||
@@ -464,6 +465,12 @@ export default function DashboardPage() {
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
{/* v1.4.16 phase D reconcile (CRITICAL C3) — on-surface comparison
|
||||
toggle. The Settings-only Select shipped in B8 was buried 3
|
||||
clicks deep; mounting the toggle here makes the Vormonat /
|
||||
Vorjahr overlay flip a single tap on the page that uses it. */}
|
||||
<CompareToggle />
|
||||
|
||||
{/* v1.4: Getting-started checklist for brand-new users.
|
||||
* Self-gates visibility on (onboardingCompletedAt == null
|
||||
* || measurementCount < 5) and disappears once dismissed
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: () => ({
|
||||
data: {
|
||||
version: 1,
|
||||
widgets: [],
|
||||
comparisonBaseline: "lastMonth" as const,
|
||||
},
|
||||
isLoading: false,
|
||||
}),
|
||||
useMutation: () => ({
|
||||
mutate: vi.fn(),
|
||||
isPending: false,
|
||||
isSuccess: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
}),
|
||||
useQueryClient: () => ({
|
||||
cancelQueries: vi.fn(),
|
||||
getQueryData: vi.fn(),
|
||||
setQueryData: vi.fn(),
|
||||
invalidateQueries: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
import { CompareToggle } from "../compare-toggle";
|
||||
|
||||
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
|
||||
return renderToStaticMarkup(
|
||||
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("<CompareToggle>", () => {
|
||||
it("renders all three baseline segments", () => {
|
||||
const html = render(<CompareToggle />);
|
||||
expect(html).toContain('data-slot="compare-toggle-option-none"');
|
||||
expect(html).toContain('data-slot="compare-toggle-option-lastMonth"');
|
||||
expect(html).toContain('data-slot="compare-toggle-option-lastYear"');
|
||||
});
|
||||
|
||||
it("marks the persisted baseline as the active segment", () => {
|
||||
const html = render(<CompareToggle />);
|
||||
// Mocked layout above persists `lastMonth`; that segment must be
|
||||
// the only one carrying aria-pressed=true / data-active="true".
|
||||
expect(html).toMatch(
|
||||
/data-slot="compare-toggle-option-lastMonth"[^>]*data-active="true"/,
|
||||
);
|
||||
expect(html).not.toMatch(
|
||||
/data-slot="compare-toggle-option-none"[^>]*data-active="true"/,
|
||||
);
|
||||
expect(html).not.toMatch(
|
||||
/data-slot="compare-toggle-option-lastYear"[^>]*data-active="true"/,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses 44px (min-h-11) tap targets per WCAG 2.5.5", () => {
|
||||
const html = render(<CompareToggle />);
|
||||
// Every segment carries the min-h-11 utility — the WCAG-compliance
|
||||
// floor we promise mobile users.
|
||||
const segmentCount = (html.match(/data-slot="compare-toggle-option-/g) ?? [])
|
||||
.length;
|
||||
const minH11Count = (html.match(/min-h-11/g) ?? []).length;
|
||||
expect(segmentCount).toBe(3);
|
||||
expect(minH11Count).toBeGreaterThanOrEqual(3);
|
||||
});
|
||||
|
||||
it("translates the segment labels (EN)", () => {
|
||||
const html = render(<CompareToggle />);
|
||||
expect(html).toContain("None");
|
||||
expect(html).toContain("Last month");
|
||||
expect(html).toContain("Last year");
|
||||
});
|
||||
|
||||
it("translates the segment labels (DE)", () => {
|
||||
const html = render(<CompareToggle />, "de");
|
||||
expect(html).toContain("Aus");
|
||||
expect(html).toContain("Vormonat");
|
||||
expect(html).toContain("Vorjahr");
|
||||
});
|
||||
|
||||
it("attaches role=group with the toggleLabel for screen readers", () => {
|
||||
const html = render(<CompareToggle />);
|
||||
expect(html).toContain('role="group"');
|
||||
expect(html).toMatch(/aria-label="(Compare to|Vergleichen mit)"/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
COMPARISON_BASELINES,
|
||||
resolveDashboardLayout,
|
||||
type ComparisonBaseline,
|
||||
type DashboardLayout,
|
||||
} from "@/lib/dashboard-layout";
|
||||
|
||||
/**
|
||||
* v1.4.16 phase D reconcile (CRITICAL C3) — on-surface comparison
|
||||
* toggle. Replaces the Settings-only Select buried 3 clicks deep with
|
||||
* a 3-segment control mounted next to the dashboard greeting and the
|
||||
* insights page hero. Persists via the same `/api/dashboard/widgets`
|
||||
* PUT the Settings page uses, so a flip on either surface updates the
|
||||
* other on next refetch.
|
||||
*
|
||||
* Hit area: each segment is `min-h-11` (44 px) per WCAG 2.5.5; pressed
|
||||
* state is the `default` button variant, idle is `outline`.
|
||||
*/
|
||||
export function CompareToggle({ className }: { className?: string }) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: layoutData } = useQuery({
|
||||
queryKey: ["user", "dashboardWidgets"],
|
||||
queryFn: async () => {
|
||||
const res = await fetch("/api/dashboard/widgets");
|
||||
if (!res.ok) throw new Error("failed");
|
||||
const json = await res.json();
|
||||
return json.data as DashboardLayout;
|
||||
},
|
||||
});
|
||||
|
||||
const layout = layoutData ? resolveDashboardLayout(layoutData) : null;
|
||||
const value: ComparisonBaseline = layout?.comparisonBaseline ?? "none";
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: async (next: ComparisonBaseline) => {
|
||||
if (!layout) throw new Error("layout-not-loaded");
|
||||
const body: DashboardLayout = { ...layout, comparisonBaseline: next };
|
||||
const res = await fetch("/api/dashboard/widgets", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) throw new Error("save-failed");
|
||||
return (await res.json()).data as DashboardLayout;
|
||||
},
|
||||
onMutate: async (next) => {
|
||||
await queryClient.cancelQueries({
|
||||
queryKey: ["user", "dashboardWidgets"],
|
||||
});
|
||||
const prev = queryClient.getQueryData<DashboardLayout>([
|
||||
"user",
|
||||
"dashboardWidgets",
|
||||
]);
|
||||
if (prev) {
|
||||
queryClient.setQueryData<DashboardLayout>(
|
||||
["user", "dashboardWidgets"],
|
||||
{ ...prev, comparisonBaseline: next },
|
||||
);
|
||||
}
|
||||
return { prev };
|
||||
},
|
||||
onError: (_err, _next, ctx) => {
|
||||
if (ctx?.prev) {
|
||||
queryClient.setQueryData(["user", "dashboardWidgets"], ctx.prev);
|
||||
}
|
||||
},
|
||||
onSettled: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["user", "dashboardWidgets"] });
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t("comparison.toggleLabel")}
|
||||
data-slot="compare-toggle"
|
||||
className={cn(
|
||||
"border-border bg-background inline-flex flex-wrap items-center gap-0.5 rounded-md border p-0.5",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{COMPARISON_BASELINES.map((option) => {
|
||||
const active = value === option;
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
type="button"
|
||||
data-slot={`compare-toggle-option-${option}`}
|
||||
data-active={active ? "true" : undefined}
|
||||
aria-pressed={active}
|
||||
disabled={mutation.isPending || !layout}
|
||||
onClick={() => {
|
||||
if (!active) mutation.mutate(option);
|
||||
}}
|
||||
className={cn(
|
||||
"min-h-11 rounded px-3 text-xs font-medium transition-colors",
|
||||
"focus-visible:ring-ring/50 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none",
|
||||
active
|
||||
? "bg-primary text-primary-foreground"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-accent",
|
||||
mutation.isPending && "cursor-progress",
|
||||
)}
|
||||
>
|
||||
{t(`comparison.baseline.${option}`)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user