mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
release: v1.32.0 — hardening and scalability (#580)
* release: prepare v1.32.0 * test: stabilize water capture re-entry
This commit is contained in:
1 parent
b01822be48
commit
62eb431d66
372 files changed
+25178
-8561
No files matched your search
@@ -24,6 +24,10 @@ vi.mock("next/dynamic", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => "/insights/body-temperature",
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-auth", () => ({
|
||||
useAuth: () => ({
|
||||
user: { timezone: "UTC", dateOfBirth: null, gender: null },
|
||||
@@ -120,6 +124,41 @@ describe("<HealthKitMetricPage> status mount", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes the manual capture type on the populated branch", () => {
|
||||
analyticsMock.mockReturnValue({
|
||||
data: { summaries: { HEART_RATE_VARIABILITY: { count: 12 } } },
|
||||
isEmpty: false,
|
||||
});
|
||||
metricStatusMock.mockReturnValue({ data: undefined, isLoading: false });
|
||||
|
||||
const html = render(
|
||||
<HealthKitMetricPage
|
||||
{...baseProps}
|
||||
emptyStateCtaType={null}
|
||||
captureType="BODY_TEMPERATURE"
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain('data-slot="metric-add-reading"');
|
||||
expect(html).toContain(
|
||||
"/measurements?add=BODY_TEMPERATURE&returnTo=%2Finsights%2Fbody-temperature",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not expose capture for a populated device-only metric", () => {
|
||||
analyticsMock.mockReturnValue({
|
||||
data: { summaries: { HEART_RATE_VARIABILITY: { count: 12 } } },
|
||||
isEmpty: false,
|
||||
});
|
||||
metricStatusMock.mockReturnValue({ data: undefined, isLoading: false });
|
||||
|
||||
const html = render(
|
||||
<HealthKitMetricPage {...baseProps} emptyStateCtaType={null} />,
|
||||
);
|
||||
|
||||
expect(html).not.toContain('data-slot="metric-add-reading"');
|
||||
});
|
||||
|
||||
it("does not mount the assessment card when statusMetric is omitted", () => {
|
||||
analyticsMock.mockReturnValue({
|
||||
data: { summaries: { HEART_RATE_VARIABILITY: { count: 12 } } },
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import { SubPageShell } from "../sub-page-shell";
|
||||
|
||||
vi.mock("next/navigation", () => ({
|
||||
usePathname: () => "/insights/weight",
|
||||
}));
|
||||
|
||||
/**
|
||||
* v1.4.25 W4 — `<SubPageShell>` unit tests.
|
||||
*
|
||||
@@ -136,6 +140,36 @@ describe("<SubPageShell>", () => {
|
||||
expect(html).not.toContain("items-center gap-0.5");
|
||||
});
|
||||
|
||||
it("links a populated metric capture action to a preselected one-shot form", () => {
|
||||
const html = render(
|
||||
<SubPageShell
|
||||
title="Weight"
|
||||
captureType="WEIGHT"
|
||||
showAllValuesType="WEIGHT"
|
||||
>
|
||||
<span />
|
||||
</SubPageShell>,
|
||||
);
|
||||
|
||||
const idx = html.indexOf('data-slot="metric-add-reading"');
|
||||
expect(idx).toBeGreaterThan(-1);
|
||||
expect(idx).toBeLessThan(html.indexOf("</header>"));
|
||||
expect(html).toContain('aria-label="Add: Weight"');
|
||||
expect(html).toContain(
|
||||
"/measurements?add=WEIGHT&returnTo=%2Finsights%2Fweight",
|
||||
);
|
||||
});
|
||||
|
||||
it("omits the populated metric capture action without a capture type", () => {
|
||||
const html = render(
|
||||
<SubPageShell title="Weight" showAllValuesType="WEIGHT">
|
||||
<span />
|
||||
</SubPageShell>,
|
||||
);
|
||||
|
||||
expect(html).not.toContain('data-slot="metric-add-reading"');
|
||||
});
|
||||
|
||||
it("omits the show-all-values control without a type", () => {
|
||||
const html = render(
|
||||
<SubPageShell title="BMI">
|
||||
|
||||
@@ -28,6 +28,14 @@ function render(node: React.ReactNode) {
|
||||
);
|
||||
}
|
||||
|
||||
function expectSingleSectionHeading(html: string, title: string) {
|
||||
const headings = Array.from(
|
||||
html.matchAll(/<h2(?:\s[^>]*)?>(.*?)<\/h2>/g),
|
||||
(match) => match[1],
|
||||
);
|
||||
expect(headings).toEqual([title]);
|
||||
}
|
||||
|
||||
const FIXTURE: WorkoutDetailPayload = {
|
||||
id: "w-1",
|
||||
sportType: "running",
|
||||
@@ -68,6 +76,7 @@ describe("<WorkoutDetailHeader>", () => {
|
||||
describe("<WorkoutDetailStats>", () => {
|
||||
it("renders one tile per available field", () => {
|
||||
const html = render(<WorkoutDetailStats workout={FIXTURE} />);
|
||||
expectSingleSectionHeading(html, "Stats");
|
||||
expect(html).toContain("Duration");
|
||||
expect(html).toContain("Distance");
|
||||
expect(html).toContain("Active energy");
|
||||
@@ -141,6 +150,7 @@ describe("<WorkoutDetailRoute>", () => {
|
||||
},
|
||||
};
|
||||
const html = render(<WorkoutDetailRoute workout={withRoute} />);
|
||||
expectSingleSectionHeading(html, "Route");
|
||||
expect(html).toContain('data-slot="workout-detail-route"');
|
||||
expect(html).toContain("<path");
|
||||
expect(html).toContain("Export GPX");
|
||||
@@ -183,6 +193,7 @@ describe("<WorkoutDetailHrSection>", () => {
|
||||
},
|
||||
};
|
||||
const html = render(<WorkoutDetailHrSection workout={withHr} />);
|
||||
expectSingleSectionHeading(html, "Heart rate");
|
||||
expect(html).toContain('data-slot="workout-detail-hr"');
|
||||
expect(html).toContain('data-slot="workout-detail-hr-provenance"');
|
||||
expect(html).toContain("From your heart-rate data");
|
||||
@@ -228,6 +239,7 @@ describe("<WorkoutDetailZones>", () => {
|
||||
},
|
||||
};
|
||||
const html = render(<WorkoutDetailZones workout={withZones} />);
|
||||
expectSingleSectionHeading(html, "Effort zones");
|
||||
expect(html).toContain('data-slot="workout-detail-zones"');
|
||||
expect(html).toContain("Effort zones");
|
||||
expect(html).toContain("Z3");
|
||||
@@ -248,6 +260,7 @@ describe("<WorkoutDetailSplits>", () => {
|
||||
],
|
||||
};
|
||||
const html = render(<WorkoutDetailSplits workout={withSplits} />);
|
||||
expectSingleSectionHeading(html, "Splits");
|
||||
expect(html).toContain('data-slot="workout-detail-splits"');
|
||||
expect(html).toContain("5:00");
|
||||
expect(html).toContain("4:48 /km");
|
||||
@@ -257,6 +270,7 @@ describe("<WorkoutDetailSplits>", () => {
|
||||
describe("<WorkoutDetailDayLinks>", () => {
|
||||
it("renders the that-day navigation links", () => {
|
||||
const html = render(<WorkoutDetailDayLinks workout={FIXTURE} />);
|
||||
expectSingleSectionHeading(html, "That day");
|
||||
expect(html).toContain('data-slot="workout-detail-day-links"');
|
||||
expect(html).toContain('href="/insights/pulse"');
|
||||
expect(html).toContain('href="/insights/sleep"');
|
||||
@@ -282,6 +296,7 @@ describe("<WorkoutInsightCard>", () => {
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expectSingleSectionHeading(html, "Activity insight");
|
||||
expect(html).toContain("A steady, aerobic-leaning ride.");
|
||||
expect(html).toContain('data-slot="workout-detail-insight"');
|
||||
});
|
||||
|
||||
@@ -68,4 +68,34 @@ describe("<WorkoutList>", () => {
|
||||
expect(html).toContain("freediving");
|
||||
expect(html).not.toContain("insights.workouts.sport.");
|
||||
});
|
||||
it("renders an accessible load-more control and its pending/error states", () => {
|
||||
const ready = render(
|
||||
<WorkoutList workouts={[ROW]} hasNextPage onLoadMore={() => {}} />,
|
||||
);
|
||||
expect(ready).toContain('data-slot="workout-list-load-more"');
|
||||
expect(ready).toContain("Load more workouts");
|
||||
|
||||
const pending = render(
|
||||
<WorkoutList
|
||||
workouts={[ROW]}
|
||||
hasNextPage
|
||||
isFetchingNextPage
|
||||
onLoadMore={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(pending).toContain('aria-busy="true"');
|
||||
expect(pending).toContain("Loading more workouts");
|
||||
|
||||
const failed = render(
|
||||
<WorkoutList
|
||||
workouts={[ROW]}
|
||||
hasNextPage
|
||||
isFetchNextPageError
|
||||
onLoadMore={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(failed).toContain('role="alert"');
|
||||
expect(failed).toContain("More workouts could not be loaded");
|
||||
expect(failed).toContain(">Retry<");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { I18nProvider } from "@/lib/i18n/context";
|
||||
import {
|
||||
ConversationRename,
|
||||
getConversationRenameKeyAction,
|
||||
} from "../conversation-rename";
|
||||
|
||||
function renderRename() {
|
||||
const client = new QueryClient();
|
||||
return renderToStaticMarkup(
|
||||
<QueryClientProvider client={client}>
|
||||
<I18nProvider initialLocale="en">
|
||||
<ConversationRename id="c1" title="Morning check-in" />
|
||||
</I18nProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("ConversationRename", () => {
|
||||
it("renders a keyboard-focusable rename affordance with a localized label", () => {
|
||||
const html = renderRename();
|
||||
|
||||
expect(html).toContain('data-slot="coach-conversation-rename"');
|
||||
expect(html).toContain('aria-label="Rename conversation"');
|
||||
expect(html).toContain('type="button"');
|
||||
});
|
||||
|
||||
it("maps Enter to save and Escape to cancel without hijacking other keys", () => {
|
||||
expect(getConversationRenameKeyAction("Enter")).toBe("save");
|
||||
expect(getConversationRenameKeyAction("Escape")).toBe("cancel");
|
||||
expect(getConversationRenameKeyAction("a")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -176,6 +176,17 @@ describe("<HistoryRail>", () => {
|
||||
expect(buttons.length).toBe(2);
|
||||
});
|
||||
|
||||
it("renders an accessible rename button for each conversation row", () => {
|
||||
const client = makeClientWithConversations(samplePage);
|
||||
const html = render(
|
||||
<HistoryRail activeId={null} onSelect={() => {}} />,
|
||||
client,
|
||||
);
|
||||
const buttons = html.match(/data-slot="coach-conversation-rename"/g) ?? [];
|
||||
expect(buttons.length).toBe(2);
|
||||
expect(html).toContain('aria-label="Rename conversation"');
|
||||
});
|
||||
|
||||
// v1.30.2 (QoL H1) — infinite history: reachability beyond the first page.
|
||||
it("renders every conversation across multiple cached pages (not just page one)", () => {
|
||||
const client = makeClientWithPages([
|
||||
|
||||
@@ -10,6 +10,14 @@ function render(node: React.ReactNode, locale: "en" | "de" = "en") {
|
||||
);
|
||||
}
|
||||
|
||||
function classesForSlot(html: string, slot: string): string[] {
|
||||
const elements =
|
||||
html.match(new RegExp(`<[^>]+data-slot="${slot}"[^>]*>`, "g")) ?? [];
|
||||
return elements.map(
|
||||
(element) => element.match(/\bclass="([^"]*)"/)?.[1] ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
describe("<SourceChips>", () => {
|
||||
it("renders nothing when provenance is null", () => {
|
||||
const html = render(<SourceChips provenance={null} />);
|
||||
@@ -56,6 +64,29 @@ describe("<SourceChips>", () => {
|
||||
expect(html).toContain("n=7");
|
||||
});
|
||||
|
||||
it("uses full semantic text color on source labels", () => {
|
||||
const html = render(
|
||||
<SourceChips
|
||||
provenance={{
|
||||
windows: ["last7days"],
|
||||
metrics: ["bp"],
|
||||
counts: { bp: 7 },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
const classNames = [
|
||||
...classesForSlot(html, "coach-source-chip"),
|
||||
...classesForSlot(html, "coach-source-window"),
|
||||
...classesForSlot(html, "coach-source-count"),
|
||||
];
|
||||
|
||||
expect(classNames).toHaveLength(3);
|
||||
for (const className of classNames) {
|
||||
expect(className.split(/\s+/)).toContain("text-info");
|
||||
expect(className).not.toMatch(/\b(?:opacity-\d+|text-\S+\/\d+)\b/);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not render n=0 chips for zero counts", () => {
|
||||
const html = render(
|
||||
<SourceChips
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type {
|
||||
CoachConversationDTO,
|
||||
CoachConversationDetailDTO,
|
||||
CoachConversationsPage,
|
||||
} from "@/lib/ai/coach/types";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
applyOptimisticCoachConversationRename,
|
||||
invalidateCoachConversationRename,
|
||||
patchCoachConversationTitle,
|
||||
restoreCoachConversationRename,
|
||||
} from "../use-coach";
|
||||
|
||||
function conversation(id: string, title: string): CoachConversationDTO {
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
createdAt: "2026-07-20T10:00:00.000Z",
|
||||
updatedAt: "2026-07-20T10:00:00.000Z",
|
||||
messageCount: 2,
|
||||
fenced: false,
|
||||
};
|
||||
}
|
||||
|
||||
function page(
|
||||
...conversations: CoachConversationDTO[]
|
||||
): CoachConversationsPage {
|
||||
return { conversations, nextCursor: null };
|
||||
}
|
||||
|
||||
describe("Coach conversation rename cache lifecycle", () => {
|
||||
let client: QueryClient;
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it("optimistically updates the head list, every history variant, and detail cache", async () => {
|
||||
const target = conversation("c1", "Before");
|
||||
const other = conversation("c2", "Other");
|
||||
client.setQueryData(queryKeys.coachConversations(), page(target, other));
|
||||
client.setQueryData(queryKeys.coachConversationHistory(""), {
|
||||
pages: [page(target), page(other)],
|
||||
pageParams: [null, "cursor-1"],
|
||||
});
|
||||
client.setQueryData(queryKeys.coachConversationHistory("before"), {
|
||||
pages: [page(target)],
|
||||
pageParams: [null],
|
||||
});
|
||||
client.setQueryData<CoachConversationDetailDTO>(
|
||||
queryKeys.coachConversation("c1"),
|
||||
{ ...target, attachmentCount: 0, messages: [] },
|
||||
);
|
||||
|
||||
await applyOptimisticCoachConversationRename(client, {
|
||||
id: "c1",
|
||||
title: "After",
|
||||
});
|
||||
|
||||
expect(
|
||||
client.getQueryData<CoachConversationsPage>(
|
||||
queryKeys.coachConversations(),
|
||||
)?.conversations[0].title,
|
||||
).toBe("After");
|
||||
for (const search of ["", "before"]) {
|
||||
const data = client.getQueryData<{
|
||||
pages: CoachConversationsPage[];
|
||||
}>(queryKeys.coachConversationHistory(search));
|
||||
expect(data?.pages[0].conversations[0].title).toBe("After");
|
||||
}
|
||||
expect(
|
||||
client.getQueryData<CoachConversationDetailDTO>(
|
||||
queryKeys.coachConversation("c1"),
|
||||
)?.title,
|
||||
).toBe("After");
|
||||
});
|
||||
|
||||
it("restores the exact cache snapshots after a failed request", async () => {
|
||||
const target = conversation("c1", "Before");
|
||||
const head = page(target);
|
||||
const history = { pages: [page(target)], pageParams: [null] };
|
||||
const detail: CoachConversationDetailDTO = {
|
||||
...target,
|
||||
attachmentCount: 0,
|
||||
messages: [],
|
||||
};
|
||||
client.setQueryData(queryKeys.coachConversations(), head);
|
||||
client.setQueryData(queryKeys.coachConversationHistory(""), history);
|
||||
client.setQueryData(queryKeys.coachConversation("c1"), detail);
|
||||
|
||||
const snapshot = await applyOptimisticCoachConversationRename(client, {
|
||||
id: "c1",
|
||||
title: "After",
|
||||
});
|
||||
restoreCoachConversationRename(client, snapshot);
|
||||
|
||||
expect(client.getQueryData(queryKeys.coachConversations())).toStrictEqual(
|
||||
head,
|
||||
);
|
||||
expect(
|
||||
client.getQueryData(queryKeys.coachConversationHistory("")),
|
||||
).toStrictEqual(history);
|
||||
expect(
|
||||
client.getQueryData(queryKeys.coachConversation("c1")),
|
||||
).toStrictEqual(detail);
|
||||
});
|
||||
|
||||
it("persists the trimmed title with PATCH and returns the server result", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: { id: "c1", title: "Persisted" },
|
||||
error: null,
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
);
|
||||
global.fetch = fetchMock;
|
||||
|
||||
await expect(
|
||||
patchCoachConversationTitle({ id: "c1", title: " Persisted " }),
|
||||
).resolves.toEqual({ id: "c1", title: "Persisted" });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"/api/insights/chat/c1",
|
||||
expect.objectContaining({
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ title: "Persisted" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("invalidates the list prefix and renamed detail on settle", async () => {
|
||||
const invalidate = vi.spyOn(client, "invalidateQueries");
|
||||
|
||||
await invalidateCoachConversationRename(client, "c1");
|
||||
|
||||
expect(invalidate).toHaveBeenCalledWith({
|
||||
queryKey: queryKeys.coachConversations(),
|
||||
});
|
||||
expect(invalidate).toHaveBeenCalledWith({
|
||||
queryKey: queryKeys.coachConversation("c1"),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -557,7 +557,7 @@ function ChatBubbleImpl({
|
||||
<div
|
||||
aria-hidden="true"
|
||||
data-slot="coach-bubble-user-avatar"
|
||||
className="text-muted-foreground bg-muted/60 mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold"
|
||||
className="text-foreground bg-muted/60 mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold"
|
||||
>
|
||||
{initials ?? <User className="size-3.5" />}
|
||||
</div>
|
||||
|
||||
@@ -1090,6 +1090,7 @@ export function CoachConversation({
|
||||
className={cn("flex min-h-0 flex-1 flex-col", className)}
|
||||
>
|
||||
{docScopeBanner}
|
||||
{!heroActive ? <h1 className="sr-only">{title}</h1> : null}
|
||||
{/* v1.21.4 (A) — the page-toolbar gear was removed; Settings now lives
|
||||
in the composer's `+` actions menu alongside New chat and
|
||||
Conversations, keeping the page chrome to the composer alone. */}
|
||||
|
||||
@@ -12,7 +12,10 @@ import {
|
||||
SheetDescription,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import type { CoachLaunchScope } from "@/lib/insights/coach-launch-context";
|
||||
import type {
|
||||
CoachCloseIntent,
|
||||
CoachLaunchScope,
|
||||
} from "@/lib/insights/coach-launch-context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { useIsMobile } from "@/hooks/use-is-mobile";
|
||||
@@ -73,7 +76,7 @@ export function coachMaximizeHref(
|
||||
*/
|
||||
export interface CoachDrawerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (next: boolean) => void;
|
||||
onOpenChange: (next: boolean, closeIntent?: CoachCloseIntent) => void;
|
||||
/** Optional pre-fill for the input box (suggested-prompt chip click). */
|
||||
prefill?: string | null;
|
||||
/**
|
||||
@@ -166,7 +169,7 @@ export function CoachDrawer({
|
||||
);
|
||||
// Close the drawer (aborts any in-flight stream via `handleOpenChange`)
|
||||
// then route to the dedicated page.
|
||||
onOpenChange(false);
|
||||
onOpenChange(false, "navigate");
|
||||
resetRef.current?.();
|
||||
router.push(href);
|
||||
}, [onOpenChange, router, documentId, workoutId]);
|
||||
@@ -177,7 +180,7 @@ export function CoachDrawer({
|
||||
// Coach page. The former `?view=conversations` in-page slide-in drawer is
|
||||
// gone; selecting a row there routes back to `/coach?c=<id>`.
|
||||
const handleOpenConversations = useCallback(() => {
|
||||
onOpenChange(false);
|
||||
onOpenChange(false, "navigate");
|
||||
resetRef.current?.();
|
||||
router.push("/coach/conversations");
|
||||
}, [onOpenChange, router]);
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import type { FormEvent, KeyboardEvent } from "react";
|
||||
import { Check, Loader2, Pencil, X } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { COACH_CONVERSATION_TITLE_MAX } from "@/lib/ai/coach/types";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { useRenameCoachConversation } from "./use-coach";
|
||||
|
||||
export type ConversationRenameKeyAction = "save" | "cancel";
|
||||
|
||||
export function getConversationRenameKeyAction(
|
||||
key: string,
|
||||
): ConversationRenameKeyAction | null {
|
||||
if (key === "Enter") return "save";
|
||||
if (key === "Escape") return "cancel";
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface ConversationRenameProps {
|
||||
id: string;
|
||||
title: string;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function ConversationRename({
|
||||
id,
|
||||
title,
|
||||
compact = false,
|
||||
}: ConversationRenameProps) {
|
||||
const { t } = useTranslations();
|
||||
const rename = useRenameCoachConversation();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(title);
|
||||
const submittingRef = useRef(false);
|
||||
|
||||
function cancel() {
|
||||
if (rename.isPending) return;
|
||||
setDraft(title);
|
||||
setEditing(false);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
const nextTitle = draft.trim();
|
||||
if (
|
||||
submittingRef.current ||
|
||||
rename.isPending ||
|
||||
nextTitle.length === 0 ||
|
||||
nextTitle.length > COACH_CONVERSATION_TITLE_MAX
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (nextTitle === title) {
|
||||
setDraft(title);
|
||||
setEditing(false);
|
||||
return;
|
||||
}
|
||||
|
||||
submittingRef.current = true;
|
||||
try {
|
||||
await rename.mutateAsync({ id, title: nextTitle });
|
||||
setEditing(false);
|
||||
} catch {
|
||||
// The shared mutation restores every cache and surfaces the localized
|
||||
// failure. Keep the user's draft in the input so retrying loses nothing.
|
||||
} finally {
|
||||
submittingRef.current = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
void save();
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
|
||||
const action = getConversationRenameKeyAction(event.key);
|
||||
if (!action) return;
|
||||
event.preventDefault();
|
||||
if (action === "cancel") cancel();
|
||||
else void save();
|
||||
}
|
||||
|
||||
if (!editing) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size={compact ? "icon" : "icon-lg"}
|
||||
onClick={() => {
|
||||
setDraft(title);
|
||||
setEditing(true);
|
||||
}}
|
||||
aria-label={t("insights.coach.rename.action")}
|
||||
data-slot="coach-conversation-rename"
|
||||
className={cn("shrink-0", compact && "size-11")}
|
||||
>
|
||||
<Pencil className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
const invalid =
|
||||
draft.trim().length === 0 ||
|
||||
draft.trim().length > COACH_CONVERSATION_TITLE_MAX;
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
data-slot="coach-conversation-rename-form"
|
||||
className={cn(
|
||||
"bg-background absolute inset-y-1 left-1 z-10 flex min-w-0 items-center gap-1",
|
||||
compact ? "right-14" : "right-16",
|
||||
)}
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={rename.isPending}
|
||||
maxLength={COACH_CONVERSATION_TITLE_MAX}
|
||||
aria-label={t("insights.coach.rename.input")}
|
||||
data-slot="coach-conversation-rename-input"
|
||||
className="h-10 min-w-0 flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={rename.isPending || invalid}
|
||||
aria-label={t("insights.coach.rename.save")}
|
||||
data-slot="coach-conversation-rename-save"
|
||||
className="size-10 shrink-0"
|
||||
>
|
||||
{rename.isPending ? (
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Check className="size-4" aria-hidden="true" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={cancel}
|
||||
disabled={rename.isPending}
|
||||
aria-label={t("insights.coach.rename.cancel")}
|
||||
data-slot="coach-conversation-rename-cancel"
|
||||
className="size-10 shrink-0"
|
||||
>
|
||||
<X className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { useLoadMoreSentinel } from "@/hooks/use-load-more-sentinel";
|
||||
|
||||
import { COACH_SCROLLBAR } from "./message-thread";
|
||||
import { ConversationRename } from "./conversation-rename";
|
||||
import {
|
||||
useCoachConversationHistory,
|
||||
useDeleteCoachConversationWithUndo,
|
||||
@@ -208,7 +209,7 @@ export function HistoryRail({
|
||||
data-slot="coach-history-item"
|
||||
data-active={isActive ? "true" : undefined}
|
||||
className={cn(
|
||||
"group flex items-center gap-1.5 rounded-lg px-2.5 py-2",
|
||||
"group relative flex items-center gap-1.5 rounded-lg px-2.5 py-2",
|
||||
"text-sm transition-colors",
|
||||
isActive
|
||||
? "bg-primary/15 text-foreground"
|
||||
@@ -245,6 +246,7 @@ export function HistoryRail({
|
||||
{formatRelativeTime(c.updatedAt, t, locale)}
|
||||
</span>
|
||||
</button>
|
||||
<ConversationRename id={c.id} title={c.title} compact />
|
||||
{/* v1.4.27 R3d MB2 — drop the hover-only `opacity-0`
|
||||
reveal: touch surfaces have no hover, so the delete
|
||||
affordance was invisible on mobile. The button
|
||||
|
||||
@@ -86,7 +86,7 @@ export function SourceChips({ provenance, className }: SourceChipsProps) {
|
||||
data-slot="coach-source-chip"
|
||||
data-metric={chip.metric}
|
||||
className={cn(
|
||||
"border-info/25 text-info/90",
|
||||
"border-info/25 text-info",
|
||||
"inline-flex items-center gap-1 rounded-full border bg-transparent",
|
||||
"px-2 py-0.5 text-xs leading-none",
|
||||
)}
|
||||
@@ -94,10 +94,14 @@ export function SourceChips({ provenance, className }: SourceChipsProps) {
|
||||
<Link2 className="h-2.5 w-2.5" aria-hidden="true" />
|
||||
<span className="font-medium">{chip.metricLabel}</span>
|
||||
{chip.windowLabel && (
|
||||
<span className="opacity-75">· {chip.windowLabel}</span>
|
||||
<span data-slot="coach-source-window" className="text-info">
|
||||
· {chip.windowLabel}
|
||||
</span>
|
||||
)}
|
||||
{typeof chip.count === "number" && chip.count > 0 && (
|
||||
<span className="opacity-60">· n={chip.count}</span>
|
||||
<span data-slot="coach-source-count" className="text-info">
|
||||
· n={chip.count}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import type { QueryClient, QueryKey } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import type {
|
||||
CoachConversationAttachmentDTO,
|
||||
@@ -20,7 +22,14 @@ import type {
|
||||
CoachUsage,
|
||||
} from "@/lib/ai/coach/types";
|
||||
import type { CoachSuggestedAction } from "@/lib/ai/coach/suggest-action";
|
||||
import { apiDelete, apiFetchRaw, apiGet, apiPost } from "@/lib/api/api-fetch";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import {
|
||||
apiDelete,
|
||||
apiFetchRaw,
|
||||
apiGet,
|
||||
apiPatch,
|
||||
apiPost,
|
||||
} from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
|
||||
/**
|
||||
@@ -45,6 +54,107 @@ const QUERY_KEYS = {
|
||||
one: (id: string) => queryKeys.coachConversation(id),
|
||||
};
|
||||
|
||||
export interface RenameCoachConversationInput {
|
||||
id: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export type CoachConversationRenameSnapshot = Array<
|
||||
readonly [QueryKey, unknown]
|
||||
>;
|
||||
|
||||
function renameConversationInCache(
|
||||
data: unknown,
|
||||
input: RenameCoachConversationInput,
|
||||
): unknown {
|
||||
if (!data || typeof data !== "object") return data;
|
||||
|
||||
if ("pages" in data && Array.isArray(data.pages)) {
|
||||
let changed = false;
|
||||
const pages = data.pages.map((page) => {
|
||||
const renamed = renameConversationInCache(page, input);
|
||||
changed ||= renamed !== page;
|
||||
return renamed;
|
||||
});
|
||||
return changed ? { ...data, pages } : data;
|
||||
}
|
||||
|
||||
if ("conversations" in data && Array.isArray(data.conversations)) {
|
||||
let changed = false;
|
||||
const conversations = data.conversations.map((conversation) => {
|
||||
if (
|
||||
conversation &&
|
||||
typeof conversation === "object" &&
|
||||
"id" in conversation &&
|
||||
conversation.id === input.id
|
||||
) {
|
||||
changed = true;
|
||||
return { ...conversation, title: input.title };
|
||||
}
|
||||
return conversation;
|
||||
});
|
||||
return changed ? { ...data, conversations } : data;
|
||||
}
|
||||
|
||||
if ("id" in data && data.id === input.id && "title" in data) {
|
||||
return { ...data, title: input.title };
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Capture and update every currently materialised conversation cache. Search
|
||||
* variants live below the list prefix, while the open thread has its own key.
|
||||
*/
|
||||
export async function applyOptimisticCoachConversationRename(
|
||||
queryClient: QueryClient,
|
||||
input: RenameCoachConversationInput,
|
||||
): Promise<CoachConversationRenameSnapshot> {
|
||||
const detailKey = queryKeys.coachConversation(input.id);
|
||||
await Promise.all([
|
||||
queryClient.cancelQueries({ queryKey: QUERY_KEYS.list() }),
|
||||
queryClient.cancelQueries({ queryKey: detailKey }),
|
||||
]);
|
||||
|
||||
const snapshot: CoachConversationRenameSnapshot = [
|
||||
...queryClient.getQueriesData({ queryKey: QUERY_KEYS.list() }),
|
||||
...queryClient.getQueriesData({ queryKey: detailKey, exact: true }),
|
||||
];
|
||||
for (const [key, previous] of snapshot) {
|
||||
queryClient.setQueryData(key, renameConversationInCache(previous, input));
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
export function restoreCoachConversationRename(
|
||||
queryClient: QueryClient,
|
||||
snapshot: CoachConversationRenameSnapshot,
|
||||
): void {
|
||||
for (const [key, previous] of snapshot) {
|
||||
queryClient.setQueryData(key, previous);
|
||||
}
|
||||
}
|
||||
|
||||
export async function invalidateCoachConversationRename(
|
||||
queryClient: QueryClient,
|
||||
id: string,
|
||||
): Promise<void> {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.list() }),
|
||||
queryClient.invalidateQueries({ queryKey: QUERY_KEYS.one(id) }),
|
||||
]);
|
||||
}
|
||||
|
||||
export async function patchCoachConversationTitle(
|
||||
input: RenameCoachConversationInput,
|
||||
): Promise<RenameCoachConversationInput> {
|
||||
const title = input.title.trim();
|
||||
return apiPatch<RenameCoachConversationInput>(
|
||||
`/api/insights/chat/${encodeURIComponent(input.id)}`,
|
||||
{ title },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The single (first) page of conversations. Used ONLY for the
|
||||
* auto-open-most-recent-thread behaviour on mount
|
||||
@@ -287,6 +397,32 @@ export function useDeleteCoachConversationWithUndo() {
|
||||
return { pendingDeleteIds, requestDelete, undoDelete };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared rename mutation for every Coach history surface. It snapshots each
|
||||
* materialised list/search/detail cache before the optimistic write and
|
||||
* restores those exact data references if persistence fails.
|
||||
*/
|
||||
export function useRenameCoachConversation() {
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslations();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: patchCoachConversationTitle,
|
||||
onMutate: (input: RenameCoachConversationInput) =>
|
||||
applyOptimisticCoachConversationRename(queryClient, {
|
||||
...input,
|
||||
title: input.title.trim(),
|
||||
}),
|
||||
onError: (_error, _input, snapshot) => {
|
||||
if (snapshot) restoreCoachConversationRename(queryClient, snapshot);
|
||||
toast.error(t("insights.coach.rename.error"));
|
||||
},
|
||||
onSettled: (_data, _error, input) => {
|
||||
void invalidateCoachConversationRename(queryClient, input.id);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.29.x (S7) — attach a stored document to an EXISTING fenced (or about-to-be-
|
||||
* fenced) conversation. On success invalidates the conversation detail + rail so
|
||||
|
||||
@@ -34,11 +34,10 @@ import { SubPageShell } from "@/components/insights/sub-page-shell";
|
||||
* envelope:
|
||||
*
|
||||
* 1. `<SubPageShell>` with a localised title + description.
|
||||
* 2. Empty-state CTA when the user has no observations for the
|
||||
* 2. Optional empty-state CTA when the user has no observations for the
|
||||
* metric — points at `/measurements?add=<TYPE>` so the existing
|
||||
* quick-entry dialog can light up. The CTA target is optional;
|
||||
* Apple-Health-only metrics (active energy, body temperature)
|
||||
* pass `null` to render an onboarding hint without a dead link.
|
||||
* quick-entry dialog can light up. Device-led empty states may omit it
|
||||
* even when the populated page offers manual contextual capture.
|
||||
* 3. `<HealthChartDynamic>` mounted on the canonical
|
||||
* `ChartOverlayKey` so the chart-cog popover persists per metric.
|
||||
* 4. A header-height Coach launch icon (`coachLaunch` on the shell) —
|
||||
@@ -96,11 +95,16 @@ export interface HealthKitMetricPageProps {
|
||||
/** Optional value bands (Apple-Health-style target zone shading). */
|
||||
valueBands?: ComponentProps<typeof HealthChartDynamic>["valueBands"];
|
||||
/**
|
||||
* Optional empty-state CTA target. `null` renders the empty state
|
||||
* without a primary action (Apple-Health-only metrics that have no
|
||||
* manual entry form). String values land in `/measurements?add=<x>`.
|
||||
* Optional empty-state CTA target. `null` renders the empty state without a
|
||||
* primary action. String values land in `/measurements?add=<x>`.
|
||||
*/
|
||||
emptyStateCtaType?: string | null;
|
||||
/**
|
||||
* Manual capture type for the populated-page header action. When omitted,
|
||||
* the empty-state CTA type is reused; pass it explicitly when a metric is
|
||||
* manually supported but its empty state deliberately remains device-led.
|
||||
*/
|
||||
captureType?: string | null;
|
||||
/** Icon node mounted in the empty-state card. */
|
||||
emptyStateIcon: ReactNode;
|
||||
/**
|
||||
@@ -197,6 +201,7 @@ export function HealthKitMetricPage({
|
||||
yAxisUnit,
|
||||
valueBands,
|
||||
emptyStateCtaType,
|
||||
captureType,
|
||||
emptyStateIcon,
|
||||
coachPrefill,
|
||||
valueScale,
|
||||
@@ -372,6 +377,10 @@ export function HealthKitMetricPage({
|
||||
/>
|
||||
}
|
||||
coachLaunch
|
||||
captureType={
|
||||
(captureType === undefined ? emptyStateCtaType : captureType) ??
|
||||
undefined
|
||||
}
|
||||
showAllValuesType={effectiveType}
|
||||
>
|
||||
<HealthChartDynamic
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { useMounted } from "@/hooks/use-mounted";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { prefersReducedMotion } from "@/lib/charts/reduced-motion";
|
||||
@@ -648,6 +649,7 @@ function InsightsTabStripImpl({
|
||||
}: InsightsTabStripProps) {
|
||||
const { t } = useTranslations();
|
||||
const pathname = usePathname();
|
||||
const mounted = useMounted();
|
||||
// v1.4.31 — memoise the pill list so the strip's main render
|
||||
// path doesn't rebuild the array on every parent re-render. The
|
||||
// strip is wrapped in `React.memo` (see export below); the memo
|
||||
@@ -765,6 +767,7 @@ function InsightsTabStripImpl({
|
||||
<nav
|
||||
data-slot="insights-tab-strip"
|
||||
data-tour-id="insights-hero"
|
||||
data-hydrated={mounted ? "true" : undefined}
|
||||
aria-label={t("insights.navAriaLabel")}
|
||||
// v1.4.28 FB-D3 — `touch-action: pan-y` lets vertical swipes that
|
||||
// begin on the sticky strip scroll the page through it. The
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -15,11 +15,9 @@ import { queryKeys, refetchInactiveDailyReads } from "@/lib/query-keys";
|
||||
/**
|
||||
* v1.29 — manual water quick-add sheet, opened from the hydration card.
|
||||
*
|
||||
* Chips (+200/+300/+500 mL) fire immediately (mode "add") and keep the
|
||||
* sheet open so a run of taps composes one round number; the sheet stays
|
||||
* a lightweight stepper, not a form the user has to re-open per tap. The
|
||||
* custom-amount field and the "edit today's total" disclosure both close
|
||||
* on submit — the two are one-shot actions.
|
||||
* Chips (+200/+300/+500 mL) and custom amounts are one-shot writes:
|
||||
* the sheet closes and clears only after the API confirms success. A
|
||||
* rejected write leaves the sheet and input untouched so the user can retry.
|
||||
*
|
||||
* Every write hits `POST /api/nutrients/water`, which owns ONLY the
|
||||
* `source="MANUAL"` row (migration 0249) — never the Apple-synced row.
|
||||
@@ -30,20 +28,27 @@ const QUICK_CHIPS_ML = [200, 300, 500] as const;
|
||||
interface WaterQuickAddSheetProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Today's combined (all-source) total, for the "edit total" pre-fill. */
|
||||
todayTotalMl: number;
|
||||
/** Called after a confirmed write; bypasses dirty-dismiss guards. */
|
||||
onSuccess?: () => void;
|
||||
/** Today's combined total. Omit outside the hydration detail surface. */
|
||||
todayTotalMl?: number;
|
||||
}
|
||||
|
||||
export function WaterQuickAddSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSuccess,
|
||||
todayTotalMl,
|
||||
}: WaterQuickAddSheetProps) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [customAmount, setCustomAmount] = useState("");
|
||||
const [editMode, setEditMode] = useState(false);
|
||||
const [editAmount, setEditAmount] = useState(() => String(todayTotalMl));
|
||||
const [editAmount, setEditAmount] = useState(() =>
|
||||
todayTotalMl == null ? "" : String(todayTotalMl),
|
||||
);
|
||||
const writePendingRef = useRef(false);
|
||||
const closeAfterSuccess = onSuccess ?? (() => onOpenChange(false));
|
||||
|
||||
// v1.29.x — the Today digest joins the invalidation. The write route
|
||||
// already hard-evicts the server snapshot bucket
|
||||
@@ -54,7 +59,7 @@ export function WaterQuickAddSheet({
|
||||
// `refetchInactiveDailyReads` forces the inactive refetch, mirroring the
|
||||
// measurement / mood / medication fix.
|
||||
const invalidate = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["nutrients"] });
|
||||
void queryClient.invalidateQueries({ queryKey: queryKeys.nutrientsRoot() });
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.dashboardSnapshot(),
|
||||
});
|
||||
@@ -75,23 +80,52 @@ export function WaterQuickAddSheet({
|
||||
onSuccess: () => {
|
||||
invalidate();
|
||||
setEditMode(false);
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: () => toast.error(t("nutrients.hydration.quickAddError")),
|
||||
});
|
||||
|
||||
const handleCustomAdd = () => {
|
||||
const amount = Number(customAmount);
|
||||
if (!Number.isFinite(amount) || amount <= 0) return;
|
||||
addMutation.mutate(amount);
|
||||
setCustomAmount("");
|
||||
onOpenChange(false);
|
||||
const addWater = async (amount: number) => {
|
||||
if (writePendingRef.current) return;
|
||||
writePendingRef.current = true;
|
||||
try {
|
||||
await addMutation.mutateAsync(amount);
|
||||
toast.success(
|
||||
t("nutrients.hydration.quickAddSuccess", { amount: String(amount) }),
|
||||
);
|
||||
setCustomAmount("");
|
||||
closeAfterSuccess();
|
||||
} catch {
|
||||
// The mutation owns the translated error toast. Preserve all input.
|
||||
} finally {
|
||||
writePendingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditSave = () => {
|
||||
const handleCustomAdd = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const amount = Number(customAmount);
|
||||
if (!Number.isFinite(amount) || amount <= 0) return;
|
||||
void addWater(amount);
|
||||
};
|
||||
|
||||
const handleEditSave = async (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const amount = Number(editAmount);
|
||||
if (!Number.isFinite(amount) || amount < 0) return;
|
||||
setMutation.mutate(amount);
|
||||
if (writePendingRef.current || !Number.isFinite(amount) || amount < 0) {
|
||||
return;
|
||||
}
|
||||
writePendingRef.current = true;
|
||||
try {
|
||||
await setMutation.mutateAsync(amount);
|
||||
toast.success(
|
||||
t("nutrients.hydration.quickAddSuccess", { amount: String(amount) }),
|
||||
);
|
||||
closeAfterSuccess();
|
||||
} catch {
|
||||
// The mutation owns the translated error toast. Preserve all input.
|
||||
} finally {
|
||||
writePendingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -107,24 +141,23 @@ export function WaterQuickAddSheet({
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={addMutation.isPending}
|
||||
onClick={() => {
|
||||
addMutation.mutate(amountMl);
|
||||
toast.success(`+${amountMl} mL`);
|
||||
}}
|
||||
className="min-h-11 sm:min-h-8"
|
||||
disabled={addMutation.isPending || setMutation.isPending}
|
||||
onClick={() => void addWater(amountMl)}
|
||||
>
|
||||
+{amountMl} mL
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<form className="flex items-end gap-2" onSubmit={handleCustomAdd}>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label htmlFor="water-custom-amount">
|
||||
{t("nutrients.hydration.quickAddCustomLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
id="water-custom-amount"
|
||||
name="amountMl"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
@@ -135,22 +168,28 @@ export function WaterQuickAddSheet({
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCustomAdd}
|
||||
disabled={addMutation.isPending || !customAmount}
|
||||
type="submit"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
disabled={
|
||||
addMutation.isPending || setMutation.isPending || !customAmount
|
||||
}
|
||||
>
|
||||
{t("nutrients.hydration.quickAddSubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{editMode ? (
|
||||
<div className="border-border/70 space-y-1.5 border-t pt-4">
|
||||
{todayTotalMl != null && editMode ? (
|
||||
<form
|
||||
className="border-border/70 space-y-1.5 border-t pt-4"
|
||||
onSubmit={handleEditSave}
|
||||
>
|
||||
<Label htmlFor="water-edit-total">
|
||||
{t("nutrients.hydration.editTotal")}
|
||||
</Label>
|
||||
<div className="flex items-end gap-2">
|
||||
<Input
|
||||
id="water-edit-total"
|
||||
name="totalMl"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
@@ -160,20 +199,20 @@ export function WaterQuickAddSheet({
|
||||
onChange={(e) => setEditAmount(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleEditSave}
|
||||
disabled={setMutation.isPending}
|
||||
type="submit"
|
||||
className="min-h-11 sm:min-h-9"
|
||||
disabled={addMutation.isPending || setMutation.isPending}
|
||||
>
|
||||
{t("nutrients.hydration.quickAddSubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
</form>
|
||||
) : todayTotalMl != null ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground self-start"
|
||||
className="text-muted-foreground min-h-11 self-start sm:min-h-8"
|
||||
onClick={() => {
|
||||
setEditAmount(String(todayTotalMl));
|
||||
setEditMode(true);
|
||||
@@ -181,7 +220,7 @@ export function WaterQuickAddSheet({
|
||||
>
|
||||
{t("nutrients.hydration.editTotal")}
|
||||
</Button>
|
||||
)}
|
||||
) : null}
|
||||
</ResponsiveSheet>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useRef, type ReactNode } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { ListOrdered } from "lucide-react";
|
||||
import { ListOrdered, Plus } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -13,8 +13,13 @@ import { metricScopeFromExplainer } from "@/components/insights/coach-metric-sco
|
||||
import { useCoachLaunch } from "@/lib/insights/coach-launch-context";
|
||||
import { useScrollResetOnRoute } from "@/hooks/use-scroll-reset-on-route";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import { SUB_PAGE_SLUGS } from "@/lib/insights/sub-page-metric";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const INSIGHT_METRIC_RETURN_PATHS: Readonly<Record<string, true>> =
|
||||
Object.fromEntries(
|
||||
SUB_PAGE_SLUGS.map((slug) => [`/insights/${slug}`, true] as const),
|
||||
);
|
||||
/**
|
||||
* v1.4.25 W4 — common visual frame for each metric sub-page.
|
||||
*
|
||||
@@ -126,6 +131,11 @@ export interface SubPageShellProps {
|
||||
* second header affordance: the FAB stays the single entry point.
|
||||
*/
|
||||
coachLaunch?: boolean;
|
||||
/**
|
||||
* Canonical measurement-form type for the populated page's contextual
|
||||
* capture action. Omit it for device-only or derived metrics.
|
||||
*/
|
||||
captureType?: string;
|
||||
/**
|
||||
* v1.8.5 W4b — a "show all readings" entry linking to the dedicated
|
||||
* `/insights/values/<type>` subpage. Sub-pages pass the metric's
|
||||
@@ -153,6 +163,7 @@ export function SubPageShell({
|
||||
// stands) but now gates whether the page registers its metric as the
|
||||
// Coach launch context's ambient scope, so the FAB opens contextual.
|
||||
coachLaunch = false,
|
||||
captureType,
|
||||
showAllValuesType,
|
||||
children,
|
||||
}: SubPageShellProps) {
|
||||
@@ -163,6 +174,15 @@ export function SubPageShell({
|
||||
// where the user drilled in from (e.g. `weight → show all values → back to
|
||||
// weight`) rather than always returning to the Insights overview.
|
||||
const pathname = usePathname();
|
||||
const captureReturnTo =
|
||||
pathname && INSIGHT_METRIC_RETURN_PATHS[pathname] ? pathname : null;
|
||||
const captureHref =
|
||||
captureType && captureReturnTo
|
||||
? `/measurements?add=${encodeURIComponent(
|
||||
captureType,
|
||||
)}&returnTo=${encodeURIComponent(captureReturnTo)}`
|
||||
: null;
|
||||
const captureLabel = `${t("measurements.addMeasurement")}: ${title}`;
|
||||
// a11y: focus the heading on mount so a tab-strip navigation actually
|
||||
// moves screen-reader focus into the sub-page body. v1.4.27 MB7 /
|
||||
// CF-35 made the focus call opt-in via `focusOnMount` — the
|
||||
@@ -283,6 +303,26 @@ export function SubPageShell({
|
||||
with a tighter gap the later sibling's invisible halo sat
|
||||
on top of its neighbour's clickable edge. */}
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
{captureHref ? (
|
||||
<Button
|
||||
asChild
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-slot="metric-add-reading"
|
||||
className={cn(
|
||||
"text-muted-foreground hover:text-foreground relative size-10",
|
||||
"before:absolute before:-inset-1.5 before:content-['']",
|
||||
)}
|
||||
>
|
||||
<Link
|
||||
href={captureHref}
|
||||
aria-label={captureLabel}
|
||||
title={captureLabel}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
</Link>
|
||||
</Button>
|
||||
) : null}
|
||||
{/* v1.16.8 — "show all readings" rides the header cluster
|
||||
as an icon button, LEFT of the target-adjust gear (it
|
||||
used to be a full-width outline button at the page foot).
|
||||
|
||||
@@ -53,6 +53,7 @@ export function WorkoutDetailDayLinks({ workout }: WorkoutDetailDayLinksProps) {
|
||||
<TileHeader
|
||||
icon={CalendarDays}
|
||||
title={t("insights.workouts.detail.thatDayTitle")}
|
||||
titleAs="h2"
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -53,6 +53,7 @@ export function WorkoutDetailHrSection({
|
||||
<TileHeader
|
||||
icon={HeartPulse}
|
||||
title={t("insights.workouts.detail.hrChartTitle")}
|
||||
titleAs="h2"
|
||||
/>
|
||||
{series.source === "pulse_window" ? (
|
||||
<p
|
||||
|
||||
@@ -44,6 +44,7 @@ export function WorkoutInsightCard({
|
||||
<TileHeader
|
||||
icon={Sparkles}
|
||||
title={t("insights.workouts.detail.insightTitle")}
|
||||
titleAs="h2"
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -102,6 +102,7 @@ export function WorkoutDetailRoute({ workout }: WorkoutDetailRouteProps) {
|
||||
<TileHeader
|
||||
icon={MapIcon}
|
||||
title={t("insights.workouts.detail.routeTitle")}
|
||||
titleAs="h2"
|
||||
right={
|
||||
<Button
|
||||
type="button"
|
||||
|
||||
@@ -38,6 +38,7 @@ export function WorkoutDetailSplits({ workout }: WorkoutDetailSplitsProps) {
|
||||
<TileHeader
|
||||
icon={Flag}
|
||||
title={t("insights.workouts.detail.splitsTitle")}
|
||||
titleAs="h2"
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
Timer,
|
||||
} from "lucide-react";
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "@/lib/i18n/context";
|
||||
import type { WorkoutDetailPayload } from "@/hooks/use-workouts";
|
||||
@@ -157,9 +157,12 @@ export function WorkoutDetailStats({ workout }: WorkoutDetailStatsProps) {
|
||||
return (
|
||||
<Card data-slot="workout-detail-stats">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">
|
||||
<h2
|
||||
data-slot="card-title"
|
||||
className="text-base leading-none font-semibold"
|
||||
>
|
||||
{t("insights.workouts.detail.statsTitle")}
|
||||
</CardTitle>
|
||||
</h2>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div
|
||||
|
||||
@@ -46,6 +46,7 @@ export function WorkoutDetailZones({ workout }: WorkoutDetailZonesProps) {
|
||||
<TileHeader
|
||||
icon={Gauge}
|
||||
title={t("insights.workouts.detail.zonesTitle")}
|
||||
titleAs="h2"
|
||||
/>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{zones.model === "whoop"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { Map as MapIcon, HeartPulse } from "lucide-react";
|
||||
import { HeartPulse, Loader2, Map as MapIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getNumberFormat, getDateTimeFormat } from "@/lib/intl/formatter-cache";
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "@/lib/format-locale";
|
||||
import { iconForSport } from "@/lib/workouts/sport-icons";
|
||||
import type { WorkoutListEntry } from "@/hooks/use-workouts";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/**
|
||||
* v1.4.32 — workout list row primitive.
|
||||
@@ -69,9 +70,20 @@ function formatDate(
|
||||
export interface WorkoutListProps {
|
||||
workouts: WorkoutListEntry[];
|
||||
className?: string;
|
||||
hasNextPage?: boolean;
|
||||
isFetchingNextPage?: boolean;
|
||||
isFetchNextPageError?: boolean;
|
||||
onLoadMore?: () => void;
|
||||
}
|
||||
|
||||
export function WorkoutList({ workouts, className }: WorkoutListProps) {
|
||||
export function WorkoutList({
|
||||
workouts,
|
||||
className,
|
||||
hasNextPage = false,
|
||||
isFetchingNextPage = false,
|
||||
isFetchNextPageError = false,
|
||||
onLoadMore,
|
||||
}: WorkoutListProps) {
|
||||
const { t, locale } = useTranslations();
|
||||
const timeFormat = useTimeFormatPreference();
|
||||
|
||||
@@ -152,6 +164,47 @@ export function WorkoutList({ workouts, className }: WorkoutListProps) {
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
{hasNextPage ? (
|
||||
<li
|
||||
data-slot="workout-list-load-more"
|
||||
className="flex flex-col items-center gap-2 p-3"
|
||||
>
|
||||
{isFetchNextPageError ? (
|
||||
<p
|
||||
id="workout-list-load-more-error"
|
||||
role="alert"
|
||||
className="text-destructive text-center text-sm"
|
||||
>
|
||||
{t("insights.workouts.loadMoreError")}
|
||||
</p>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 min-w-44"
|
||||
disabled={isFetchingNextPage}
|
||||
aria-busy={isFetchingNextPage || undefined}
|
||||
aria-describedby={
|
||||
isFetchNextPageError ? "workout-list-load-more-error" : undefined
|
||||
}
|
||||
onClick={onLoadMore}
|
||||
>
|
||||
{isFetchingNextPage ? (
|
||||
<>
|
||||
<Loader2
|
||||
className="size-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{t("insights.workouts.loadingMore")}
|
||||
</>
|
||||
) : isFetchNextPageError ? (
|
||||
t("common.retry")
|
||||
) : (
|
||||
t("insights.workouts.loadMore")
|
||||
)}
|
||||
</Button>
|
||||
</li>
|
||||
) : null}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user