From 6e74d38213f045878e1b8e6622c20919fb082af6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Sun, 10 May 2026 03:00:12 +0200 Subject: [PATCH] fix(design): on-surface comparison toggle on dashboard + insights (C3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 `` 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) --- src/app/insights/page.tsx | 9 ++ src/app/page.tsx | 7 ++ .../__tests__/compare-toggle.test.tsx | 91 ++++++++++++++ src/components/comparison/compare-toggle.tsx | 117 ++++++++++++++++++ 4 files changed, 224 insertions(+) create mode 100644 src/components/comparison/__tests__/compare-toggle.test.tsx create mode 100644 src/components/comparison/compare-toggle.tsx diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx index 9ceb5daab..f58a1426c 100644 --- a/src/app/insights/page.tsx +++ b/src/app/insights/page.tsx @@ -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() {
+ {/* 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. */} +
+ +
+
diff --git a/src/app/page.tsx b/src/app/page.tsx index bf86456bf..247615aa6 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -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() {
+ {/* 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. */} + + {/* v1.4: Getting-started checklist for brand-new users. * Self-gates visibility on (onboardingCompletedAt == null * || measurementCount < 5) and disappears once dismissed diff --git a/src/components/comparison/__tests__/compare-toggle.test.tsx b/src/components/comparison/__tests__/compare-toggle.test.tsx new file mode 100644 index 000000000..a0b4a34db --- /dev/null +++ b/src/components/comparison/__tests__/compare-toggle.test.tsx @@ -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( + {node}, + ); +} + +describe("", () => { + it("renders all three baseline segments", () => { + const html = render(); + 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(); + // 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(); + // 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(); + expect(html).toContain("None"); + expect(html).toContain("Last month"); + expect(html).toContain("Last year"); + }); + + it("translates the segment labels (DE)", () => { + const html = render(, "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(); + expect(html).toContain('role="group"'); + expect(html).toMatch(/aria-label="(Compare to|Vergleichen mit)"/); + }); +}); diff --git a/src/components/comparison/compare-toggle.tsx b/src/components/comparison/compare-toggle.tsx new file mode 100644 index 000000000..c9e39ccb0 --- /dev/null +++ b/src/components/comparison/compare-toggle.tsx @@ -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([ + "user", + "dashboardWidgets", + ]); + if (prev) { + queryClient.setQueryData( + ["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 ( +
+ {COMPARISON_BASELINES.map((option) => { + const active = value === option; + return ( + + ); + })} +
+ ); +}