fix(url): write page state into the query string through one serialised helper

Next 16.4 adopts a native history write a render later. A second write
inside that gap was undone when the router adopted the first, and a
write computed from useSearchParams started from the URL before the
last one. Clearing the vault's filters could therefore leave
?encounter= behind: the debounced search wrote the filters it had
rendered back over the clear.

@/lib/url-state is now the one way a page writes its own query: each
write starts from the live address bar, at most one waits for the
router at a time, and later updates queue on top of it and go together
once the router has it (or after a short grace). useUrlSearch reads the
same live value and reports each adoption. The filter hook (documents,
measurements, mood), the open document, the day layer, the timeline's
zoom and range, the medication tabs, the AI provider choice, the
Coach's ?c= and the one-shot parameter strips all go through it; the
filter changes merge into the live filters. A guard refuses raw
history writes and router writes built from the rendered params
outside the helper.

The timeline spec now waits for the values menu to hand focus back
before scrolling to the last row; it measured mid-animation and the
focus return scrolled the page back.
This commit is contained in:
Marc-André Bombeck committed 2026-10-23 02:04:21 +02:00
1 parent 333dfe8746
commit d8e4cf6000
27 files changed
+846 -276

No files matched your search

@@ -1,7 +1,7 @@
{
"$comment": "Production files over 800 lines and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 123,
"total": 145465,
"total": 145428,
"entries": {
"app/api/dashboard/summary/route.ts": 1032,
"app/api/documents/inbound/route.ts": 811,
@@ -18,7 +18,7 @@
"components/charts/mood-chart.tsx": 1166,
"components/cycle/log-day-sheet.tsx": 1639,
"components/documents/document-detail-sheet.tsx": 1304,
"components/documents/documents-view.tsx": 1244,
"components/documents/documents-view.tsx": 1223,
"components/insights/coach-panel/chat-bubble.tsx": 888,
"components/insights/coach-panel/coach-conversation.tsx": 1286,
"components/insights/coach-panel/use-coach.ts": 1486,
@@ -29,7 +29,7 @@
"components/measurement-reminders/vorsorge-section.tsx": 1536,
"components/measurements/measurement-form.tsx": 815,
"components/measurements/measurement-list.tsx": 2019,
"components/medications/detail/medication-detail-tabs.tsx": 1176,
"components/medications/detail/medication-detail-tabs.tsx": 1160,
"components/medications/dose-history-ledger.tsx": 1052,
"components/medications/medication-table.tsx": 853,
"components/medications/wizard/wizard-payload.ts": 1414,
@@ -1,7 +1,7 @@
{
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 411,
"total": 148137,
"total": 148109,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 314,
@@ -74,7 +74,7 @@
"app/insights/medications/page.tsx :: InsightsMedikamentePage": 265,
"app/insights/page-client.tsx :: InsightsPageClient": 376,
"app/labs/page.tsx :: LabsPage": 228,
"app/medications/page-client.tsx :: MedicationsPageClient": 591,
"app/medications/page-client.tsx :: MedicationsPageClient": 590,
"app/notifications/page.tsx :: NotificationsPage": 327,
"app/page-client.tsx :: DashboardPageClient": 2131,
"app/page-client.tsx :: DashboardPageClient > (anonymous)": 1279,
@@ -118,7 +118,7 @@
"components/daily/today-hero.tsx :: TodayHero": 488,
"components/dashboard/dashboard-header.tsx :: DashboardHeader": 215,
"components/dashboard/medication-intake-quick-add.tsx :: MedicationIntakeQuickAdd": 384,
"components/day/day-layer.tsx :: DayLayer": 360,
"components/day/day-layer.tsx :: DayLayer": 358,
"components/day/day-view.tsx :: DayView": 309,
"components/documents/document-ai-section.tsx :: DocumentAiSection": 262,
"components/documents/document-bulk-bar.tsx :: DocumentBulkBar": 204,
@@ -135,7 +135,7 @@
"components/illness/new-episode-sheet.tsx :: NewEpisodeSheet": 264,
"components/insights/coach-panel/attachment-picker.tsx :: AttachmentPicker": 208,
"components/insights/coach-panel/chat-bubble.tsx :: ChatBubbleImpl": 419,
"components/insights/coach-panel/coach-conversation.tsx :: CoachConversation": 1012,
"components/insights/coach-panel/coach-conversation.tsx :: CoachConversation": 1011,
"components/insights/coach-panel/coach-input.tsx :: CoachInput": 259,
"components/insights/coach-panel/coach-model-picker.tsx :: CoachModelPicker": 212,
"components/insights/coach-panel/conversations-panel.tsx :: ConversationsPanel": 317,
@@ -186,7 +186,7 @@
"components/measurements/measurement-list.tsx :: MeasurementList > data.measurements.map(arg)": 223,
"components/measurements/measurement-list.tsx :: MeasurementList > data.measurements.map(arg) #2": 229,
"components/medications/detail/efficacy/efficacy-chart.tsx :: EfficacyChart": 361,
"components/medications/detail/medication-detail-tabs.tsx :: MedicationDetailTabs": 787,
"components/medications/detail/medication-detail-tabs.tsx :: MedicationDetailTabs": 771,
"components/medications/dose-history-add-dialog.tsx :: LedgerAddDialog": 223,
"components/medications/dose-history-ledger.tsx :: DoseHistoryLedger": 404,
"components/medications/dose-history-ledger.tsx :: LedgerRowItem": 314,
@@ -233,7 +233,7 @@
"components/settings/access/managed-profile-edit-form.tsx :: ManagedProfileEditFields": 208,
"components/settings/access/managed-profile-guardians.tsx :: ManagedProfileGuardians": 234,
"components/settings/account-section/index.tsx :: AccountSection": 659,
"components/settings/ai/codex-provider-form.tsx :: CodexProviderForm": 281,
"components/settings/ai/codex-provider-form.tsx :: CodexProviderForm": 280,
"components/settings/ai/fallback-chain-card.tsx :: FallbackChainCard": 228,
"components/settings/ai/runtime-actions-row.tsx :: RuntimeActionsRow": 282,
"components/settings/api-section.tsx :: ApiTokensCard": 366,
@@ -248,7 +248,7 @@
"components/settings/import-panel/json-import-card.tsx :: JsonImportCard": 223,
"components/settings/import-panel/record-csv-import-card.tsx :: RecordCsvImportSheet": 460,
"components/settings/insights-pill-order-section.tsx :: InsightsPillOrderSection": 255,
"components/settings/integrations/connections-panel.tsx :: ConnectionsPanel": 236,
"components/settings/integrations/connections-panel.tsx :: ConnectionsPanel": 230,
"components/settings/integrations/document-sources-card.tsx :: SourceForm": 306,
"components/settings/integrations/google-health-card.tsx :: GoogleHealthCard": 300,
"components/settings/integrations/integration-card.tsx :: IntegrationCard": 209,
@@ -276,7 +276,7 @@
"components/timeline/series-point-tips.tsx :: SeriesPointTips": 212,
"components/timeline/timeline-chart.tsx :: ChartBody": 243,
"components/timeline/timeline-chronicle.tsx :: TimelineChronicle": 274,
"components/timeline/timeline-view.tsx :: TimelineView": 502,
"components/timeline/timeline-view.tsx :: TimelineView": 501,
"components/ui/responsive-sheet.tsx :: ResponsiveSheet": 239,
"components/vaccinations/catalog-picker.tsx :: CatalogPicker": 221,
"components/vaccinations/custom-vaccine-sheet.tsx :: CustomVaccineSheet": 246,
@@ -0,0 +1,92 @@
/**
* A stand-in browser for code that writes through `@/lib/url-state`: a
* location, a session history that records every write, and the event
* plumbing the helper dispatches on. The router "adopts" each write on the
* next microtask, as Next does a render later, so a test that awaits between
* writes sees them land one after another.
*/
import { vi } from "vitest";
import { reportRouterSearch, resetUrlStateForTests } from "@/lib/url-state";
export interface UrlStateBrowser {
/** `pushState` hrefs, in order. */
push: ReturnType<typeof vi.fn>;
/** `replaceState` hrefs, in order. */
replace: ReturnType<typeof vi.fn>;
current: () => string;
uninstall: () => void;
}
export function installUrlStateBrowser(
initialUrl: string,
{ autoAdopt = true }: { autoAdopt?: boolean } = {},
): UrlStateBrowser {
resetUrlStateForTests();
const push = vi.fn();
const replace = vi.fn();
let url = initialUrl;
let state: unknown = null;
const parsed = () => new URL(url, "http://localhost");
const location = {
get pathname() {
return parsed().pathname;
},
get search() {
return parsed().search;
},
get hash() {
return parsed().hash;
},
get href() {
return parsed().href;
},
};
const adopt = () => {
if (autoAdopt) queueMicrotask(() => reportRouterSearch(location.search));
};
const history = {
get state() {
return state;
},
pushState(next: unknown, _unused: string, href: string) {
url = href;
state = next;
push(href);
adopt();
},
replaceState(next: unknown, _unused: string, href: string) {
url = href;
state = next;
replace(href);
adopt();
},
back() {},
};
const g = globalThis as unknown as Record<string, unknown>;
const previous = g.window;
g.window = {
location,
history,
addEventListener() {},
removeEventListener() {},
dispatchEvent() {
return true;
},
requestAnimationFrame(callback: (time: number) => void) {
callback(0);
return 0;
},
cancelAnimationFrame() {},
};
return {
push,
replace,
current: () => url,
uninstall: () => {
resetUrlStateForTests();
if (previous === undefined) delete g.window;
else g.window = previous;
},
};
}
@@ -0,0 +1,73 @@
/**
* Every write of page state into the query string goes through
* `@/lib/url-state`, which derives it from the live address and holds it
* until the router has the previous one.
*
* Next 16.4 adopts a native history write a render later, and a write
* computed from `useSearchParams` starts from the URL before the last write.
* Each surface that wrote on its own met one of the two: a quick second
* step of the day undone, a closed document sheet left open, cleared vault
* filters coming back as `?encounter=`. A raw `history.pushState` /
* `replaceState`, or a router write built from the rendered search params,
* reopens the class, so both are refused outside the helper and the few
* places listed here with their reason.
*/
import { describe, expect, it } from "vitest";
import { readSourceFolder } from "@/__tests__/helpers/source-files";
const RAW_HISTORY_WRITE = /\bhistory\s*\.\s*(?:pushState|replaceState)\s*\(/;
const RENDERED_SEARCH = /\bsearchParams\??\.toString\(\)/;
const ROUTER_WRITE = /\brouter\s*\.\s*(?:push|replace)\s*\(/;
const ALLOWED: Record<string, string> = {
"lib/url-state.ts": "the helper itself",
"components/clinician/share-unlock-gate.tsx":
"scrubs a passphrase from the fragment synchronously, before the unlock request leaves; no query state",
"components/documents/documents-view.tsx":
"closeDocumentSelectionHistoryEntry takes a history-shaped argument for its tests; the page passes `urlStateHistory`",
};
describe("query-string writes go through @/lib/url-state", () => {
const files = readSourceFolder("src", {
floor: 500,
include: (rel) =>
!rel.startsWith("generated/") &&
!rel.includes("__tests__/") &&
!/\.test\.tsx?$/.test(rel),
});
it("reads the whole tree (floor)", () => {
expect(files.length).toBeGreaterThan(1000);
});
it("finds no raw history write outside the helper", () => {
const offenders = files
.filter(([rel, text]) => !ALLOWED[rel] && RAW_HISTORY_WRITE.test(text))
.map(([rel]) => rel);
expect(offenders).toEqual([]);
});
it("finds no router write built from the rendered search params", () => {
const offenders = files
.filter(
([rel, text]) =>
!ALLOWED[rel] &&
RENDERED_SEARCH.test(text) &&
ROUTER_WRITE.test(text),
)
.map(([rel]) => rel);
expect(offenders).toEqual([]);
});
it("still sees the helper's own writes (the matcher is alive)", () => {
const helper = files.find(([rel]) => rel === "lib/url-state.ts");
expect(helper && RAW_HISTORY_WRITE.test(helper[1])).toBe(true);
for (const rel of Object.keys(ALLOWED)) {
expect(
files.some(([path]) => path === rel),
`${rel} is still in the tree`,
).toBe(true);
}
});
});