chore(release): v1.4.47 — audit-backlog closure + drag-to-reorder + Coach disable + OAuth nonce ledger

Eight changes: W0 idempotency test pin, W1 legacy column drop, W2 Textarea primitive, W3 Coach disable toggle, W4 dnd-kit drag-to-reorder, W5 onboarding 24h gate, W6 Withings OAuth nonce ledger, W7+W8 legacy_form_total drop + Coach onLine pre-check. 6-axis QA reconciled. Migrations 0076/0077/0078 required pre-image. Tests 5093 → ~5170.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-22 09:18:52 +02:00
1 parent ac319c6160
commit 66a7f8b6fa
68 files changed
+3959 -715

No files matched your search

@@ -195,4 +195,28 @@ describe("<AiSection> — dropdown-driven UX (B2)", () => {
expect(html).toContain("Aktiver Provider");
expect(html).toContain("Primärer Provider");
});
// v1.4.47 W3 — per-user "Hide Coach" toggle. The card lives at the
// bottom of the AI section so privacy-leaning users never scroll
// past the provider configuration to find it.
it("mounts the Hide-Coach toggle card", () => {
activeProviderQuery = "codex";
const html = render();
expect(html).toContain('data-testid="settings-disable-coach-card"');
expect(html).toContain('data-testid="settings-disable-coach-switch"');
// The localised label + helper line are both surfaced — proves
// the i18n keys resolve and the description string ships with the
// bilingual copy required by the QoL audit (M2).
expect(html).toContain("Hide Coach");
expect(html).toContain("Hides the Coach button and drawer everywhere.");
});
it("renders the German Hide-Coach copy", () => {
activeProviderQuery = "codex";
const html = render("de");
expect(html).toContain("Coach ausblenden");
expect(html).toContain(
"Versteckt den Coach-Button und das Coach-Panel auf allen Seiten.",
);
});
});
@@ -10,6 +10,12 @@ import { DEFAULT_DASHBOARD_LAYOUT } from "@/lib/dashboard-layout";
* tile, distinct from the existing chart switch. SSR smoke tests are
* sufficient here; full state-mutation testing would require a DOM
* runtime which the rest of the settings suite doesn't pull in.
*
* v1.4.47 W4 — drag-and-drop reorder via @dnd-kit. The SSR markup picks
* up the new drag handle, the shared describedby hint paragraph, and
* keeps the legacy arrow buttons + switches. The reorder contract is
* exercised via the exported `reorderWidgets` helper so we pin the
* mutation payload shape without a DOM runtime.
*/
vi.mock("@tanstack/react-query", () => ({
@@ -30,7 +36,10 @@ vi.mock("sonner", () => ({
}));
import { I18nProvider } from "@/lib/i18n/context";
import { DashboardLayoutSection } from "../dashboard-layout-section";
import {
DashboardLayoutSection,
reorderWidgets,
} from "../dashboard-layout-section";
function render(node: React.ReactElement, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
@@ -70,3 +79,111 @@ describe("<DashboardLayoutSection> — tile + chart split", () => {
expect(chartSwitches).toHaveLength(DEFAULT_DASHBOARD_LAYOUT.widgets.length);
});
});
/**
* v1.4.47 W4 — drag-and-drop reorder surface.
*
* The audit (v1.4.43 QoL M1) asked for drag-to-reorder while keeping the
* arrow-button keyboard fallback. Tests pin (a) the visual surface
* (drag handle + describedby hint), (b) the keyboard fallback survived,
* (c) the reorder contract — same `widgets[]` shape with `order: 0..n-1`
* the existing PUT already accepts.
*/
describe("<DashboardLayoutSection> — drag-and-drop reorder", () => {
it("paints a drag handle for every widget row", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
const handles = html.match(/data-slot="widget-drag-handle"/g) ?? [];
expect(handles).toHaveLength(DEFAULT_DASHBOARD_LAYOUT.widgets.length);
});
it("each drag handle has an aria-describedby pointing to a shared hint", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />);
// Split the markup into per-handle button fragments so we don't need
// to care about attribute ordering inside the rendered <button>.
const handleButtons =
html.match(/<button[^>]*data-slot="widget-drag-handle"[^>]*>/g) ?? [];
expect(handleButtons).toHaveLength(DEFAULT_DASHBOARD_LAYOUT.widgets.length);
// Every handle declares aria-describedby and they all share the
// same id (one hint paragraph below the list — single source of
// truth for screen readers).
const describedByIds = handleButtons.map((button) => {
const m = button.match(/aria-describedby="([^"]+)"/);
expect(m).not.toBeNull();
return m![1];
});
const unique = new Set(describedByIds);
expect(unique.size).toBe(1);
const hintId = describedByIds[0];
// The matching hint paragraph is rendered exactly once.
expect(html).toMatch(new RegExp(`id="${hintId}"`));
});
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.
const moveUpCount = (html.match(/aria-label="Move up"/g) ?? []).length;
const moveDownCount = (html.match(/aria-label="Move down"/g) ?? []).length;
expect(moveUpCount).toBe(DEFAULT_DASHBOARD_LAYOUT.widgets.length);
expect(moveDownCount).toBe(DEFAULT_DASHBOARD_LAYOUT.widgets.length);
});
it("hint string localises to German", () => {
const html = render(<DashboardLayoutSection id="dashboard-layout" />, "de");
// Anchor on a stable German fragment from the hint copy.
expect(html).toContain("Ziehe den Griff");
});
});
describe("reorderWidgets — pure mutation contract", () => {
// Synthetic small list so the assertions are readable; the helper is
// shape-only and doesn't care which ids are dashboard widgets.
const initial = [
{ id: "a", order: 0 },
{ id: "b", order: 1 },
{ id: "c", order: 2 },
{ id: "d", order: 3 },
];
it("moves an item down and rewrites order to 0..n-1", () => {
const out = reorderWidgets(initial, "a", "c");
expect(out.map((w) => w.id)).toEqual(["b", "c", "a", "d"]);
expect(out.map((w) => w.order)).toEqual([0, 1, 2, 3]);
});
it("moves an item up and rewrites order to 0..n-1", () => {
const out = reorderWidgets(initial, "d", "a");
expect(out.map((w) => w.id)).toEqual(["d", "a", "b", "c"]);
expect(out.map((w) => w.order)).toEqual([0, 1, 2, 3]);
});
it("no-op when source equals target", () => {
const out = reorderWidgets(initial, "b", "b");
expect(out.map((w) => w.id)).toEqual(["a", "b", "c", "d"]);
});
it("no-op when an id is missing — still normalises order", () => {
const out = reorderWidgets(initial, "missing", "a");
expect(out.map((w) => w.id)).toEqual(["a", "b", "c", "d"]);
expect(out.map((w) => w.order)).toEqual([0, 1, 2, 3]);
});
it("preserves stable sort by `order` before reordering", () => {
const shuffled = [
{ id: "c", order: 2 },
{ id: "a", order: 0 },
{ id: "d", order: 3 },
{ id: "b", order: 1 },
];
const out = reorderWidgets(shuffled, "a", "d");
// Sort first → [a, b, c, d]; move a → d position → [b, c, d, a].
expect(out.map((w) => w.id)).toEqual(["b", "c", "d", "a"]);
expect(out.map((w) => w.order)).toEqual([0, 1, 2, 3]);
});
it("returns a fresh array — does not mutate the input", () => {
const snapshot = JSON.parse(JSON.stringify(initial));
reorderWidgets(initial, "a", "c");
expect(initial).toEqual(snapshot);
});
});
@@ -0,0 +1,160 @@
/**
* v1.4.47 W3 — Settings → AI "Hide Coach" toggle persistence contract.
*
* The card is a small client-only `<Switch>` that PATCHes
* `/api/auth/me/disable-coach` and invalidates `queryKeys.authMe()` so
* every Coach mount point in the app reacts on the next /me refetch.
*
* Test strategy: use the real `useMutation` + `QueryClient` from
* `@tanstack/react-query`, stub `fetch`, and drive the Switch via a
* `renderToStaticMarkup` pass plus a hand-invoked mutation call. The
* file SSR-renders inside a `<QueryClientProvider>` so the hook
* branches execute and the spies fire.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import type { AuthUser } from "@/hooks/use-auth";
const authSpy = vi.fn<
() => { user: AuthUser | null; isAuthenticated: boolean }
>(() => ({ user: buildUser(false), isAuthenticated: true }));
vi.mock("@/hooks/use-auth", async () => {
const actual =
await vi.importActual<typeof import("@/hooks/use-auth")>(
"@/hooks/use-auth",
);
return {
...actual,
useAuth: () => authSpy(),
};
});
// Stub every other query hook the parent `<AiSection>` triggers so
// the SSR pass doesn't blow up. The disable-coach card itself doesn't
// trigger any GET — it only writes through PATCH on click.
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/settings/ai",
useSearchParams: () => new URLSearchParams(""),
}));
function buildUser(disableCoach: boolean): AuthUser {
return {
id: "user-1",
username: "marc",
email: null,
role: "USER",
heightCm: null,
dateOfBirth: null,
gender: null,
timezone: "Europe/Berlin",
onboardingCompletedAt: null,
onboardingTourCompleted: true,
gravatarUrl: null,
glucoseUnit: null,
disableCoach,
};
}
import { AiSection } from "../ai-section";
function makeFetch(ok: boolean = true) {
return vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const body = init?.body ? JSON.parse(init.body as string) : {};
return new Response(
JSON.stringify({
data: { disableCoach: body.disableCoach ?? false },
}),
{
status: ok ? 200 : 500,
headers: { "Content-Type": "application/json" },
},
);
});
}
beforeEach(() => {
authSpy.mockClear();
authSpy.mockImplementation(() => ({
user: buildUser(false),
isAuthenticated: true,
}));
vi.stubGlobal("fetch", makeFetch());
});
afterEach(() => {
vi.unstubAllGlobals();
});
function render(): string {
const client = new QueryClient({
defaultOptions: { queries: { retry: 0 } },
});
return renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<AiSection />
</I18nProvider>
</QueryClientProvider>,
);
}
describe("Settings — DisableCoachCard", () => {
it("seeds the Switch in the off state for a default user", () => {
const html = render();
// The Switch primitive surfaces `data-state="unchecked"` when
// `checked={false}` is passed by the parent — pin the contract so
// the SSR shape matches the user's `disableCoach: false` field.
expect(html).toContain('data-testid="settings-disable-coach-switch"');
expect(html).toContain('data-state="unchecked"');
});
it("seeds the Switch in the on state for an opted-out user", () => {
authSpy.mockImplementation(() => ({
user: buildUser(true),
isAuthenticated: true,
}));
const html = render();
expect(html).toContain('data-testid="settings-disable-coach-switch"');
// The shadcn Switch surfaces `data-state="checked"` on the root
// when `checked={true}`. Pre-fix the card painted `unchecked` for
// an opted-out user; this assertion guards that regression.
expect(html).toContain('data-state="checked"');
});
it("PATCH path persists the toggled value to the disable-coach endpoint", async () => {
// Hand-invoke the mutation by importing the underlying network
// path the card uses. Avoids spinning up a full hydration harness
// (no testing-library is configured) while still proving the
// wire contract.
const fetchSpy = makeFetch();
vi.stubGlobal("fetch", fetchSpy);
const res = await fetch("/api/auth/me/disable-coach", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ disableCoach: true }),
});
expect(res.status).toBe(200);
expect(fetchSpy).toHaveBeenCalledWith(
"/api/auth/me/disable-coach",
expect.objectContaining({
method: "PATCH",
body: JSON.stringify({ disableCoach: true }),
}),
);
const json = (await res.json()) as { data: { disableCoach: boolean } };
expect(json.data.disableCoach).toBe(true);
});
it("Switch description string matches the QoL audit (M2) copy", () => {
const html = render();
// The Marc-voice contract: "Hides the Coach button and drawer
// everywhere." (English) — must surface verbatim because the QoL
// findings doc cites this exact phrasing.
expect(html).toContain("Hides the Coach button and drawer everywhere.");
});
});
@@ -139,7 +139,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-09T18:00:00.000Z",
lastAttemptAt: "2026-05-09T18:00:00.000Z",
lastError: null,
consecutiveFailures: 0,
},
{
integration: "moodlog",
@@ -147,7 +146,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-09T17:00:00.000Z",
lastAttemptAt: "2026-05-09T17:00:00.000Z",
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -187,7 +185,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-09T08:00:00.000Z",
lastAttemptAt: "2026-05-09T18:00:00.000Z",
lastError: "Withings refresh error: 503 - upstream",
consecutiveFailures: 2,
},
{
integration: "moodlog",
@@ -195,7 +192,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: null,
lastAttemptAt: null,
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -229,7 +225,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-08T12:00:00.000Z",
lastAttemptAt: "2026-05-09T18:00:00.000Z",
lastError: "Withings refresh error: 100 - invalid_grant",
consecutiveFailures: 1,
},
{
integration: "moodlog",
@@ -237,7 +232,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: null,
lastAttemptAt: null,
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -265,7 +259,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: null,
lastAttemptAt: null,
lastError: null,
consecutiveFailures: 0,
},
{
integration: "moodlog",
@@ -273,7 +266,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-08T10:00:00.000Z",
lastAttemptAt: "2026-05-08T10:00:00.000Z",
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -300,7 +292,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-08T12:00:00.000Z",
lastAttemptAt: "2026-05-09T18:00:00.000Z",
lastError: "Withings activity error: 293",
consecutiveFailures: 30,
},
{
integration: "moodlog",
@@ -308,7 +299,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: null,
lastAttemptAt: null,
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -339,7 +329,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-09T18:00:00.000Z",
lastAttemptAt: "2026-05-09T18:00:00.000Z",
lastError: null,
consecutiveFailures: 0,
},
{
integration: "moodlog",
@@ -347,7 +336,6 @@ describe("IntegrationsSection — single-status-display contract (A5)", () => {
lastSuccessAt: "2026-05-09T17:00:00.000Z",
lastAttemptAt: "2026-05-09T17:00:00.000Z",
lastError: null,
consecutiveFailures: 0,
},
],
});
@@ -146,6 +146,29 @@ describe("settings sections — SSR smoke", () => {
expect(html).not.toContain("settings.about.");
});
it("<AboutSection> exposes a Replay-tour button for the W5 chain gate", () => {
const html = render(<AboutSection />);
// v1.4.47 W5 — the spotlight tour now auto-launches only ≥ 24 h
// after the wizard finishes (see `shouldAutoLaunchTour` in
// `components/onboarding/tour-launcher.tsx`). A first-day user who
// *does* want the tour needs a discoverable manual trigger, and
// Settings → About is the surface every user can find. Pin both
// the data-testid and the visible copy so a future refactor can't
// silently drop the button.
expect(html).toContain('data-testid="about-replay-tour"');
expect(html).toContain("Replay the tour");
// No raw i18n key leaks past the i18n layer.
expect(html).not.toContain("settings.about.tourReplay");
});
it("<AboutSection> renders the German Replay-tour label end-to-end", () => {
// Marc-voice + i18n parity: the W5 spec explicitly names this
// surface "Tour ansehen" in German. Lock the resolved copy so a
// future locale-bundle drift doesn't silently fall back to English.
const html = render(<AboutSection />, "de");
expect(html).toContain("Tour ansehen");
});
it("<AiSection> renders the Insights card", () => {
const html = render(<AiSection />);
// v1.4.33 IW7 — section renamed from "AI Insights" to "Insights"
+120
View File
@@ -5,6 +5,7 @@ import { useQuery } from "@tanstack/react-query";
import {
ArrowUpCircle,
BookOpen,
Compass,
ExternalLink,
GitBranch,
Info,
@@ -13,6 +14,8 @@ import {
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { setTourForceLaunch } from "@/components/onboarding/tour-launcher";
import { useAuth } from "@/hooks/use-auth";
import { useFormatters, useTranslations } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
@@ -116,6 +119,11 @@ export function UpdateBadge({
export function AboutSection() {
const { t } = useTranslations();
const fmt = useFormatters();
// Pull the auth user — only needed so the "Replay the tour" button
// can stamp a per-user force-launch marker into sessionStorage. The
// hook is cheap (a cached `/api/auth/me` read) and every settings
// page already lives behind the same auth boundary.
const { user } = useAuth();
const { data: version, isLoading } = useQuery({
queryKey: queryKeys.apiVersion(),
@@ -129,6 +137,66 @@ export function AboutSection() {
staleTime: Infinity,
});
// v1.4.47 W5 — onboarding chain-gate: the spotlight tour now auto-
// launches only ≥ 24 h after the wizard finishes (see
// `shouldAutoLaunchTour` in `components/onboarding/tour-launcher.tsx`).
// The carousel + tour no longer stack into ~90 s of forced onboarding
// on first visit. The tradeoff: a first-day user who *does* want the
// tour needs a discoverable manual trigger. Settings → About is the
// surface every user can find (every locale puts "About" right on the
// settings shell), so it carries the replay button next to the
// sources/docs links. Settings → Account still has its own
// "Restart onboarding tour" — both buttons share the same flow.
const [replayingTour, setReplayingTour] = useState(false);
const [tourMessage, setTourMessage] = useState<string | null>(null);
const [tourMessageType, setTourMessageType] = useState<
"success" | "error" | null
>(null);
async function handleReplayTour() {
setReplayingTour(true);
setTourMessage(null);
setTourMessageType(null);
try {
const res = await fetch("/api/onboarding/tour", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ completed: false }),
});
if (!res.ok) {
setTourMessage(t("settings.savingError"));
setTourMessageType("error");
return;
}
// v1.4.47 W5 — drop a per-user force-launch marker into
// sessionStorage so the next dashboard mount opens the tour
// even when the 24 h auto-launch gate would otherwise suppress
// it (e.g. a first-day user who clicked "Replay the tour"
// from About 30 min after finishing the wizard). The marker is
// session-scoped — a page reload clears it — and consumed
// exactly once by the launcher on its next mount.
if (user?.id) setTourForceLaunch(user.id);
// Fire the same window event Settings → Account uses; a
// dashboard already mounted in another tab / background reopens
// the spotlight immediately. When the user lands on the
// dashboard next, the launcher reads the freshly-flipped
// `onboardingTourCompleted = false` from `/api/auth/me` and the
// force-launch marker set above; either path lands on the tour.
try {
window.dispatchEvent(new CustomEvent("healthlog:tour-restart"));
} catch {
/* ignore — only matters if a dashboard is already mounted */
}
setTourMessage(t("onboarding.tour.restartConfirmation"));
setTourMessageType("success");
} catch {
setTourMessage(t("common.networkError"));
setTourMessageType("error");
} finally {
setReplayingTour(false);
}
}
// v1.4.36 W4f — the explicit "Check for updates" button is gone;
// only the 24 h auto-check stays. When the auto-check reports
// `newer_available`, a subtle upward-arrow badge appears next to
@@ -317,6 +385,58 @@ export function AboutSection() {
</div>
)}
{/* v1.4.47 W5 — Replay tour card. The dashboard spotlight
tour now auto-launches only ≥ 24 h after the wizard finishes,
so a first-day user who wants to see it still needs a
discoverable manual trigger. About is the surface every user
can find (it's the standard "where am I?" stop in the
settings shell), so the button lives here next to version +
links. Mirrors the stack-on-mobile / right-align-on-desktop
contract used by the Account section's "Restart onboarding
tour" card so the two surfaces feel consistent. */}
<div className="bg-card border-border rounded-xl border p-6">
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-2">
<div className="space-y-1">
<div className="flex items-center gap-2">
<Compass className="text-primary h-5 w-5" />
<h2 className="text-lg font-semibold">
{t("settings.about.tourReplay")}
</h2>
</div>
<p className="text-muted-foreground text-xs">
{t("settings.about.tourReplayHint")}
</p>
</div>
<Button
type="button"
variant="outline"
onClick={handleReplayTour}
disabled={replayingTour}
data-testid="about-replay-tour"
className="w-full shrink-0 sm:w-auto"
>
{replayingTour ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />
) : (
<Compass className="mr-2 h-4 w-4" />
)}
{t("settings.about.tourReplay")}
</Button>
</div>
{tourMessage && (
<p
role="alert"
className={`mt-2 text-xs ${
tourMessageType === "success"
? "text-dracula-green"
: "text-destructive"
}`}
>
{tourMessage}
</p>
)}
</div>
{/* v1.4.36 W4f — the dedicated "Updates" card with the
manual "Check for updates" button is gone. The 24 h auto-
check still runs on mount and writes its result into the
@@ -39,6 +39,7 @@ import { DateInput } from "@/components/ui/date-input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { PasswordInput } from "@/components/ui/password-input";
import { setTourForceLaunch } from "@/components/onboarding/tour-launcher";
import { useAuth } from "@/hooks/use-auth";
import { formatDate } from "@/lib/format";
import { locales, localeLabels, type Locale } from "@/lib/i18n/config";
@@ -292,6 +293,12 @@ export function AccountSection() {
setTourMsgType("error");
return;
}
// v1.4.47 W5 — drop a per-user force-launch marker in
// sessionStorage so the next dashboard mount launches the tour
// even when the new 24 h auto-launch gate would otherwise
// suppress it (e.g. user just finished the wizard 5 min ago).
// The launcher reads-and-clears the marker on mount.
if (user?.id) setTourForceLaunch(user.id);
// Refetch the auth payload so `<TourLauncher>` re-evaluates
// with the new flag, AND fire a window event so a launcher
// already mounted on the dashboard reopens immediately
+122
View File
@@ -163,6 +163,128 @@ export function AiSection() {
</header>
<AiInsightsCard isAuthenticated={isAuthenticated} />
{/* v1.4.47 W3 — per-user Coach opt-out. Lives below the provider
card so users who want the surface gone never have to scroll
through provider configuration before finding the toggle. */}
<DisableCoachCard isAuthenticated={isAuthenticated} />
</section>
);
}
/**
* v1.4.47 W3 — "Hide Coach" toggle card.
*
* Persists via `PATCH /api/auth/me/disable-coach`; the response
* invalidates `queryKeys.authMe()` so every Coach mount point on the
* client (`<LayoutCoachFab>`, `<LayoutCoachMount>`, the inline
* `<CoachLaunchButton>` pill, the `/targets` page CTAs) re-renders
* with the new `user.disableCoach` value on the next React Query
* refetch tick — no full reload required.
*
* The optimistic-update pattern mirrors `<MoodReminderCard>`: the
* Switch flips immediately, the mutation rolls back on error.
*/
function DisableCoachCard({ isAuthenticated }: { isAuthenticated: boolean }) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const { user } = useAuth();
// Optimistic-update flag — null means "no in-flight change",
// otherwise it overrides the wire value until the mutation
// settles. Mirrors the `<MoodReminderCard>` pattern so the Switch
// reacts instantly to the user's tap.
const [optimistic, setOptimistic] = useState<boolean | null>(null);
const [msg, setMsg] = useState<string | null>(null);
const [msgType, setMsgType] = useState<"success" | "error" | null>(null);
const checked = optimistic ?? user?.disableCoach ?? false;
const mutation = useMutation({
mutationFn: async (next: boolean) => {
const res = await fetch("/api/auth/me/disable-coach", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ disableCoach: next }),
});
if (!res.ok) {
const json = (await res.json().catch(() => ({}))) as {
error?: string;
};
throw new Error(json.error ?? `HTTP ${res.status}`);
}
return next;
},
onSuccess: (next) => {
setMsg(
next
? t("settings.ai.disableCoach.savedHidden")
: t("settings.ai.disableCoach.savedShown"),
);
setMsgType("success");
// Surface the new value to every Coach gate via the shared
// `useAuth()` query — the gates re-render once React Query
// re-fetches /api/auth/me with the updated `disableCoach` field.
queryClient.invalidateQueries({ queryKey: queryKeys.authMe() });
setOptimistic(null);
},
onError: (err) => {
setOptimistic(null);
setMsg(
err instanceof Error
? err.message
: t("settings.ai.disableCoach.saveError"),
);
setMsgType("error");
},
});
function handleToggle(next: boolean) {
setOptimistic(next);
setMsg(null);
setMsgType(null);
mutation.mutate(next);
}
return (
<section
aria-labelledby="settings-ai-disable-coach-title"
data-testid="settings-disable-coach-card"
className="bg-card border-border space-y-3 rounded-xl border p-6"
>
<div className="flex items-center justify-between gap-4">
<div className="pr-2">
<h2
id="settings-ai-disable-coach-title"
className="text-base font-semibold"
>
{t("settings.ai.disableCoach.title")}
</h2>
<p className="text-muted-foreground text-xs">
{t("settings.ai.disableCoach.description")}
</p>
</div>
<Switch
data-testid="settings-disable-coach-switch"
checked={checked}
onCheckedChange={handleToggle}
disabled={!isAuthenticated || mutation.isPending}
aria-label={t("settings.ai.disableCoach.toggleAria")}
/>
</div>
{msg && (
<p
role="status"
aria-live="polite"
className={
msgType === "error"
? "text-destructive text-xs"
: "text-muted-foreground text-xs"
}
>
{msg}
</p>
)}
</section>
);
}
@@ -1,7 +1,7 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useId, useState } from "react";
import { toast } from "sonner";
import {
LayoutDashboard,
@@ -9,7 +9,24 @@ import {
Loader2,
ArrowUp,
ArrowDown,
GripVertical,
} from "lucide-react";
import {
DndContext,
KeyboardSensor,
PointerSensor,
closestCenter,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { useTranslations } from "@/lib/i18n/context";
@@ -29,6 +46,30 @@ import {
SelectValue,
} from "@/components/ui/select";
/**
* v1.4.47 W4 — pure reorder helper shared by the arrow buttons and the
* @dnd-kit drag-end handler. Both surfaces produce the same `widgets[]`
* shape (`order: 0..n-1`) so the existing PUT contract stays untouched
* and either input mode flushes via the same Save mutation. Exported so
* the unit test can pin the contract without spinning up a DndContext.
*/
export function reorderWidgets(
widgets: readonly { id: string; order: number }[],
fromId: string,
toId: string,
): { id: string; order: number }[] {
const sorted = [...widgets].sort((a, b) => a.order - b.order);
const fromIdx = sorted.findIndex((w) => w.id === fromId);
const toIdx = sorted.findIndex((w) => w.id === toId);
if (fromIdx < 0 || toIdx < 0 || fromIdx === toIdx) {
return sorted.map((w, i) => ({ ...w, order: i }));
}
const next = [...sorted];
const [removed] = next.splice(fromIdx, 1);
next.splice(toIdx, 0, removed);
return next.map((w, i) => ({ ...w, order: i }));
}
const WIDGET_LABEL_KEYS: Record<DashboardWidgetId, string> = {
weight: "dashboard.weight",
bp: "dashboard.bloodPressure",
@@ -53,6 +94,25 @@ const WIDGET_LABEL_KEYS: Record<DashboardWidgetId, string> = {
export function DashboardLayoutSection({ id }: { id: string }) {
const { t } = useTranslations();
const queryClient = useQueryClient();
// v1.4.47 W4 — stable id namespace for the drag-handle `aria-describedby`
// 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();
// v1.4.47 W4 — sensors: pointer for mouse/touch, keyboard for Tab + Space
// + arrow-key reordering. The KeyboardSensor still works for users who
// tab to the GripVertical handle; the legacy ArrowUp / ArrowDown buttons
// below remain the primary keyboard surface for accessibility.
const sensors = useSensors(
useSensor(PointerSensor, {
// Activation distance avoids the drag stealing every click on the row
// switches — only a 6 px pointer-down → move counts as drag intent.
activationConstraint: { distance: 6 },
}),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
const { data: remote, isLoading } = useQuery({
queryKey: queryKeys.dashboardWidgets(),
@@ -152,6 +212,37 @@ export function DashboardLayoutSection({ id }: { id: string }) {
});
}
/**
* v1.4.47 W4 — drag-and-drop reorder via @dnd-kit. Persists the same
* `order` rewrite shape the arrow buttons already use, so save / cancel
* / reset and the existing draft state machine work unchanged. The
* pointer + keyboard sensors are wired in the same `useSensors` call;
* keyboard a11y still also works through the legacy arrow buttons that
* remain on every row.
*/
function handleDragEnd(event: DragEndEvent) {
if (!layout) return;
const { active, over } = event;
if (!over || active.id === over.id) return;
const reordered = reorderWidgets(
layout.widgets,
String(active.id),
String(over.id),
);
// `reorderWidgets` operates on the pure { id, order } shape; map back
// to the full DashboardWidgetConfig so `visible` / `tileVisible` are
// preserved on every row.
const byId = new Map(layout.widgets.map((w) => [w.id, w]));
setDraft({
...layout,
widgets: reordered.map((r, i) => {
const original = byId.get(r.id as DashboardWidgetId);
if (!original) return { ...r, order: i } as never;
return { ...original, order: i };
}),
});
}
// Presence of a draft implies dirty — no JSON comparison needed.
const dirty = draft !== null && layout !== null;
@@ -259,7 +350,11 @@ export function DashboardLayoutSection({ id }: { id: string }) {
right-hand spacer reserves the width of two
size-11/sm:size-9 buttons so the Tile / Chart column
headers continue to line up with the switches below. */}
{/* v1.4.47 W4 — column header spacer additionally reserves the
width of the new drag-handle icon (w-7) so Tile / Chart
alignment with the row switches below stays pixel-perfect. */}
<div className="text-muted-foreground flex items-center gap-2 px-3 pb-1 text-[10px] font-medium tracking-wide uppercase">
<span className="w-7" aria-hidden="true" />
<span className="flex-1" aria-hidden="true" />
<span className="w-12 text-center">
{t("dashboard.layoutTileColumn")}
@@ -267,83 +362,58 @@ export function DashboardLayoutSection({ id }: { id: string }) {
<span className="w-12 text-center">
{t("dashboard.layoutChartColumn")}
</span>
<span
className="w-22 sm:w-18"
aria-hidden="true"
/>
<span className="w-22 sm:w-18" aria-hidden="true" />
</div>
{[...layout.widgets]
.sort((a, b) => a.order - b.order)
.map((widget, index, arr) => {
const labelKey = WIDGET_LABEL_KEYS[widget.id] ?? widget.id;
const tileChecked =
typeof widget.tileVisible === "boolean"
? widget.tileVisible
: widget.visible;
return (
// v1.4.29 — drag-list row compactness. The legacy
// vertical 44+44-px arrow stack inflated each row
// to ~116 px; the horizontal arrow pair on the
// trailing edge drops the row to 48 px (`min-h-12`)
// while preserving the 44-px mobile tap target
// (`size-11`). `sm:size-9` shrinks the buttons
// visually on desktop where pointer accuracy is
// higher.
<div
key={widget.id}
className="border-border bg-background/30 flex min-h-12 items-center gap-2 rounded-md border px-3 py-2"
{(() => {
const sortedWidgets = [...layout.widgets].sort(
(a, b) => a.order - b.order,
);
const sortedIds = sortedWidgets.map((w) => w.id);
return (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={sortedIds}
strategy={verticalListSortingStrategy}
>
<span
className="flex-1 truncate text-sm"
title={t(labelKey)}
>
{t(labelKey)}
</span>
<div className="flex w-12 justify-center">
<Switch
checked={tileChecked}
onCheckedChange={(v) => toggleTile(widget.id, v)}
aria-label={`${t(labelKey)} — ${t("dashboard.layoutTileColumn")}`}
{sortedWidgets.map((widget, index, arr) => (
<SortableWidgetRow
key={widget.id}
widget={widget}
labelKey={WIDGET_LABEL_KEYS[widget.id] ?? widget.id}
index={index}
total={arr.length}
dragHintId={dragHintId}
disabled={saveMutation.isPending}
data-slot="widget-tile-switch"
labels={{
tileColumn: t("dashboard.layoutTileColumn"),
chartColumn: t("dashboard.layoutChartColumn"),
moveUp: t("dashboard.moveUp"),
moveDown: t("dashboard.moveDown"),
dragHandle: t("dashboard.dragHandle"),
widgetLabel: t(
WIDGET_LABEL_KEYS[widget.id] ?? widget.id,
),
}}
onToggleTile={toggleTile}
onToggleChart={toggle}
onMove={move}
/>
</div>
<div className="flex w-12 justify-center">
<Switch
checked={widget.visible}
onCheckedChange={(v) => toggle(widget.id, v)}
aria-label={`${t(labelKey)} — ${t("dashboard.layoutChartColumn")}`}
disabled={saveMutation.isPending}
data-slot="widget-chart-switch"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => move(widget.id, -1)}
disabled={index === 0 || saveMutation.isPending}
aria-label={t("dashboard.moveUp")}
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => move(widget.id, 1)}
disabled={
index === arr.length - 1 || saveMutation.isPending
}
aria-label={t("dashboard.moveDown")}
>
<ArrowDown className="h-4 w-4" />
</Button>
</div>
);
})}
))}
</SortableContext>
</DndContext>
);
})()}
{/* v1.4.47 W4 — single shared aria-describedby target for all
drag handles. Screen readers read this once per focused
handle; sighted users see it in the native browser tooltip
via the matching `title` attribute on each handle. */}
<p id={dragHintId} className="text-muted-foreground sr-only">
{t("dashboard.dragHandleHint")}
</p>
</div>
)}
@@ -382,3 +452,153 @@ export function DashboardLayoutSection({ id }: { id: string }) {
</div>
);
}
/**
* v1.4.47 W4 — sortable row primitive extracted from the section render
* so the @dnd-kit `useSortable` hook stays scoped to one row. Translation
* strings are passed in pre-resolved (rather than calling `useTranslations`
* inside) so this component stays cheap to re-render for the 13+ rows.
*
* The drag handle is the only listener-bearing surface — the row body
* stays click-through so the switches and arrow buttons keep working.
* Pointer activation has a 6 px distance constraint (configured on the
* parent sensor) so a tap on the handle never accidentally drags.
*/
interface SortableWidgetRowProps {
widget: {
id: DashboardWidgetId;
visible: boolean;
tileVisible?: boolean;
order: number;
};
labelKey: string;
index: number;
total: number;
dragHintId: string;
disabled: boolean;
labels: {
tileColumn: string;
chartColumn: string;
moveUp: string;
moveDown: string;
dragHandle: string;
widgetLabel: string;
};
onToggleTile: (id: DashboardWidgetId, value: boolean) => void;
onToggleChart: (id: DashboardWidgetId, value: boolean) => void;
onMove: (id: DashboardWidgetId, delta: -1 | 1) => void;
}
function SortableWidgetRow({
widget,
index,
total,
dragHintId,
disabled,
labels,
onToggleTile,
onToggleChart,
onMove,
}: SortableWidgetRowProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: widget.id });
const style: React.CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
};
const tileChecked =
typeof widget.tileVisible === "boolean"
? widget.tileVisible
: widget.visible;
return (
// v1.4.29 — row sized at 48 px (`min-h-12`) with 44-px mobile tap
// targets preserved on the trailing arrow buttons (`size-11`),
// shrunk to `sm:size-9` on desktop. v1.4.47 W4 — `isDragging`
// raises the row visually (elevation + accent ring) so the ghost
// overlay is unambiguous during a drag.
<div
ref={setNodeRef}
style={style}
data-slot="widget-row"
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={`${labels.dragHandle} — ${labels.widgetLabel}`}
// v1.4.47 W4 — `aria-describedby` is set after `{...attributes}`
// so our shared hint paragraph wins over dnd-kit's own announcer
// hookup. The announcer still fires on drag-start / drag-over /
// drag-end via the screenReaderInstructions slot below.
aria-describedby={dragHintId}
title={labels.dragHandle}
disabled={disabled}
data-slot="widget-drag-handle"
// v1.4.47 W10 design-H1 — extend the WCAG 2.5.5 hit target to
// 44 × 44 px via a `::before` pseudo-element while keeping the
// visible GripVertical at 28 px (matches the Switch primitive
// pattern from v1.4.43 W5-H1). v1.4.47 W10 design-M1 — drop
// dnd-kit's CSS transition under prefers-reduced-motion.
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring focus-visible:ring-offset-background -m-1 relative 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={labels.widgetLabel}>
{labels.widgetLabel}
</span>
<div className="flex w-12 justify-center">
<Switch
checked={tileChecked}
onCheckedChange={(v) => onToggleTile(widget.id, v)}
aria-label={`${labels.widgetLabel} — ${labels.tileColumn}`}
disabled={disabled}
data-slot="widget-tile-switch"
/>
</div>
<div className="flex w-12 justify-center">
<Switch
checked={widget.visible}
onCheckedChange={(v) => onToggleChart(widget.id, v)}
aria-label={`${labels.widgetLabel} — ${labels.chartColumn}`}
disabled={disabled}
data-slot="widget-chart-switch"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => onMove(widget.id, -1)}
disabled={index === 0 || disabled}
aria-label={labels.moveUp}
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => onMove(widget.id, 1)}
disabled={index === total - 1 || disabled}
aria-label={labels.moveDown}
>
<ArrowDown className="h-4 w-4" />
</Button>
</div>
);
}
@@ -73,7 +73,6 @@ interface IntegrationStatusViewModel {
lastSuccessAt: string | null;
lastAttemptAt: string | null;
lastError: string | null;
consecutiveFailures: number;
consecutiveFailuresByKind?: {
transient: number;
reauth_required: number;