basalt-ui 2.12.0 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/MIGRATING.md +50 -12
  3. package/agent/rules/basalt-state.md +1 -1
  4. package/agent/skills/basalt-app/SKILL.md +1 -1
  5. package/agent/templates/main.tpl +1 -0
  6. package/dist/cli/basalt-install.d.ts +10 -0
  7. package/dist/cli/basalt-install.d.ts.map +1 -0
  8. package/dist/cli/basalt-install.js +0 -0
  9. package/dist/cli/check-theme.js +1 -1
  10. package/dist/cli/doctor-upgrade.d.ts +3 -3
  11. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  12. package/dist/cli/doctor-upgrade.js +28 -44
  13. package/dist/cli/doctor.js +3 -3
  14. package/dist/cli/index.d.ts +4 -28
  15. package/dist/cli/index.d.ts.map +1 -1
  16. package/dist/cli/index.js +10 -49
  17. package/dist/cli/provider-tags.d.ts +12 -0
  18. package/dist/cli/provider-tags.d.ts.map +1 -0
  19. package/dist/cli/provider-tags.js +28 -0
  20. package/dist/cli/render-imports.d.ts +24 -0
  21. package/dist/cli/render-imports.d.ts.map +1 -0
  22. package/dist/cli/render-imports.js +74 -0
  23. package/dist/cli/router-wiring.d.ts +12 -0
  24. package/dist/cli/router-wiring.d.ts.map +1 -1
  25. package/dist/cli/router-wiring.js +18 -0
  26. package/dist/cli/source-text.d.ts +7 -0
  27. package/dist/cli/source-text.d.ts.map +1 -1
  28. package/dist/cli/source-text.js +34 -0
  29. package/dist/cli/sync.d.ts.map +1 -1
  30. package/dist/cli/sync.js +18 -13
  31. package/dist/guard/fonts-hint.d.ts +3 -0
  32. package/dist/guard/fonts-hint.d.ts.map +1 -0
  33. package/dist/guard/fonts-hint.js +4 -0
  34. package/dist/guard/index.d.ts +1 -1
  35. package/dist/guard/index.d.ts.map +1 -1
  36. package/dist/guard/index.js +2 -1
  37. package/dist/index.d.ts +3 -3
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +3 -1
  40. package/dist/provider/create-router.d.ts +57 -10
  41. package/dist/provider/create-router.d.ts.map +1 -1
  42. package/dist/provider/create-router.js +28 -17
  43. package/dist/provider/index.d.ts +2 -2
  44. package/dist/provider/index.d.ts.map +1 -1
  45. package/dist/provider/index.js +23 -7
  46. package/dist/query-client.d.ts +2 -62
  47. package/dist/query-client.d.ts.map +1 -1
  48. package/dist/query-client.js +13 -18
  49. package/dist/router-tanstack/nav.d.ts +5 -0
  50. package/dist/router-tanstack/nav.d.ts.map +1 -1
  51. package/dist/router-tanstack/search-store-warnings.d.ts +33 -0
  52. package/dist/router-tanstack/search-store-warnings.d.ts.map +1 -0
  53. package/dist/router-tanstack/search-store-warnings.js +77 -0
  54. package/dist/router-tanstack/search-store.d.ts +2 -5
  55. package/dist/router-tanstack/search-store.d.ts.map +1 -1
  56. package/dist/router-tanstack/search-store.js +111 -110
  57. package/dist/router-tanstack/use-nav.d.ts +4 -2
  58. package/dist/router-tanstack/use-nav.d.ts.map +1 -1
  59. package/dist/router-tanstack/use-nav.js +55 -18
  60. package/dist/shell/app-breadcrumbs.d.ts +1 -3
  61. package/dist/shell/app-breadcrumbs.d.ts.map +1 -1
  62. package/dist/shell/app-breadcrumbs.js +1 -6
  63. package/dist/shell/index.d.ts +14 -5
  64. package/dist/shell/index.d.ts.map +1 -1
  65. package/dist/shell/index.js +6 -29
  66. package/dist/shell/nav-types.d.ts +7 -0
  67. package/dist/shell/nav-types.d.ts.map +1 -1
  68. package/dist/shell/page-aside.d.ts +4 -2
  69. package/dist/shell/page-aside.d.ts.map +1 -1
  70. package/dist/shell/page-aside.js +41 -23
  71. package/dist/shell/page-bar.d.ts +1 -1
  72. package/dist/shell/page-bar.d.ts.map +1 -1
  73. package/dist/shell/page-bar.js +39 -33
  74. package/dist/telemetry.d.ts +31 -2
  75. package/dist/telemetry.d.ts.map +1 -1
  76. package/dist/telemetry.js +32 -12
  77. package/dist/theme/ctl-theme.d.ts.map +1 -1
  78. package/dist/theme/ctl-theme.js +17 -30
  79. package/dist/theme/extend.d.ts +18 -0
  80. package/dist/theme/extend.d.ts.map +1 -0
  81. package/dist/theme/extend.js +6 -0
  82. package/dist/theme/index.d.ts.map +1 -1
  83. package/dist/theme/index.js +44 -84
  84. package/dist/unwrap.d.ts +29 -0
  85. package/dist/unwrap.d.ts.map +1 -0
  86. package/dist/unwrap.js +18 -0
  87. package/llms.txt +9 -5
  88. package/package.json +1 -1
  89. package/src/cli/basalt-install.ts +9 -0
  90. package/src/cli/check-theme.ts +1 -1
  91. package/src/cli/doctor-upgrade.ts +40 -61
  92. package/src/cli/doctor.ts +3 -3
  93. package/src/cli/index.ts +14 -71
  94. package/src/cli/provider-tags.ts +38 -0
  95. package/src/cli/render-imports.ts +104 -0
  96. package/src/cli/router-wiring.ts +23 -0
  97. package/src/cli/source-text.ts +39 -0
  98. package/src/cli/sync.ts +27 -21
  99. package/src/guard/fonts-hint.ts +2 -0
  100. package/src/guard/index.ts +2 -2
  101. package/src/index.ts +4 -2
  102. package/src/provider/create-router.tsx +103 -39
  103. package/src/provider/index.tsx +27 -9
  104. package/src/query-client.ts +20 -78
  105. package/src/router-tanstack/nav.ts +5 -0
  106. package/src/router-tanstack/search-store-warnings.ts +120 -0
  107. package/src/router-tanstack/search-store.ts +200 -206
  108. package/src/router-tanstack/use-nav.ts +116 -76
  109. package/src/shell/app-breadcrumbs.tsx +1 -12
  110. package/src/shell/index.tsx +22 -55
  111. package/src/shell/nav-types.ts +8 -0
  112. package/src/shell/page-aside.tsx +59 -26
  113. package/src/shell/page-bar.tsx +63 -59
  114. package/src/telemetry.ts +71 -13
  115. package/src/theme/__snapshots__/plain-theme.test.ts.snap +2354 -0
  116. package/src/theme/ctl-theme.tsx +20 -19
  117. package/src/theme/extend.ts +18 -0
  118. package/src/theme/index.ts +50 -49
  119. package/src/unwrap.ts +44 -0
