basalt-ui 2.11.0 → 2.12.0

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 (109) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +26 -0
  3. package/MIGRATING.md +33 -12
  4. package/README.md +2 -0
  5. package/agent/rules/basalt-mantine.md +1 -1
  6. package/agent/skills/basalt-app/SKILL.md +1 -1
  7. package/agent/skills/basalt-charts/SKILL.md +1 -1
  8. package/dist/charts/DualPanel.d.ts.map +1 -1
  9. package/dist/charts/DualPanel.js +1 -0
  10. package/dist/charts/Lines.d.ts.map +1 -1
  11. package/dist/charts/Lines.js +7 -45
  12. package/dist/charts/MirroredBars.js +2 -2
  13. package/dist/charts/compile.d.ts.map +1 -1
  14. package/dist/charts/compile.js +21 -5
  15. package/dist/charts/labels.d.ts +34 -0
  16. package/dist/charts/labels.d.ts.map +1 -0
  17. package/dist/charts/labels.js +63 -0
  18. package/dist/charts/marks.d.ts +7 -0
  19. package/dist/charts/marks.d.ts.map +1 -1
  20. package/dist/charts/marks.js +22 -0
  21. package/dist/charts/scales.d.ts +4 -1
  22. package/dist/charts/scales.d.ts.map +1 -1
  23. package/dist/charts/scales.js +5 -3
  24. package/dist/charts/ticks.d.ts +12 -0
  25. package/dist/charts/ticks.d.ts.map +1 -0
  26. package/dist/charts/ticks.js +42 -0
  27. package/dist/charts/types.d.ts +11 -3
  28. package/dist/charts/types.d.ts.map +1 -1
  29. package/dist/cli/doctor-upgrade.d.ts +2 -3
  30. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  31. package/dist/cli/doctor-upgrade.js +71 -26
  32. package/dist/cli/index.d.ts +3 -1
  33. package/dist/cli/index.d.ts.map +1 -1
  34. package/dist/cli/index.js +3 -1
  35. package/dist/cli/sync.d.ts.map +1 -1
  36. package/dist/cli/sync.js +2 -1
  37. package/dist/commands/command-stash.d.ts +15 -0
  38. package/dist/commands/command-stash.d.ts.map +1 -0
  39. package/dist/commands/command-stash.js +31 -0
  40. package/dist/commands/define-commands.d.ts +2 -3
  41. package/dist/commands/define-commands.d.ts.map +1 -1
  42. package/dist/commands/define-commands.js +9 -7
  43. package/dist/commands/define-overlays.d.ts +6 -12
  44. package/dist/commands/define-overlays.d.ts.map +1 -1
  45. package/dist/commands/define-overlays.js +28 -34
  46. package/dist/commands/projectors.js +1 -1
  47. package/dist/provider/hotkeys.d.ts +2 -6
  48. package/dist/provider/hotkeys.d.ts.map +1 -1
  49. package/dist/provider/hotkeys.js +10 -15
  50. package/dist/provider/index.d.ts +5 -3
  51. package/dist/provider/index.d.ts.map +1 -1
  52. package/dist/provider/index.js +12 -35
  53. package/dist/provider/modals-mount.d.ts +16 -0
  54. package/dist/provider/modals-mount.d.ts.map +1 -0
  55. package/dist/provider/modals-mount.js +42 -0
  56. package/dist/provider/notifier.d.ts +22 -0
  57. package/dist/provider/notifier.d.ts.map +1 -0
  58. package/dist/provider/notifier.js +36 -0
  59. package/dist/provider/route-transition.d.ts +1 -1
  60. package/dist/provider/route-transition.d.ts.map +1 -1
  61. package/dist/provider/route-transition.js +1 -1
  62. package/dist/provider/slots.d.ts +25 -0
  63. package/dist/provider/slots.d.ts.map +1 -0
  64. package/dist/provider/slots.js +29 -0
  65. package/dist/provider/spotlight-actions.d.ts +1 -1
  66. package/dist/provider/spotlight-actions.d.ts.map +1 -1
  67. package/dist/provider/spotlight-actions.js +2 -3
  68. package/dist/provider/spotlight-mount.d.ts +3 -0
  69. package/dist/provider/spotlight-mount.d.ts.map +1 -0
  70. package/dist/provider/spotlight-mount.js +26 -0
  71. package/dist/router-tanstack/nav-stash.d.ts +24 -0
  72. package/dist/router-tanstack/nav-stash.d.ts.map +1 -0
  73. package/dist/router-tanstack/nav-stash.js +23 -0
  74. package/dist/router-tanstack/nav.d.ts +5 -15
  75. package/dist/router-tanstack/nav.d.ts.map +1 -1
  76. package/dist/router-tanstack/nav.js +6 -16
  77. package/dist/router-tanstack/use-nav.js +1 -1
  78. package/dist/surfaces.d.ts +1 -1
  79. package/dist/surfaces.js +1 -1
  80. package/llms.txt +4 -4
  81. package/package.json +2 -2
  82. package/src/charts/DualPanel.tsx +1 -0
  83. package/src/charts/Lines.tsx +11 -57
  84. package/src/charts/MirroredBars.tsx +2 -2
  85. package/src/charts/compile.ts +34 -6
  86. package/src/charts/labels.ts +118 -0
  87. package/src/charts/marks.ts +41 -0
  88. package/src/charts/scales.ts +9 -7
  89. package/src/charts/ticks.ts +61 -0
  90. package/src/charts/types.ts +11 -3
  91. package/src/cli/doctor-upgrade.ts +101 -35
  92. package/src/cli/index.ts +5 -3
  93. package/src/cli/sync.ts +2 -2
  94. package/src/commands/command-stash.ts +44 -0
  95. package/src/commands/define-commands.ts +10 -17
  96. package/src/commands/define-overlays.ts +40 -68
  97. package/src/commands/projectors.ts +1 -1
  98. package/src/provider/hotkeys.ts +14 -22
  99. package/src/provider/index.tsx +28 -52
  100. package/src/provider/modals-mount.tsx +66 -0
  101. package/src/provider/notifier.ts +52 -0
  102. package/src/provider/route-transition.ts +1 -1
  103. package/src/provider/slots.ts +59 -0
  104. package/src/provider/spotlight-actions.tsx +3 -4
  105. package/src/provider/spotlight-mount.tsx +33 -0
  106. package/src/router-tanstack/nav-stash.ts +41 -0
  107. package/src/router-tanstack/nav.ts +11 -31
  108. package/src/router-tanstack/use-nav.ts +1 -1
  109. package/src/surfaces.ts +1 -1
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Tick selection that needs no engine: the stride every band axis shares, and the round,
3
+ * bucket-snapped ticks of a bucketed Date axis.
4
+ */
5
+ import { scaleUtc } from 'd3-scale'
6
+
7
+ /** Every n-th value, n the smallest stride that leaves at most `count` of them. */
8
+ export function strideEvery<V>(values: readonly V[], count: number): V[] {
9
+ const stride = Math.max(1, Math.ceil(values.length / Math.max(1, count)))
10
+ return values.filter((_, i) => i % stride === 0)
11
+ }
12
+
13
+ /** The median gap between sorted, DISTINCT numbers: two or more of them leave a positive one. */
14
+ function medianGap(sorted: readonly number[]): number {
15
+ const gaps = sorted.slice(1).map((t, i) => t - (sorted[i] as number))
16
+ return gaps.toSorted((a, b) => a - b)[gaps.length >> 1] as number
17
+ }
18
+
19
+ /** The index of the value nearest `target` in an ascending, non-empty array (binary search). */
20
+ function nearestIndex(sorted: readonly number[], target: number): number {
21
+ let lo = 0
22
+ let hi = sorted.length - 1
23
+ while (lo < hi) {
24
+ const mid = (lo + hi) >> 1
25
+ if ((sorted[mid] as number) < target) lo = mid + 1
26
+ else hi = mid
27
+ }
28
+ const before = lo - 1
29
+ return before >= 0 && target - (sorted[before] as number) <= (sorted[lo] as number) - target
30
+ ? before
31
+ : lo
32
+ }
33
+
34
+ /**
35
+ * Ticks of a bucketed Date axis: the time scale's own round instants, each snapped to the bucket
36
+ * it falls in. Labelling every bucket and letting the engine thin the collisions leaves an uneven,
37
+ * near-touching subset ("18:13 18:17 18:21"); round instants are evenly spaced whenever the
38
+ * buckets are. A bucket is used once, and a round instant with no bucket within a step of it is
39
+ * dropped. Fewer than two picks falls back to a plain stride over the distinct,
40
+ * sorted buckets. `count` must be finite (`xTickPolicy` guards it). O(ticks · log buckets) after the sort.
41
+ */
42
+ export function bucketTicks(values: readonly Date[], count: number): Date[] {
43
+ const times = [...new Set(values.map((v) => v.getTime()).filter(Number.isFinite))].toSorted(
44
+ (a, b) => a - b,
45
+ )
46
+ const asDates = (ts: readonly number[]): Date[] => ts.map((t) => new Date(t))
47
+ const first = times[0]
48
+ const last = times.at(-1)
49
+ if (first === undefined || last === undefined || first === last) return asDates(times)
50
+ const step = medianGap(times)
51
+ const want = Math.max(1, Math.floor(count))
52
+ const picked = new Set<number>()
53
+ for (const tick of scaleUtc()
54
+ .domain([new Date(first), new Date(last)])
55
+ .ticks(want)) {
56
+ const t = tick.getTime()
57
+ const near = times[nearestIndex(times, t)]
58
+ if (near !== undefined && Math.abs(near - t) < step) picked.add(near)
59
+ }
60
+ return asDates(picked.size >= 2 ? [...picked] : strideEvery(times, want))
61
+ }
@@ -67,9 +67,11 @@ export type ChartSeries<T> = {
67
67
  * dot follows the datum. A series drawn from `plot.rows` already has one.
68
68
  */
69
69
  cursorValue?: ((d: T) => number | null) | undefined
70
- /** A marker at a point (a PR star, a status dot); `null` for none. On a `cursorValue` series
71
- * only `color` applies, to the cursor dot, and each distinct color is one extra mark: keep colors
72
- * a small categorical set (statuses, buckets), never a continuous scale. */
70
+ /** A marker at a point (a PR star, a status dot); `null` for none. Always-on markers are `Lines`'
71
+ * alone. On a `CartesianChart` with consumer `marks` only the CURSOR dot of a `cursorValue`
72
+ * series reads `getMarker` (its `color`): without `cursorValue` it is ignored there, so draw a
73
+ * persistent dot in `marks` yourself. Each distinct color is one extra mark: keep colors a small
74
+ * categorical set (statuses, buckets), never a continuous scale. */
73
75
  getMarker?:
74
76
  | ((d: T) => {
75
77
  color?: string | undefined
@@ -265,6 +267,12 @@ export type PlotContext<T, X extends ChartX = ChartX> = {
265
267
  data: readonly T[]
266
268
  /** Bind a mark to the right axis with `yScale: plot.y2` (present only with a `y2` config). */
267
269
  y2: 'y2' | undefined
270
+ /**
271
+ * Where an x value sits in the plot, 0 (left edge) to 1 (right edge), on the SAME x scale the
272
+ * axis draws: an explicit `xDomain` or the extent of every datum. Outside [0, 1] a value is
273
+ * clipped; `null` for a value the scale cannot place.
274
+ */
275
+ xFraction: (x: X) => number | null
268
276
  /** The resolved y domain (and the right axis', with `y2`): basalt's, never the engine's. */
269
277
  yDomain: readonly [number, number]
270
278
  y2Domain: readonly [number, number] | undefined
@@ -2,13 +2,14 @@
2
2
  * `doctor`'s 2.0 strictness and upgrade checks. Each returns null (pass), `{ fail }` (the problem
3
3
  * plus its fix) or `{ skip }` (the check could not run: a check that cannot run is not a pass).
4
4
  */
5
- import { writeFileSync } from 'node:fs'
5
+ import { readdirSync, writeFileSync } from 'node:fs'
6
+ import type { Dirent } from 'node:fs'
6
7
  import { createRequire } from 'node:module'
7
8
  import { dirname, relative, resolve } from 'node:path'
8
9
 
9
10
  import { BASALT_CONFIG_KEYS, RETIRED_CONFIG_KEYS, shellConfigError } from './config'
10
11
  import type { BasaltConfig } from './config'
11
- import { parseJsonc, routerSeedDest, scannableFiles } from './index'
12
+ import { START_PROVIDER_HINT, parseJsonc, routerSeedDest, scannableFiles } from './index'
12
13
  import type { BasaltInstall } from './index'
13
14
  import {
14
15
  appEntry,
@@ -405,51 +406,116 @@ function providerTags(src: string): ProviderTag[] {
405
406
 
406
407
  const carriesRouter = (tag: ProviderTag): boolean => /(^|\s)router\s*=/.test(tag.attrs)
407
408
 
409
+ /** `_app.tsx` or `_app/route.tsx` at any depth: a pathless layout (`_app.map.tsx` is a child, `__root` is the root). */
410
+ const PATHLESS_LAYOUT = /(^|\/)(_[^_./][^./]*\.[jt]sx|_[^_./][^./]*\/route\.[jt]sx)$/
411
+
412
+ /** Every file under `rel`, recursively; an unreadable directory has no files. */
413
+ function filesUnder(cwd: string, rel: string): string[] {
414
+ let entries: Dirent[]
415
+ try {
416
+ entries = readdirSync(resolve(cwd, rel), { withFileTypes: true })
417
+ } catch {
418
+ return []
419
+ }
420
+ return entries.flatMap((e) =>
421
+ e.isDirectory() ? filesUnder(cwd, `${rel}/${e.name}`) : [`${rel}/${e.name}`],
422
+ )
423
+ }
424
+
425
+ type RouteFile = { file: string; text: string | null; tags: ProviderTag[] }
426
+
427
+ /** The root route and every pathless layout, each read once; `text` is null for a missing file. */
428
+ function startProviderFiles(cwd: string): { root: RouteFile; layouts: RouteFile[] } {
429
+ const rootFile = routerSeedDest('', 'root')
430
+ const routesDir = dirname(rootFile)
431
+ const load = (file: string): RouteFile => {
432
+ const text = readIfExists(resolve(cwd, file))
433
+ return { file, text, tags: providerTags(text ?? '') }
434
+ }
435
+ const layouts = filesUnder(cwd, routesDir)
436
+ .filter((f) => PATHLESS_LAYOUT.test(f.slice(routesDir.length + 1)))
437
+ .toSorted()
438
+ return { root: load(rootFile), layouts: layouts.map(load) }
439
+ }
440
+
441
+ /**
442
+ * How the exported root route is created: `createRootRouteWithContext` is typed (TypeScript gates the
443
+ * context at `createRouter`), `createRootRoute` is not. Anything else (a re-export, a wrapper, no
444
+ * `export const Route`) is null and never fails. A type annotation on `Route` is allowed.
445
+ */
446
+ function rootRouteKind(src: string): 'typed' | 'untyped' | null {
447
+ const kind =
448
+ /\bexport\s+const\s+Route\s*(?::[^=]+)?=\s*(createRootRouteWithContext|createRootRoute)\b/.exec(
449
+ tokenize(src).code,
450
+ )?.[1]
451
+ if (kind === undefined) return null
452
+ return kind === 'createRootRoute' ? 'untyped' : 'typed'
453
+ }
454
+
455
+ const fail = (problem: string, fix: string): { fail: string } => ({
456
+ fail: `app-wiring: ${problem} (TanStack Start app). Fix: ${fix}.`,
457
+ })
458
+
408
459
  /**
409
- * A Start app owns its router and entry: the wiring is an embedded `<BasaltProvider>` (no `router=`)
410
- * in its root route component, around `<Outlet />`. ANY tag with `router=` mounts a second router
411
- * inside Start's, so it fails even beside an embedded one.
460
+ * A Start app owns its router and entry: the wiring is ONE embedded `<BasaltProvider>` tag (no
461
+ * `router=`) around `<Outlet />`, in the root route or a pathless layout (a landing kept at 0 JS
462
+ * mounts it in the layout). ANY tag with `router=` mounts a second router inside Start's, so it
463
+ * fails even beside an embedded one. The exported root route must not be a bare `createRootRoute(`:
464
+ * the provider reads `context.queryClient`. Only that untyped form fails — a re-export, wrapper or
465
+ * missing `Route` export is skipped silently, and the context's type argument is left to TypeScript.
412
466
  */
413
467
  function startWiring(cwd: string): { fail: string } | null {
414
- const root = routerSeedDest('', 'root')
415
- const text = readIfExists(resolve(cwd, root))
416
- const tags = providerTags(text ?? '')
417
- const mounting = tags.some(carriesRouter)
418
- if (!mounting && tags.length > 0) return null
419
- const problem =
420
- text === null
421
- ? 'does not exist'
422
- : mounting
423
- ? 'passes router= to BasaltProvider, which mounts a second router inside Start'
424
- : 'does not render <BasaltProvider>'
425
- return {
426
- fail: `app-wiring: ${root} ${problem} (TanStack Start app). Fix: render <BasaltProvider><Outlet /></BasaltProvider> in the root route component.`,
468
+ const { root, layouts } = startProviderFiles(cwd)
469
+ const withTags = [root, ...layouts].filter((f) => f.tags.length > 0)
470
+ const mounting = withTags.find((f) => f.tags.some(carriesRouter))
471
+ if (mounting) {
472
+ return fail(
473
+ `${mounting.file} passes router= to BasaltProvider, which mounts a second router inside Start`,
474
+ START_PROVIDER_HINT,
475
+ )
476
+ }
477
+ const [first] = withTags
478
+ if (first === undefined) {
479
+ const problem =
480
+ root.text === null
481
+ ? `${root.file} does not exist and no pathless layout renders <BasaltProvider>`
482
+ : `neither ${root.file} nor a pathless layout (src/routes/_<name>.tsx, _<name>/route.tsx) renders <BasaltProvider>`
483
+ return fail(problem, START_PROVIDER_HINT)
484
+ }
485
+ const tagCount = withTags.reduce((n, f) => n + f.tags.length, 0)
486
+ if (tagCount > 1) {
487
+ return fail(
488
+ `${withTags.map((f) => f.file).join(' and ')} render ${tagCount} <BasaltProvider> tags; the extra ones nest a duplicate Query/Mantine tree`,
489
+ 'keep one',
490
+ )
427
491
  }
492
+ if (root.text === null) {
493
+ return fail(
494
+ `${root.file} does not exist, so the provider in ${first.file} has no root route context`,
495
+ 'create it with `export const Route = createRootRouteWithContext<BasaltRouterContext>()({ … })`',
496
+ )
497
+ }
498
+ if (rootRouteKind(root.text) !== 'untyped') return null
499
+ return fail(
500
+ `${root.file} exports a Route built with createRootRoute(), so its router context has no queryClient, which the embedded BasaltProvider reads from context.queryClient`,
501
+ "`createRootRouteWithContext<BasaltRouterContext>()({ … })` (import type { BasaltRouterContext } from 'basalt-ui') and pass the QueryClient in createRouter({ context })",
502
+ )
428
503
  }
429
504
 
430
505
  /**
431
- * Warnings for a Start app's embedded provider; heuristics, not proofs. A `{...spread}` on the tag
432
- * could carry a `router`; `src/router.tsx` never mentioning `queryClient` means the embedded
433
- * provider will find no `context.queryClient`. Empty when there is nothing to judge.
506
+ * Warnings for a Start app's embedded provider; heuristics, not proofs. A `{...spread}` on a tag
507
+ * could carry a `router`. Empty when there is nothing to judge.
434
508
  */
435
509
  export function startWiringWarnings(cwd: string): string[] {
436
510
  if (!isStartApp(cwd, '')) return []
437
- const out: string[] = []
438
- const root = readIfExists(resolve(cwd, routerSeedDest('', 'root')))
439
- if (root !== null && providerTags(root).some((t) => t.spread)) {
440
- out.push(
441
- 'app-wiring: <BasaltProvider {...spread}> in the root route could pass router=, which mounts ' +
511
+ const { root, layouts } = startProviderFiles(cwd)
512
+ return [root, ...layouts]
513
+ .filter((f) => f.tags.some((t) => t.spread))
514
+ .map(
515
+ (f) =>
516
+ `app-wiring: <BasaltProvider {...spread}> in ${f.file} could pass router=, which mounts ` +
442
517
  'a second router inside Start (heuristic: the spread is not followed).',
443
518
  )
444
- }
445
- const router = readIfExists(resolve(cwd, 'src/router.tsx'))
446
- if (router !== null && !/queryClient/.test(router)) {
447
- out.push(
448
- 'app-wiring: src/router.tsx never mentions queryClient — embedded BasaltProvider needs ' +
449
- 'context.queryClient on the Start router (heuristic text check; ignore if you build it elsewhere).',
450
- )
451
- }
452
- return out
453
519
  }
454
520
 
455
521
  const BASALT_SHELL_TAG = /<BasaltShell\b/g
package/src/cli/index.ts CHANGED
@@ -661,9 +661,11 @@ export function routerSeedDests(appRel: string): string[] {
661
661
  )
662
662
  }
663
663
 
664
- export const START_APP_NOTE =
665
- 'TanStack Start app — no main.tsx/nav.tsx/__root.tsx seeded (Start owns the router); render ' +
666
- '<BasaltProvider><Outlet /></BasaltProvider> in your root route component.'
664
+ /** Where a Start app's embedded provider goes (doctor, init and sync all say it). */
665
+ export const START_PROVIDER_HINT =
666
+ 'render <BasaltProvider><Outlet /></BasaltProvider> in the root route component or a pathless layout'
667
+
668
+ export const START_APP_NOTE = `TanStack Start app — no main.tsx/nav.tsx/__root.tsx seeded (Start owns the router); ${START_PROVIDER_HINT}.`
667
669
 
668
670
  /**
669
671
  * The router seeds an app does not get, for `init` and `sync`: why (`start` | `code-routed` |
package/src/cli/sync.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  sha256,
37
37
  shippedAssetPath,
38
38
  START_APP_NOTE,
39
+ START_PROVIDER_HINT,
39
40
  unitState,
40
41
  writeFileEnsuringDir,
41
42
  writeUnit,
@@ -232,8 +233,7 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
232
233
  const stale = startSkippedSeeds.filter((d) => isTracked(d) && existsSync(resolve(cwd, d)))
233
234
  const mounting = stale.filter((d) => !d.endsWith('nav.tsx'))
234
235
  const inert = stale.filter((d) => d.endsWith('nav.tsx'))
235
- const embedded =
236
- 'Delete them and render <BasaltProvider><Outlet /></BasaltProvider> in the Start root route (embedded mode).'
236
+ const embedded = `Delete them and ${START_PROVIDER_HINT} (embedded mode).`
237
237
  if (mounting.length > 0) {
238
238
  console.error(
239
239
  `⚠ basalt-ui sync: ${mounting.join(', ')} mount a second router inside this TanStack Start app; left untouched. ${embedded}`,
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The command registry's runtime stash, as a leaf: no React, no peers. `defineCommands` fills it;
3
+ * the provider's hotkey binder, the Spotlight projector and `ShortcutsHelp` read it. Kept apart from
4
+ * `define-commands.ts` so a reader never imports the module that registers feature mounts.
5
+ */
6
+ import { createNotifier } from '../provider/notifier'
7
+ import type { Command, CommandMap } from './define-commands'
8
+
9
+ let activeCommands: CommandMap = {}
10
+ const store = createNotifier()
11
+
12
+ /** @internal — `defineCommands` only. The last call wins; readers subscribed via {@link subscribeCommands} re-read. */
13
+ export function setActiveCommands(spec: CommandMap): void {
14
+ activeCommands = spec
15
+ store.notify()
16
+ }
17
+
18
+ /** @internal — test isolation only. */
19
+ export function resetCommandStash(): void {
20
+ setActiveCommands({})
21
+ }
22
+
23
+ /** @internal — exposed to the provider and projectors.ts to iterate the runtime stash. Returns a readonly view. */
24
+ export function getActiveCommands(): Readonly<CommandMap> {
25
+ return activeCommands
26
+ }
27
+
28
+ /** @internal — `useSyncExternalStore` subscribe for a late `defineCommands` (a lazily loaded route). */
29
+ export const subscribeCommands = store.subscribe
30
+
31
+ /**
32
+ * Runs a command, swallowing a sync throw or async rejection so a failing command never becomes an
33
+ * unhandled rejection (which the provider would report as a `window.error`). Dev logs it.
34
+ */
35
+ export function runCommandSafely(cmd: Command): void {
36
+ const report = (error: unknown): void => {
37
+ if (process.env.NODE_ENV !== 'production') console.error('[basalt] command failed', error)
38
+ }
39
+ try {
40
+ Promise.resolve(cmd.run()).catch(report)
41
+ } catch (error) {
42
+ report(error)
43
+ }
44
+ }
@@ -19,7 +19,11 @@
19
19
  */
20
20
  import type { Hotkey } from '@tanstack/react-hotkeys'
21
21
  import type { ReactNode } from 'react'
22
+ import { HotkeyBinder } from '../provider/hotkeys'
23
+ import { registerSlot } from '../provider/slots'
24
+ import { SpotlightMount } from '../provider/spotlight-mount'
22
25
  import type { Slot } from '../register'
26
+ import { setActiveCommands } from './command-stash'
23
27
 
24
28
  // ── Context ───────────────────────────────────────────────────────────────────
25
29
 
@@ -101,16 +105,6 @@ type Commands = Slot<'commands', CommandMap>
101
105
  */
102
106
  export type CommandId = Extract<keyof Commands, string>
103
107
 
104
- // ── Runtime stash ─────────────────────────────────────────────────────────────
105
-
106
- /**
107
- * Module-level runtime registry. The BasaltRegister type-slot gives the compile-time id union,
108
- * but the augmentation is erased at runtime — so defineCommands also stashes the runtime map here
109
- * for the provider and the projectors to resolve Command objects. Call defineCommands once (the
110
- * app's single command registry); the last call wins.
111
- */
112
- let activeCommands: CommandMap = {}
113
-
114
108
  // ── defineCommands ────────────────────────────────────────────────────────────
115
109
 
116
110
  /**
@@ -118,7 +112,8 @@ let activeCommands: CommandMap = {}
118
112
  * keys so the id union is exact after augmenting BasaltRegister.
119
113
  *
120
114
  * Stashes the runtime map so the provider resolves commands at runtime (type augmentation is
121
- * erased; the stash is the live source).
115
+ * erased; the stash is the live source), and registers the provider mounts that need it: Spotlight,
116
+ * plus the hotkey binder when any command has a `shortcut`. Nothing else pulls those into a bundle.
122
117
  *
123
118
  * @example
124
119
  * export const COMMANDS = defineCommands({
@@ -129,7 +124,10 @@ let activeCommands: CommandMap = {}
129
124
  * }
130
125
  */
131
126
  export function defineCommands<const T extends CommandMap>(spec: T): T {
132
- activeCommands = spec
127
+ setActiveCommands(spec)
128
+ registerSlot('spotlight', SpotlightMount)
129
+ if (Object.values(spec).some((c) => c.shortcut !== undefined))
130
+ registerSlot('hotkeys', HotkeyBinder)
133
131
  return spec
134
132
  }
135
133
 
@@ -150,8 +148,3 @@ export function defineCommands<const T extends CommandMap>(spec: T): T {
150
148
  export function defineCommand(cmd: Command): Command {
151
149
  return cmd
152
150
  }
153
-
154
- /** @internal — exposed to the provider and projectors.ts to iterate the runtime stash. Returns a readonly view. */
155
- export function getActiveCommands(): Readonly<CommandMap> {
156
- return activeCommands
157
- }
@@ -8,7 +8,8 @@
8
8
  * A form dialog is an entry whose `render` returns the form; open it from a row action with
9
9
  * `overlays.open('id', props)` and put its component in a `*-modal.tsx`.
10
10
  *
11
- * Uses @mantine/modals under the hood. ModalsProvider must be mounted (BasaltProvider does this).
11
+ * Uses @mantine/modals under the hood. Calling `defineOverlays` registers the `ModalsProvider` mount
12
+ * (a sibling of the router, in `BasaltProvider`) — an app that defines none ships none of the peer.
12
13
  *
13
14
  * @example
14
15
  * // overlays.ts (app-side)
@@ -31,53 +32,11 @@
31
32
  import type { ReactNode } from 'react'
32
33
  import { missingLayer } from '../common/errors'
33
34
  import type { Slot } from '../register'
35
+ import { modals } from '@mantine/modals'
36
+ import { ensureModalsMount, registerModalsMount } from '../provider/modals-mount'
34
37
 
35
- // ── Lazy @mantine/modals resolution ───────────────────────────────────────────
36
- // @mantine/modals is an OPTIONAL peer — never imported at module evaluation time, so importing
37
- // this module (and the ./commands barrel that re-exports it) does not require the peer. Resolves
38
- // to undefined when the peer is absent — overlays.open/close then degrade to a no-op.
39
-
40
- type ModalsModule = typeof import('@mantine/modals')
41
- type ModalsSingleton = ModalsModule['modals']
42
-
43
- let modalsPromise: Promise<ModalsSingleton | undefined> | undefined
44
-
45
- function loadModals(): Promise<ModalsSingleton | undefined> {
46
- modalsPromise ??= import('@mantine/modals').then((m) => m.modals).catch(() => undefined)
47
- return modalsPromise
48
- }
49
-
50
- // ── Modals-layer availability ─────────────────────────────────────────────────
51
-
52
- /**
53
- * How many `ModalsProvider`s are live right now — a COUNTER, not a flag: two overlapping mounts
54
- * are normal (a route swap mounts the next provider before unmounting the previous one), and a
55
- * last-write-wins boolean reports the teardown of the OLD one as "no layer" while the new one is
56
- * serving.
57
- *
58
- * It is the availability test `overlays.confirm` runs, because `@mantine/modals`' imperative API is
59
- * a window event bus: with nothing subscribed the dialog never appears and the promise never
60
- * settles.
61
- */
62
- let mountedModalsProviders = 0
63
-
64
- /**
65
- * Internal — `BasaltProvider` declares its `ModalsProvider` as live for as long as it is mounted,
66
- * and gets back the function that retracts it. There is no way to detect the provider from outside
67
- * React (its context is only readable through `useModals()`, and `confirm` is an imperative call),
68
- * so the registration is explicit. Not on the `./commands` barrel.
69
- */
70
- export function registerModalsProvider(): () => void {
71
- mountedModalsProviders++
72
- let released = false
73
- return () => {
74
- // Idempotent: an effect cleanup React runs twice (StrictMode remount) must not drive the count
75
- // below the number of providers actually on screen.
76
- if (released) return
77
- released = true
78
- mountedModalsProviders--
79
- }
80
- }
38
+ /** Bumped by `overlays.close()`; a deferred open / confirm that started in an older generation is cancelled. */
39
+ let closeGeneration = 0
81
40
 
82
41
  // ── Overlay + OverlayMap ──────────────────────────────────────────────────────
83
42
 
@@ -150,6 +109,7 @@ let activeOverlays: OverlayMap = {}
150
109
  */
151
110
  export function defineOverlays<const T extends OverlayMap>(spec: T): T {
152
111
  activeOverlays = spec
112
+ registerModalsMount()
153
113
  return spec
154
114
  }
155
115
 
@@ -213,10 +173,10 @@ export type ConfirmDeleteOptions = {
213
173
  * other exit (cancel, escape, click-outside, the close button). `onConfirm`/`onCancel` fire exactly
214
174
  * once each at most, before the promise settles.
215
175
  *
216
- * Rejects with a named `[basalt]` error when the modals layer cannot serve the dialog — the
217
- * `@mantine/modals` peer is absent, or no `ModalsProvider` is registered as live (see
218
- * {@link registerModalsProvider}). Both would otherwise leave the promise pending forever: the
219
- * imperative API is a window event bus with nothing subscribed.
176
+ * The first call registers the modals mount and waits for the `BasaltProvider` to commit it — a tick
177
+ * normally, up to 5 s while a provider is mounted and busy. Rejects with a named `[basalt]` error when
178
+ * no `BasaltProvider` is mounted (after a 500 ms grace for one mounting now): the imperative API is a
179
+ * window event bus, and with nothing subscribed the promise would stay pending forever.
220
180
  *
221
181
  * @example
222
182
  * if (await overlays.confirm({ title: 'Discard draft?', onConfirm: () => reset() })) navigate('/')
@@ -241,17 +201,15 @@ async function confirm(options: ConfirmOptions): Promise<boolean> {
241
201
  onCancel,
242
202
  } = options
243
203
 
244
- const modals = await loadModals()
245
- if (modals === undefined) {
246
- throw new Error(
247
- missingLayer(
248
- 'overlays.confirm',
249
- '@mantine/modals',
250
- 'install the @mantine/modals peer and mount <BasaltProvider>',
251
- ),
252
- )
204
+ const startedAt = closeGeneration
205
+ // `confirm` needs no registry entry, so it asks for the mount itself and waits for the provider.
206
+ const live = await ensureModalsMount()
207
+ if (startedAt !== closeGeneration) {
208
+ // `overlays.close()` ran while the mount was pending: the dialog never opens, the answer is "no".
209
+ onCancel?.()
210
+ return false
253
211
  }
254
- if (mountedModalsProviders === 0) {
212
+ if (!live) {
255
213
  throw new Error(
256
214
  missingLayer(
257
215
  'overlays.confirm',
@@ -356,12 +314,24 @@ export const overlays = {
356
314
  console.warn(`[basalt] overlays.open: no overlay registered for "${String(key)}"`)
357
315
  return
358
316
  }
359
- void loadModals().then((modals) =>
360
- modals?.open({
361
- title: spec.title,
362
- children: spec.render(props),
363
- }),
364
- )
317
+ // A `defineOverlays` made after first render has its mount committed a tick later: wait for it,
318
+ // or the dialog is published to a bus with no subscriber and lost.
319
+ const startedAt = closeGeneration
320
+ void ensureModalsMount().then((live) => {
321
+ // `overlays.close()` ran while the mount was pending: it cancels this open.
322
+ if (startedAt !== closeGeneration) return
323
+ if (!live) {
324
+ if (process.env.NODE_ENV !== 'production') {
325
+ console.warn('[basalt] overlays.open: no mounted <BasaltProvider> to show the overlay')
326
+ }
327
+ return
328
+ }
329
+ try {
330
+ modals.open({ title: spec.title, children: spec.render(props) })
331
+ } catch (error) {
332
+ if (process.env.NODE_ENV !== 'production') console.error('[basalt] overlay failed', error)
333
+ }
334
+ })
365
335
  },
366
336
 
367
337
  /**
@@ -387,6 +357,8 @@ export const overlays = {
387
357
  * overlays.close()
388
358
  */
389
359
  close(): void {
390
- void loadModals().then((modals) => modals?.closeAll())
360
+ // Cancels every open / confirm still waiting for the modals mount.
361
+ closeGeneration++
362
+ modals.closeAll()
391
363
  },
392
364
  }
@@ -3,7 +3,7 @@
3
3
  * `ShortcutsHelp` renders. Reads the runtime stash (populated by `defineCommands`), not the
4
4
  * type-erased `BasaltRegister` slot; safe to call before any commands are registered.
5
5
  */
6
- import { getActiveCommands } from './define-commands'
6
+ import { getActiveCommands } from './command-stash'
7
7
 
8
8
  // ── ShortcutEntry ─────────────────────────────────────────────────────────────
9
9
 
@@ -3,32 +3,18 @@
3
3
  * `shortcut`. `@tanstack/react-hotkeys` is subpath-required for `./commands`, so it is reached
4
4
  * through `import()` only and its runtime stays off first paint (V2-SPEC § 2).
5
5
  *
6
- * `defineCommands` has no loader-registration seam yet; when `./commands` grows one (it calls this
7
- * module's loader instead), this registry check is what goes away.
6
+ * `defineCommands` registers `HotkeyBinder` as the provider's `hotkeys` slot when a command has a
7
+ * shortcut, so this module (and the peer behind its `import()`) is reachable only from there.
8
8
  */
9
9
  import type { HotkeyRegistrationHandle } from '@tanstack/react-hotkeys'
10
- import { useEffect } from 'react'
11
- import { getActiveCommands } from '../commands/define-commands'
12
- import type { Command } from '../commands/define-commands'
13
-
14
- /**
15
- * Runs a command, swallowing a sync throw or async rejection so a failing command never becomes an
16
- * unhandled rejection (which the provider would report as a `window.error`). Dev logs it.
17
- */
18
- export function runCommandSafely(cmd: Command): void {
19
- const report = (error: unknown): void => {
20
- if (process.env.NODE_ENV !== 'production') console.error('[basalt] command failed', error)
21
- }
22
- try {
23
- Promise.resolve(cmd.run()).catch(report)
24
- } catch (error) {
25
- report(error)
26
- }
27
- }
10
+ import { useEffect, useSyncExternalStore } from 'react'
11
+ import { getActiveCommands, runCommandSafely, subscribeCommands } from '../commands/command-stash'
28
12
 
29
13
  export function useRegistryHotkeys(): void {
14
+ // A late `defineCommands` (a lazily loaded route) replaces the map; re-bind against the new one.
15
+ const registry = useSyncExternalStore(subscribeCommands, getActiveCommands, getActiveCommands)
30
16
  useEffect(() => {
31
- const commands = Object.values(getActiveCommands()).filter((c) => c.shortcut !== undefined)
17
+ const commands = Object.values(registry).filter((c) => c.shortcut !== undefined)
32
18
  if (commands.length === 0) return
33
19
 
34
20
  let cancelled = false
@@ -66,5 +52,11 @@ export function useRegistryHotkeys(): void {
66
52
  cancelled = true
67
53
  for (const handle of handles) handle.unregister()
68
54
  }
69
- }, [])
55
+ }, [registry])
56
+ }
57
+
58
+ /** The `hotkeys` slot mount: renders nothing, binds the registry's shortcuts. */
59
+ export function HotkeyBinder(): null {
60
+ useRegistryHotkeys()
61
+ return null
70
62
  }