@@ -29,8 +29,11 @@
29
29
  *
30
30
  * Headless — no Mantine, no JSX. Same tier as `useBasaltNav` and `useRouterBreadcrumbs`.
31
31
  */
32
- import { useNavigate, useSearch } from '@tanstack/react-router'
32
+ import { useEffect, useRef } from 'react'
33
+ import { useNavigate, useRouter, useRouterState, useSearch } from '@tanstack/react-router'
34
+ import type { AnyRouter } from '@tanstack/react-router'
33
35
  import { createStoreCore } from '../state/fields'
36
+ import { createStoreWarnings } from './search-store-warnings'
34
37
  import type {
35
38
  AnyField,
36
39
  FieldHandle,
@@ -100,104 +103,61 @@ export type SearchStore<S extends Record<string, AnyField>> = {
100
103
  useReset: () => () => void
101
104
  }
102
105
 
106
+ // ── Implementation ─────────────────────────────────────────────────────────
107
+
103
108
  /**
104
- * Dev-only, once per store: the URL is pinning `fallback` while something else is persisted, and
105
- * neither reader has ever been called. That combination has exactly one realistic cause — a nav
106
- * link declaring the param as a literal — and it is invisible otherwise, because every individual
107
- * piece looks correct and the feature merely never remembers anything.
108
- *
109
- * Deliberately NOT a timer over "was this store ever read": that fires in every test that builds a
110
- * store, and it cannot say what to do about it. This fires only in the broken state, and names the
111
- * fix.
109
+ * The router's SSR bootstrap (`window.$_TSR`) is present on a dehydrated page. Until the first
110
+ * reader has committed, the client must resolve exactly what the server did; after that the stored
111
+ * layer applies like on any client-only page. One page hydrates once, so this is module state.
112
112
  */
113
- function warnLinkPinsFallback(input: {
114
- key: string
115
- param: string
116
- urlValue: string
117
- storedValue: string
118
- }): void {
119
- const { key, param, urlValue, storedValue } = input
120
- // oxlint-disable-next-line no-console -- a dev-time wiring warning has no other channel
121
- console.warn(
122
- `[basalt-ui] createSearchStore('${key}'): the URL pinned \`${param}=${urlValue}\` ` +
123
- '(the fallback) ' +
124
- `while '${storedValue}' was persisted, and nothing has read this store back. A nav link is ` +
125
- `almost certainly declaring \`search: { ${param}: '${urlValue}' }\` at module scope, which ` +
126
- "overrides the stored value on every click — pass the store's own reader instead: " +
127
- '`search: <store>.linkSearch`. (dev only)',
128
- )
129
- }
130
-
131
- // ── Implementation ─────────────────────────────────────────────────────────
113
+ let hydrationDone = false
132
114
 
133
- /** Reads the merged search of every matched route, so a child or sibling needs no `from` (A3). */
134
- function useCurrentSearch(): Record<string, unknown> {
135
- const search = useSearch({ strict: false }) as unknown
136
- return typeof search === 'object' && search !== null ? (search as Record<string, unknown>) : {}
115
+ /** @internal Tests only — a fresh page for the next hydration. */
116
+ export function resetHydrationForTests(): void {
117
+ hydrationDone = false
137
118
  }
138
119
 
139
- function describeValue(value: unknown): string {
140
- return typeof value === 'string' ? value : JSON.stringify(value)
120
+ const isDehydrating = (): boolean =>
121
+ typeof window !== 'undefined' && '$_TSR' in window && !hydrationDone
122
+
123
+ /** A failed store navigate is reported, never swallowed and never an unhandled rejection. */
124
+ function reportFailure(error: unknown): void {
125
+ if (typeof reportError === 'function') reportError(error)
126
+ else
127
+ queueMicrotask(() => {
128
+ throw error
129
+ })
141
130
  }
142
131
 
143
- /**
144
- * Dev-only, once per field: a `persist: false` field was written from a route that does not
145
- * validate it, so the write had nowhere to go — no URL (the route owns no such param) and no mirror
146
- * (the field opted out of one). Silence is the wrong answer here: every other lane combination does
147
- * something, so a control that appears to work and changes nothing reads as a basalt bug.
148
- */
149
- function warnWriteHasNowhereToGo(input: { key: string; name: string; param: string }): void {
150
- const { key, name, param } = input
151
- // oxlint-disable-next-line no-console -- a dev-time wiring warning has no other channel
152
- console.warn(
153
- `[basalt-ui] createSearchStore('${key}'): wrote field '${name}' from a route that does not ` +
154
- `validate \`${param}\`, and the field is \`persist: false\` — so the write was dropped. ` +
155
- 'Either render this control on the route wired to `validateSearch`, or give the field the ' +
156
- 'localStorage lane (drop `persist: false`) so a write from elsewhere survives until the ' +
157
- 'owning route reads it. (dev only)',
158
- )
132
+ type SearchNavigate = (options: {
133
+ to: '.'
134
+ search: (prev: Record<string, unknown>) => Record<string, unknown>
135
+ replace: boolean
136
+ resetScroll: false
137
+ }) => Promise<unknown> | void
138
+
139
+ /** One shared write: always replaces scroll-neutrally and reports a rejected navigate. */
140
+ function navigateSearch(
141
+ navigate: SearchNavigate,
142
+ search: (prev: Record<string, unknown>) => Record<string, unknown>,
143
+ replace: boolean,
144
+ ): void {
145
+ // A filter lives halfway down a page as often as it lives in the bar, and the router's
146
+ // default scroll restoration treats this same-route search write as a navigation — so
147
+ // without this a select two screens down jumps the reader back to the top on every
148
+ // change. Never a prop: there is no filter write that WANTS the page to scroll.
149
+ const result = navigate({ to: '.', search, replace, resetScroll: false })
150
+ if (result !== undefined) result.catch(reportFailure)
159
151
  }
160
152
 
161
- /**
162
- * Dev-only, once per param: a `patch` named a search param ANOTHER field of the same store owns.
163
- * The navigate would put it in the URL while the store's own write path never touched the mirror,
164
- * so the next paramless visit and every `linkSearch` link resolve the OLD value — the URL and the
165
- * mirror disagree from that click on, and nothing looks broken until a reader shares a link.
166
- *
167
- * Thrown in dev rather than warned: the call is a mistake with a one-line fix (write the other
168
- * field through its own setter), and the damage is silent. Production keeps the write — a thrown
169
- * error there would take a page down over a stale param — and logs it once.
170
- */
171
- function patchOwnsFieldMessage(input: {
172
- key: string
173
- name: string
174
- owner: string
175
- param: string
176
- }): string {
177
- const { key, name, owner, param } = input
178
- return (
179
- `basalt-ui: createSearchStore('${key}'): set('${name}', …, { patch }) carries \`${param}\`, ` +
180
- `which this store's field '${owner}' owns — the URL would take it while the localStorage ` +
181
- 'mirror kept the old value, so the next paramless visit and every `linkSearch` link disagree ' +
182
- `with the page the write happened on. Write it through \`field.${owner}.use()[1]\` instead; ` +
183
- 'a `patch` is for keys the store does NOT own.'
184
- )
153
+ function isRecord(value: unknown): value is Record<string, unknown> {
154
+ return typeof value === 'object' && value !== null
185
155
  }
186
156
 
187
- /**
188
- * Dev-only, once per field: a patched write from a route that does not validate the field. The
189
- * write persists (A1), but the patch has no navigate to merge into and is dropped — the one case
190
- * where half of a two-part write silently disappears.
191
- */
192
- function warnPatchDropped(input: { key: string; name: string; param: string }): void {
193
- const { key, name, param } = input
194
- // oxlint-disable-next-line no-console -- a dev-time wiring warning has no other channel
195
- console.warn(
196
- `[basalt-ui] createSearchStore('${key}'): wrote field '${name}' with a \`patch\` from a route ` +
197
- `that does not validate \`${param}\` — the field's value persisted (A1), but the patch was ` +
198
- 'DROPPED: there is no navigate to merge it into. Render the control on the route wired to ' +
199
- '`validateSearch`, or apply that sibling param on the route that owns it. (dev only)',
200
- )
157
+ /** Reads the merged search of every matched route, so a child or sibling needs no `from` (A3). */
158
+ function useCurrentSearch(): Record<string, unknown> {
159
+ const search: unknown = useSearch({ strict: false })
160
+ return isRecord(search) ? search : {}
201
161
  }
202
162
 
203
163
  /**
@@ -248,10 +208,28 @@ function isMemoryLane(entry: StoreEntry): boolean {
248
208
  }
249
209
 
250
210
  /**
251
- * The store's implementation. Not exported from the barrel — `createSearchStore` is the public
252
- * door.
211
+ * One store per page (or per feature), over typed fields. `key` is the localStorage key; each
212
+ * field's map key is its default URL param name.
213
+ *
214
+ * @example
215
+ * export const analytics = createSearchStore({
216
+ * key: 'analytics',
217
+ * fields: {
218
+ * range: field.range({ presets: ['7d', '30d', '90d'], fallback: '30d', custom: true }),
219
+ * compare: field.enum(['none', 'previous'], 'none'),
220
+ * channels: field.multi(CHANNELS, []),
221
+ * },
222
+ * }).labels({ range: { '7d': 'Last 7 days', '30d': 'Last 30 days', '90d': 'Last 90 days' } })
223
+ *
224
+ * export const Route = createFileRoute('/analytics')({
225
+ * validateSearch: analytics.validateSearch,
226
+ * loaderDeps: ({ search }) => search,
227
+ * })
228
+ *
229
+ * // in the page: <RangeFilter field={analytics.field.range} />
230
+ * // in the nav: linkOptions({ to: '/analytics', search: analytics.linkSearch })
253
231
  */
254
- export function buildSearchStore<const S extends Record<string, AnyField>>(
232
+ export function createSearchStore<const S extends Record<string, AnyField>>(
255
233
  o: CreateSearchStoreOptions<S>,
256
234
  ): SearchStore<S> {
257
235
  assertNoLazyUrlFallback(o.key, o.fields)
@@ -263,13 +241,10 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
263
241
  // touches the other two uses exclusively. Missing it there made the pinned-link warning fire on
264
242
  // correctly wired pages.
265
243
  let readerWired = false
266
- let warned = false
267
244
  const markReaderWired = (): void => {
268
245
  readerWired = true
269
246
  }
270
- const nowhereWarned = new Set<string>()
271
- const patchDroppedWarned = new Set<string>()
272
- const patchOwnerLogged = new Set<string>()
247
+ const warnings = createStoreWarnings(o.key)
273
248
 
274
249
  /** Every URL param this store owns, mapped to the field that owns it — what a `patch` may not name. */
275
250
  const paramOwners = new Map<string, string>()
@@ -300,24 +275,21 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
300
275
  )
301
276
 
302
277
  /**
303
- * The URL lane's `clear()` needs a `navigate`, which only exists inside a render. Each render of
304
- * `urlUse` therefore leaves the navigate its mount would use here, keyed by field — so `clear()`
305
- * from an event handler on that mount navigates exactly as its setter would, and a field no mount
306
- * has read falls back to clearing the mirror alone.
278
+ * The URL lane's `clear()` runs from an event handler, where no hook is in reach. A mounted
279
+ * `urlUse` lends its router here from an EFFECT — never the render body, which a discarded or
280
+ * StrictMode render would leave behind — so `clear()` navigates through the live router and
281
+ * judges ownership against the location it is called at. With no mount reading the store it
282
+ * clears the mirror alone. With several routers mounted it fans out over all of them, each
283
+ * judged against its own location.
307
284
  */
308
- const urlClear = new Map<string, () => void>()
285
+ const mounts = new Map<AnyRouter, number>()
309
286
 
310
287
  const assertPatchNotOwned = (entry: StoreEntry, patch: Record<string, unknown>): void => {
311
288
  for (const param of Object.keys(patch)) {
312
289
  const owner = paramOwners.get(param)
313
290
  // The field's OWN params are harmless: its `toSearch` is spread after the patch and wins.
314
291
  if (owner === undefined || entry.codec.params.includes(param)) continue
315
- const message = patchOwnsFieldMessage({ key: o.key, name: entry.name, owner, param })
316
- if (process.env['NODE_ENV'] !== 'production') throw new Error(message)
317
- if (patchOwnerLogged.has(param)) continue
318
- patchOwnerLogged.add(param)
319
- // oxlint-disable-next-line no-console -- production keeps the write; the log is the record
320
- console.error(message)
292
+ warnings.patchOwned({ name: entry.name, owner, param })
321
293
  }
322
294
  }
323
295
 
@@ -333,7 +305,7 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
333
305
  }
334
306
 
335
307
  const maybeWarn = (raw: Record<string, unknown>, record: Record<string, unknown>): void => {
336
- if (warned || readerWired || process.env['NODE_ENV'] === 'production') return
308
+ if (process.env['NODE_ENV'] === 'production' || readerWired) return
337
309
  for (const entry of core.urlEntries) {
338
310
  const fromUrl = entry.codec.fromSearch(raw)
339
311
  if (fromUrl === null || !entry.codec.equals(fromUrl, entry.codec.fallback)) continue
@@ -341,26 +313,42 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
341
313
  if (stored === null || entry.codec.equals(stored, fromUrl)) continue
342
314
  // Describe both sides as the URL spells them (a range prints `30d`, not its whole value
343
315
  // object) — the message quotes a `search:` literal, so it has to be URL-shaped to be advice.
344
- warned = true
345
- warnLinkPinsFallback({
346
- key: o.key,
316
+ warnings.linkPinsFallback({
347
317
  param: entry.codec.primary,
348
- urlValue: describeValue(entry.codec.toSearch(fromUrl)[entry.codec.primary]),
349
- storedValue: describeValue(entry.codec.toSearch(stored)[entry.codec.primary]),
318
+ urlValue: entry.codec.toSearch(fromUrl)[entry.codec.primary],
319
+ storedValue: entry.codec.toSearch(stored)[entry.codec.primary],
350
320
  })
351
321
  return
352
322
  }
353
323
  }
354
324
 
325
+ /**
326
+ * Pure on the server and while a dehydrated page hydrates (see `isDehydrating`): the stored layer
327
+ * would make the client's first search differ from the HTML the server rendered, and a loader
328
+ * keyed on `search` would run with different deps. Everywhere else — a client-only app, or a
329
+ * dehydrated page once hydration committed — a paramless visit resolves URL ⊳ mirror ⊳ fallback.
330
+ */
331
+ const stored = (): Record<string, unknown> =>
332
+ typeof window === 'undefined' || isDehydrating() ? {} : core.readRecord()
333
+
355
334
  const validateSearch = (raw: Record<string, unknown>): SearchValues<S> => {
356
- const record = core.readRecord()
335
+ const record = stored()
357
336
  maybeWarn(raw, record)
358
337
  return flatten(raw, record) as SearchValues<S>
359
338
  }
360
339
 
340
+ const runsStore = (route: AnyRouter['routesById'][string] | undefined): boolean => {
341
+ const validate: unknown = route?.options.validateSearch
342
+ return (
343
+ typeof validate === 'function' &&
344
+ (validate === validateSearch ||
345
+ Function.prototype.toString.call(validate).includes('validateSearch'))
346
+ )
347
+ }
348
+
361
349
  const linkSearch = (): SearchValues<S> => {
362
350
  readerWired = true
363
- return flatten(null, core.readRecord()) as SearchValues<S>
351
+ return flatten(null, stored()) as SearchValues<S>
364
352
  }
365
353
 
366
354
  const readStored = (): Partial<StoredValues<S>> => {
@@ -371,26 +359,65 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
371
359
  const urlUse = (entry: StoreEntry) => (): readonly [unknown, FieldWrite] => {
372
360
  const search = useCurrentSearch()
373
361
  const navigate = useNavigate()
362
+ const router = useRouter()
363
+ const pathname = useRouterState({ select: (state) => state.location.pathname })
374
364
  const [record, setRecord] = core.usePersistedRecord()
375
365
  markReaderWired()
376
366
  const value = core.resolve(entry, search, record)
367
+ // Captured at render: true for every reader of the hydrating commit, false for a later mount.
368
+ const hydrating = useRef(isDehydrating())
377
369
  // The matched route validates this field iff its primary param is present (see the module
378
370
  // header). A foreign route gets the persist-only lane.
379
371
  const validated = Object.hasOwn(search, entry.codec.primary)
380
- urlClear.set(entry.name, () => {
381
- if (!validated) return
382
- navigate({
383
- to: '.',
384
- // Gated like the setter: clearing a field already at its fallback keeps the page.
385
- search: (prev: Record<string, unknown>) => ({
386
- ...prev,
387
- ...resetsFor(entry, prev, entry.codec.fallback),
388
- ...entry.codec.toSearch(entry.codec.fallback),
389
- }),
390
- replace: true,
391
- resetScroll: false,
392
- })
393
- })
372
+
373
+ useEffect(() => {
374
+ const count = mounts.get(router) ?? 0
375
+ mounts.set(router, count + 1)
376
+ return () => {
377
+ const left = (mounts.get(router) ?? 1) - 1
378
+ if (left > 0) mounts.set(router, left)
379
+ else mounts.delete(router)
380
+ }
381
+ }, [router])
382
+
383
+ // Hydration committed: the server's HTML was reproduced, so the stored layer may apply now.
384
+ useEffect(() => {
385
+ if (hydrating.current) hydrationDone = true
386
+ }, [])
387
+
388
+ // The record is the server snapshot until React re-renders with the client's, so this runs
389
+ // again once the mirror is readable. A URL still carrying the fallback was not chosen (the
390
+ // server pinned it), so it adopts the mirror — by REPLACING, so a loader keyed on `search`
391
+ // follows what the page shows. A deep link naming any other value is never overridden.
392
+ const mirrored = entry.codec.lane.persist ? entry.codec.decode(record[entry.name]) : null
393
+ const mirroredKey = mirrored === null ? null : JSON.stringify(entry.codec.toSearch(mirrored))
394
+ useEffect(() => {
395
+ if (!hydrating.current || mirrored === null) return
396
+ hydrating.current = false
397
+ if (!validated || entry.codec.equals(mirrored, entry.codec.fallback)) return
398
+ const urlValue = entry.codec.fromSearch(search)
399
+ if (urlValue !== null && !entry.codec.equals(urlValue, entry.codec.fallback)) return
400
+ navigateSearch(
401
+ (o) => router.navigate(o),
402
+ (prev) => ({ ...prev, ...entry.codec.toSearch(mirrored) }),
403
+ true,
404
+ )
405
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- one-shot per mirror value: the rest is read at that moment
406
+ }, [mirroredKey])
407
+
408
+ // Dev only. Reading the route options never calls a user validator: a route runs this store
409
+ // when its `validateSearch` IS the store's, or composes it (its source names `validateSearch`).
410
+ useEffect(() => {
411
+ if (process.env['NODE_ENV'] === 'production') return
412
+ // Everything from the committed MATCHES, so the verdict never mixes two locations.
413
+ const { matches } = router.state
414
+ const leaf = matches.at(-1)
415
+ if (leaf === undefined || !isRecord(leaf.search)) return
416
+ if (!Object.hasOwn(leaf.search, entry.codec.primary)) return
417
+ if (matches.some((match) => runsStore(router.routesById[match.routeId]))) return
418
+ warnings.foreignParam({ name: entry.name, param: entry.codec.primary, path: leaf.pathname })
419
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- re-judged per location; the router handle is stable
420
+ }, [pathname])
394
421
 
395
422
  return [
396
423
  value,
@@ -398,45 +425,29 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
398
425
  const patch = opts?.patch
399
426
  if (patch !== undefined && Object.keys(patch).length > 0) {
400
427
  assertPatchNotOwned(entry, patch)
401
- if (
402
- !validated &&
403
- !patchDroppedWarned.has(entry.name) &&
404
- process.env['NODE_ENV'] !== 'production'
405
- ) {
406
- patchDroppedWarned.add(entry.name)
407
- warnPatchDropped({ key: o.key, name: entry.name, param: entry.codec.primary })
408
- }
409
- }
410
- if (validated) {
411
- navigate({
412
- to: '.',
413
- // `patch` FIRST, the field's own params last: a patch is for keys the store does not
414
- // own (clearing a sibling `detailDate` with `undefined`), so it must never be able to
415
- // overwrite the value this very call is setting.
416
- // `resets` only when the value moves: a no-op write (a debounced box settling back on
417
- // what it held) must not throw the reader off the page they are on.
418
- search: (prev: Record<string, unknown>) => ({
419
- ...prev,
420
- ...resetsFor(entry, prev, next),
421
- ...opts?.patch,
422
- ...entry.codec.toSearch(next),
423
- }),
424
- replace: entry.codec.lane.history === 'replace',
425
- // A filter lives halfway down a page as often as it lives in the bar, and the router's
426
- // default scroll restoration treats this same-route search write as a navigation — so
427
- // without this a select two screens down jumps the reader back to the top on every
428
- // change. Never a prop: there is no filter write that WANTS the page to scroll.
429
- resetScroll: false,
430
- })
428
+ if (!validated) warnings.patchWasDropped({ name: entry.name, param: entry.codec.primary })
431
429
  }
432
- if (entry.codec.lane.persist) {
433
- core.writeField(setRecord, entry.name, next)
430
+ if (!validated) {
431
+ if (entry.codec.lane.persist) core.writeField(setRecord, entry.name, next)
432
+ else warnings.writeHasNowhereToGo({ name: entry.name, param: entry.codec.primary })
434
433
  return
435
434
  }
436
- if (validated || nowhereWarned.has(entry.name)) return
437
- if (process.env['NODE_ENV'] === 'production') return
438
- nowhereWarned.add(entry.name)
439
- warnWriteHasNowhereToGo({ key: o.key, name: entry.name, param: entry.codec.primary })
435
+ // `patch` FIRST, the field's own params last: a patch is for keys the store does not own
436
+ // (clearing a sibling `detailDate` with `undefined`), so it must never be able to overwrite
437
+ // the value this very call is setting.
438
+ // `resets` only when the value moves: a no-op write (a debounced box settling back on what
439
+ // it held) must not throw the reader off the page they are on.
440
+ navigateSearch(
441
+ (o) => navigate(o),
442
+ (prev) => ({
443
+ ...prev,
444
+ ...resetsFor(entry, prev, next),
445
+ ...opts?.patch,
446
+ ...entry.codec.toSearch(next),
447
+ }),
448
+ entry.codec.lane.history === 'replace',
449
+ )
450
+ if (entry.codec.lane.persist) core.writeField(setRecord, entry.name, next)
440
451
  },
441
452
  ] as const
442
453
  }
@@ -459,14 +470,28 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
459
470
  /**
460
471
  * Unsetting one field, per lane: drop the mirror key (never write the fallback — a thunk fallback
461
472
  * resolved into localStorage is a value nobody chose), drop the memory value, and on the URL lane
462
- * navigate back to the fallback params through the last render of `use()`.
473
+ * navigate back to the fallback params through the mounted router.
463
474
  */
464
475
  const clearFor = (entry: StoreEntry) => (): void => {
465
476
  if (entry.codec.lane.persist) core.clearField(entry.name)
466
477
  else if (!entry.codec.lane.url) core.clearMemory(entry.name)
467
478
  if (!entry.codec.lane.url) return
468
- const clearUrl = urlClear.get(entry.name)
469
- if (clearUrl !== undefined) clearUrl()
479
+ for (const router of mounts.keys()) {
480
+ // Ownership is judged where the user is NOW (the committed, validated location), not where
481
+ // the last render happened to be.
482
+ const { search } = router.state.location
483
+ if (!isRecord(search) || !Object.hasOwn(search, entry.codec.primary)) continue
484
+ // Gated like the setter: clearing a field already at its fallback keeps the page.
485
+ navigateSearch(
486
+ (o) => router.navigate(o),
487
+ (prev) => ({
488
+ ...prev,
489
+ ...resetsFor(entry, prev, entry.codec.fallback),
490
+ ...entry.codec.toSearch(entry.codec.fallback),
491
+ }),
492
+ true,
493
+ )
494
+ }
470
495
  }
471
496
 
472
497
  const field = {} as { [K in keyof S]: FieldHandle<S[K]> }
@@ -522,22 +547,19 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
522
547
  for (const entry of validatedEntries) {
523
548
  Object.assign(patch, entry.codec.toSearch(entry.codec.fallback))
524
549
  }
525
- navigate({
526
- to: '.',
527
- // `resets` only when some field actually moves — the same gate as the setter and
528
- // `clear()`. A `Reset all` with everything already at its fallback must keep the page:
529
- // this navigate REPLACES, so a page dropped here could not be got back with Back.
530
- search: (prev: Record<string, unknown>) => {
550
+ // `resets` only when some field actually moves — the same gate as the setter and
551
+ // `clear()`. A `Reset all` with everything already at its fallback must keep the page:
552
+ // this navigate REPLACES, so a page dropped here could not be got back with Back.
553
+ navigateSearch(
554
+ (o) => navigate(o),
555
+ (prev) => {
531
556
  const moved = validatedEntries.some(
532
557
  (entry) => resetsFor(entry, prev, entry.codec.fallback) !== undefined,
533
558
  )
534
559
  return { ...prev, ...(moved ? resetPatch : undefined), ...patch }
535
560
  },
536
- replace: true,
537
- // Same reason as a single field's write above — a `Reset all` pressed from the mobile
538
- // sheet must not also scroll the page it was pressed on.
539
- resetScroll: false,
540
- })
561
+ true,
562
+ )
541
563
  }
542
564
  if (memoryEntries.length > 0) core.resetMemory()
543
565
  if (!core.anyPersisted) return
@@ -575,31 +597,3 @@ export function buildSearchStore<const S extends Record<string, AnyField>>(
575
597
 
576
598
  return store
577
599
  }
578
-
579
- /**
580
- * One store per page (or per feature), over typed fields. `key` is the localStorage key; each
581
- * field's map key is its default URL param name.
582
- *
583
- * @example
584
- * export const analytics = createSearchStore({
585
- * key: 'analytics',
586
- * fields: {
587
- * range: field.range({ presets: ['7d', '30d', '90d'], fallback: '30d', custom: true }),
588
- * compare: field.enum(['none', 'previous'], 'none'),
589
- * channels: field.multi(CHANNELS, []),
590
- * },
591
- * }).labels({ range: { '7d': 'Last 7 days', '30d': 'Last 30 days', '90d': 'Last 90 days' } })
592
- *
593
- * export const Route = createFileRoute('/analytics')({
594
- * validateSearch: analytics.validateSearch,
595
- * loaderDeps: ({ search }) => search,
596
- * })
597
- *
598
- * // in the page: <RangeFilter field={analytics.field.range} />
599
- * // in the nav: linkOptions({ to: '/analytics', search: analytics.linkSearch })
600
- */
601
- export function createSearchStore<const S extends Record<string, AnyField>>(
602
- o: CreateSearchStoreOptions<S>,
603
- ): SearchStore<S> {
604
- return buildSearchStore(o)
605
- }