basalt-ui 2.11.1 → 2.13.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 (151) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +39 -0
  3. package/MIGRATING.md +51 -12
  4. package/README.md +2 -0
  5. package/agent/rules/basalt-mantine.md +1 -1
  6. package/agent/rules/basalt-state.md +1 -1
  7. package/agent/skills/basalt-app/SKILL.md +2 -2
  8. package/agent/templates/main.tpl +1 -0
  9. package/dist/cli/basalt-install.d.ts +10 -0
  10. package/dist/cli/basalt-install.d.ts.map +1 -0
  11. package/dist/cli/basalt-install.js +0 -0
  12. package/dist/cli/check-theme.js +1 -1
  13. package/dist/cli/doctor-upgrade.d.ts +5 -6
  14. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  15. package/dist/cli/doctor-upgrade.js +85 -56
  16. package/dist/cli/doctor.js +3 -3
  17. package/dist/cli/index.d.ts +5 -27
  18. package/dist/cli/index.d.ts.map +1 -1
  19. package/dist/cli/index.js +12 -49
  20. package/dist/cli/provider-tags.d.ts +12 -0
  21. package/dist/cli/provider-tags.d.ts.map +1 -0
  22. package/dist/cli/provider-tags.js +28 -0
  23. package/dist/cli/render-imports.d.ts +24 -0
  24. package/dist/cli/render-imports.d.ts.map +1 -0
  25. package/dist/cli/render-imports.js +74 -0
  26. package/dist/cli/router-wiring.d.ts +12 -0
  27. package/dist/cli/router-wiring.d.ts.map +1 -1
  28. package/dist/cli/router-wiring.js +18 -0
  29. package/dist/cli/source-text.d.ts +7 -0
  30. package/dist/cli/source-text.d.ts.map +1 -1
  31. package/dist/cli/source-text.js +34 -0
  32. package/dist/cli/sync.d.ts.map +1 -1
  33. package/dist/cli/sync.js +19 -13
  34. package/dist/commands/command-stash.d.ts +15 -0
  35. package/dist/commands/command-stash.d.ts.map +1 -0
  36. package/dist/commands/command-stash.js +31 -0
  37. package/dist/commands/define-commands.d.ts +2 -3
  38. package/dist/commands/define-commands.d.ts.map +1 -1
  39. package/dist/commands/define-commands.js +9 -7
  40. package/dist/commands/define-overlays.d.ts +6 -12
  41. package/dist/commands/define-overlays.d.ts.map +1 -1
  42. package/dist/commands/define-overlays.js +28 -34
  43. package/dist/commands/projectors.js +1 -1
  44. package/dist/guard/fonts-hint.d.ts +3 -0
  45. package/dist/guard/fonts-hint.d.ts.map +1 -0
  46. package/dist/guard/fonts-hint.js +4 -0
  47. package/dist/guard/index.d.ts +1 -1
  48. package/dist/guard/index.d.ts.map +1 -1
  49. package/dist/guard/index.js +2 -1
  50. package/dist/index.d.ts +3 -3
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +3 -1
  53. package/dist/provider/create-router.d.ts +57 -10
  54. package/dist/provider/create-router.d.ts.map +1 -1
  55. package/dist/provider/create-router.js +28 -17
  56. package/dist/provider/hotkeys.d.ts +2 -6
  57. package/dist/provider/hotkeys.d.ts.map +1 -1
  58. package/dist/provider/hotkeys.js +10 -15
  59. package/dist/provider/index.d.ts +7 -5
  60. package/dist/provider/index.d.ts.map +1 -1
  61. package/dist/provider/index.js +35 -42
  62. package/dist/provider/modals-mount.d.ts +16 -0
  63. package/dist/provider/modals-mount.d.ts.map +1 -0
  64. package/dist/provider/modals-mount.js +42 -0
  65. package/dist/provider/notifier.d.ts +22 -0
  66. package/dist/provider/notifier.d.ts.map +1 -0
  67. package/dist/provider/notifier.js +36 -0
  68. package/dist/provider/route-transition.d.ts +1 -1
  69. package/dist/provider/route-transition.d.ts.map +1 -1
  70. package/dist/provider/route-transition.js +1 -1
  71. package/dist/provider/slots.d.ts +25 -0
  72. package/dist/provider/slots.d.ts.map +1 -0
  73. package/dist/provider/slots.js +29 -0
  74. package/dist/provider/spotlight-actions.d.ts +1 -1
  75. package/dist/provider/spotlight-actions.d.ts.map +1 -1
  76. package/dist/provider/spotlight-actions.js +2 -3
  77. package/dist/provider/spotlight-mount.d.ts +3 -0
  78. package/dist/provider/spotlight-mount.d.ts.map +1 -0
  79. package/dist/provider/spotlight-mount.js +26 -0
  80. package/dist/query-client.d.ts +2 -62
  81. package/dist/query-client.d.ts.map +1 -1
  82. package/dist/query-client.js +13 -18
  83. package/dist/router-tanstack/nav-stash.d.ts +24 -0
  84. package/dist/router-tanstack/nav-stash.d.ts.map +1 -0
  85. package/dist/router-tanstack/nav-stash.js +23 -0
  86. package/dist/router-tanstack/nav.d.ts +5 -15
  87. package/dist/router-tanstack/nav.d.ts.map +1 -1
  88. package/dist/router-tanstack/nav.js +6 -16
  89. package/dist/router-tanstack/search-store-warnings.d.ts +33 -0
  90. package/dist/router-tanstack/search-store-warnings.d.ts.map +1 -0
  91. package/dist/router-tanstack/search-store-warnings.js +77 -0
  92. package/dist/router-tanstack/search-store.d.ts +2 -5
  93. package/dist/router-tanstack/search-store.d.ts.map +1 -1
  94. package/dist/router-tanstack/search-store.js +111 -110
  95. package/dist/router-tanstack/use-nav.js +1 -1
  96. package/dist/surfaces.d.ts +1 -1
  97. package/dist/surfaces.js +1 -1
  98. package/dist/telemetry.d.ts +31 -2
  99. package/dist/telemetry.d.ts.map +1 -1
  100. package/dist/telemetry.js +32 -12
  101. package/dist/theme/ctl-theme.d.ts.map +1 -1
  102. package/dist/theme/ctl-theme.js +17 -30
  103. package/dist/theme/extend.d.ts +18 -0
  104. package/dist/theme/extend.d.ts.map +1 -0
  105. package/dist/theme/extend.js +6 -0
  106. package/dist/theme/index.d.ts.map +1 -1
  107. package/dist/theme/index.js +44 -84
  108. package/dist/unwrap.d.ts +29 -0
  109. package/dist/unwrap.d.ts.map +1 -0
  110. package/dist/unwrap.js +18 -0
  111. package/llms.txt +11 -7
  112. package/package.json +2 -2
  113. package/src/cli/basalt-install.ts +9 -0
  114. package/src/cli/check-theme.ts +1 -1
  115. package/src/cli/doctor-upgrade.ts +117 -72
  116. package/src/cli/doctor.ts +3 -3
  117. package/src/cli/index.ts +15 -70
  118. package/src/cli/provider-tags.ts +38 -0
  119. package/src/cli/render-imports.ts +104 -0
  120. package/src/cli/router-wiring.ts +23 -0
  121. package/src/cli/source-text.ts +39 -0
  122. package/src/cli/sync.ts +28 -22
  123. package/src/commands/command-stash.ts +44 -0
  124. package/src/commands/define-commands.ts +10 -17
  125. package/src/commands/define-overlays.ts +40 -68
  126. package/src/commands/projectors.ts +1 -1
  127. package/src/guard/fonts-hint.ts +2 -0
  128. package/src/guard/index.ts +2 -2
  129. package/src/index.ts +4 -2
  130. package/src/provider/create-router.tsx +103 -39
  131. package/src/provider/hotkeys.ts +14 -22
  132. package/src/provider/index.tsx +55 -61
  133. package/src/provider/modals-mount.tsx +66 -0
  134. package/src/provider/notifier.ts +52 -0
  135. package/src/provider/route-transition.ts +1 -1
  136. package/src/provider/slots.ts +59 -0
  137. package/src/provider/spotlight-actions.tsx +3 -4
  138. package/src/provider/spotlight-mount.tsx +33 -0
  139. package/src/query-client.ts +20 -78
  140. package/src/router-tanstack/nav-stash.ts +41 -0
  141. package/src/router-tanstack/nav.ts +11 -31
  142. package/src/router-tanstack/search-store-warnings.ts +120 -0
  143. package/src/router-tanstack/search-store.ts +200 -206
  144. package/src/router-tanstack/use-nav.ts +1 -1
  145. package/src/surfaces.ts +1 -1
  146. package/src/telemetry.ts +71 -13
  147. package/src/theme/__snapshots__/plain-theme.test.ts.snap +2354 -0
  148. package/src/theme/ctl-theme.tsx +20 -19
  149. package/src/theme/extend.ts +18 -0
  150. package/src/theme/index.ts +50 -49
  151. package/src/unwrap.ts +44 -0
@@ -1,7 +1,7 @@
1
1
  /**
2
- * `createBasaltRouter` — the router + QueryClient wiring (V2-SPEC § 2). One `QueryClient` per call
3
- * (so an SSR entry gets one per request), carried on `context.queryClient`, plus the router
4
- * defaults basalt owns: intent preloading with Query-owned freshness, scroll restoration, the
2
+ * `basaltRouterOptions` / `createBasaltRouter` — the router + QueryClient wiring (V2-SPEC § 2). One
3
+ * `QueryClient` per call (so an SSR entry gets one per request), carried on `context.queryClient`,
4
+ * plus the router defaults basalt owns: intent preloading with Query-owned freshness, scroll restoration, the
5
5
  * pending / error / not-found components, and the route view transition (direction from the
6
6
  * `BasaltShell` nav order, V2-SPEC § 5).
7
7
  */
@@ -11,7 +11,7 @@ import { Router, createRouter } from '@tanstack/react-router'
11
11
  import type { AnyRoute, ErrorComponentProps, RouterHistory } from '@tanstack/react-router'
12
12
  import { toErrorMessage } from '../common/errors'
13
13
  import { makeQueryClient } from '../query-client'
14
- import { errorName, now, routerTelemetry } from '../telemetry'
14
+ import type { RouterHook } from '../telemetry'
15
15
  import {
16
16
  guardViewTransitionRejections,
17
17
  routeViewTransition,
@@ -21,6 +21,8 @@ import {
21
21
  /** The root route's context: `createRootRouteWithContext<BasaltRouterContext>()`. */
22
22
  export type BasaltRouterContext = {
23
23
  queryClient: QueryClient
24
+ /** Set by `basaltRouterOptions`; the mounted provider points `onRouteError` at its emitter. */
25
+ __basalt?: RouterHook
24
26
  }
25
27
 
26
28
  type BasaltRouterBase<TRouteTree extends AnyRoute> = Router<
@@ -80,36 +82,69 @@ function NotFoundComponent() {
80
82
  )
81
83
  }
82
84
 
85
+ /** The options `createBasaltRouter` owns. Each is `never` on it: basalt's, not a consumer knob. */
86
+ type ManagedKeys = Exclude<keyof BasaltRouterOptions, 'context'>
87
+
88
+ /** `queryClient` and `__basalt` are basalt's: a consumer's would be replaced, so the type rejects them. */
89
+ type ExtraContext = { queryClient?: never; __basalt?: never }
90
+ type NoContext = Record<never, never>
91
+
92
+ type RouterOptionsInput<TContext extends object> = {
93
+ /** Context beyond `queryClient`; the root route's context type extends `BasaltRouterContext`. */
94
+ context?: (TContext & ExtraContext) | undefined
95
+ /** Merged over basalt's QueryClient defaults (`staleTime` 30 s, `gcTime` 5 min, `retry` twice, never a 4xx but 408/425/429, no refetch on focus). */
96
+ query?: QueryClientConfig | undefined
97
+ }
98
+
99
+ /** What `basaltRouterOptions` returns: the router options basalt owns, plus the context. */
100
+ export type BasaltRouterOptions<TContext extends object = NoContext> = {
101
+ context: TContext & BasaltRouterContext
102
+ defaultPreload: 'intent'
103
+ defaultPreloadStaleTime: number
104
+ scrollRestoration: boolean
105
+ /** Route transitions are basalt's (V2-SPEC § 5): the router's own would double them. */
106
+ defaultViewTransition: typeof routeViewTransition | false
107
+ defaultPendingComponent: typeof PendingComponent
108
+ defaultErrorComponent: typeof ErrorComponent
109
+ defaultNotFoundComponent: typeof NotFoundComponent
110
+ defaultOnCatch: (error: unknown) => void
111
+ }
112
+
83
113
  /**
114
+ * Everything `createBasaltRouter` sets, for a router the app builds itself (TanStack Start's
115
+ * `getRouter()`): spread it into `createRouter`, and the provider mounted inside gets `route.error`
116
+ * telemetry, intent preloading, the route transition and the default pending/error/not-found UI.
117
+ * A `TContext` with required keys makes `context` required. Spread it LAST: the keys are basalt's.
84
118
  * Side effect, once per document: wraps `document.startViewTransition` so a skipped route
85
119
  * transition (`AbortError`) never becomes an unhandled rejection (`guardViewTransitionRejections`).
86
- * Nothing else global is touched.
87
120
  *
88
121
  * @example
89
- * const router = createBasaltRouter({ routeTree })
90
- * declare module '@tanstack/react-router' {
91
- * interface Register { router: typeof router }
92
- * }
93
- * // extra context (argo's auth) extends BasaltRouterContext:
94
- * const router = createBasaltRouter({ routeTree, context: { auth }, query: { queryCache } })
122
+ * export const getRouter = () => createRouter({ routeTree, ...basaltRouterOptions() })
95
123
  */
96
- export function createBasaltRouter<
97
- TRouteTree extends AnyRoute,
98
- TContext extends object = Record<never, never>,
99
- >(options: {
100
- routeTree: TRouteTree
101
- /** Context beyond `queryClient`; the root route's context type extends `BasaltRouterContext`. */
102
- context?: TContext
103
- /** Merged over basalt's QueryClient defaults (`staleTime` 30 s, `gcTime` 5 min, `retry` 2, no refetch on focus). */
104
- query?: QueryClientConfig
105
- /** Route transitions are basalt's (V2-SPEC § 5): the router's would double them. */
106
- defaultViewTransition?: never
107
- }): BasaltRouter<TRouteTree> {
124
+ export function basaltRouterOptions(options?: RouterOptionsInput<NoContext>): BasaltRouterOptions
125
+ export function basaltRouterOptions<TContext extends object>(
126
+ options: RouterOptionsInput<TContext> & { context: TContext & ExtraContext },
127
+ ): BasaltRouterOptions<TContext>
128
+ export function basaltRouterOptions<TContext extends object>(
129
+ options: RouterOptionsInput<TContext> = {},
130
+ ): BasaltRouterOptions<TContext> {
131
+ return buildRouterOptions(options)
132
+ }
133
+
134
+ function buildRouterOptions<TContext extends object>(
135
+ options: RouterOptionsInput<TContext>,
136
+ ): BasaltRouterOptions<TContext> {
108
137
  guardViewTransitionRejections()
109
- const queryClient = makeQueryClient(options.query)
110
- const router: BasaltRouterBase<TRouteTree> = createRouter({
111
- routeTree: options.routeTree,
112
- context: { ...options.context, queryClient },
138
+ const hook: RouterHook = {}
139
+ // The overloads of `basaltRouterOptions` and `createBasaltRouter` make `context` present whenever
140
+ // `TContext` has required keys, so the spread is the whole `TContext`: the one cast, here.
141
+ const context = {
142
+ ...options.context,
143
+ queryClient: makeQueryClient(options.query),
144
+ __basalt: hook,
145
+ } as TContext & BasaltRouterContext
146
+ return {
147
+ context,
113
148
  defaultPreload: 'intent',
114
149
  // Query owns freshness: a preload must not be cached a second time by the router.
115
150
  defaultPreloadStaleTime: 0,
@@ -120,19 +155,48 @@ export function createBasaltRouter<
120
155
  defaultPendingComponent: PendingComponent,
121
156
  defaultErrorComponent: ErrorComponent,
122
157
  defaultNotFoundComponent: NotFoundComponent,
123
- defaultOnCatch: (error: unknown) => {
124
- if (process.env.NODE_ENV !== 'production') console.error('[basalt] route error', error)
125
- routerTelemetry(router)({
126
- type: 'route.error',
127
- failed: true,
128
- start: now(),
129
- attributes: {
130
- 'basalt.route.id': router.state.matches.at(-1)?.routeId ?? 'unknown',
131
- 'exception.type': errorName(error),
132
- 'basalt.error.kind': 'route',
133
- },
134
- })
158
+ defaultOnCatch: (error) => {
159
+ // Unbound (before the provider's first effect): the console is the only report, in every env.
160
+ if (process.env.NODE_ENV !== 'production' || !hook.onRouteError)
161
+ console.error('[basalt] route error', error)
162
+ hook.onRouteError?.(error)
135
163
  },
164
+ }
165
+ }
166
+
167
+ type CreateRouterInput<TRouteTree extends AnyRoute> = {
168
+ routeTree: TRouteTree
169
+ history?: RouterHistory
170
+ basepath?: string
171
+ } & { [K in ManagedKeys]?: never }
172
+
173
+ /**
174
+ * @example
175
+ * const router = createBasaltRouter({ routeTree })
176
+ * declare module '@tanstack/react-router' {
177
+ * interface Register { router: typeof router }
178
+ * }
179
+ * // extra context (argo's auth) extends BasaltRouterContext:
180
+ * const router = createBasaltRouter({ routeTree, context: { auth }, query: { queryCache } })
181
+ */
182
+ export function createBasaltRouter<TRouteTree extends AnyRoute>(
183
+ options: CreateRouterInput<TRouteTree> & RouterOptionsInput<NoContext>,
184
+ ): BasaltRouter<TRouteTree>
185
+ export function createBasaltRouter<TRouteTree extends AnyRoute, TContext extends object>(
186
+ options: CreateRouterInput<TRouteTree> &
187
+ RouterOptionsInput<TContext> & { context: TContext & ExtraContext },
188
+ ): BasaltRouter<TRouteTree>
189
+ export function createBasaltRouter<TRouteTree extends AnyRoute, TContext extends object>({
190
+ routeTree,
191
+ context,
192
+ query,
193
+ ...passthrough
194
+ }: CreateRouterInput<TRouteTree> & RouterOptionsInput<TContext>): BasaltRouter<TRouteTree> {
195
+ const router: BasaltRouterBase<TRouteTree> = createRouter({
196
+ ...passthrough,
197
+ routeTree,
198
+ ...buildRouterOptions<TContext>({ context, query }),
136
199
  })
200
+ // The brand is type-level only (see `BasaltRouter`), so the one cast adds nothing at runtime.
137
201
  return router as BasaltRouter<TRouteTree>
138
202
  }
@@ -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
  }
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * BasaltProvider — the one provider tree (V2-SPEC § 2): `MantineProvider` with the Basalt theme and
3
3
  * resolver, the `--vx-*` palette `<style>`, and then
4
- * `QueryClientProvider > ModalsProvider > RouterProvider` with `Notifications` and `Spotlight` as
5
- * siblings. The consumer writes the route tree, the nav and the registries.
4
+ * `QueryClientProvider > RouterProvider` with `Notifications` as a sibling. Spotlight, the modals
5
+ * layer and the command hotkeys are slots: each mounts as a sibling only once the app's `defineNav` /
6
+ * `defineCommands` / `defineOverlays` call registered it (`./slots`), so an app defining none ships none
7
+ * of their runtimes. The consumer writes the route tree, the nav and the registries.
6
8
  *
7
9
  * It also owns the root error boundary, the `window` error listeners and the telemetry seam
8
10
  * (V2-SPEC § 7), the command hotkeys and Spotlight actions, and — in dev only — the dev dock.
@@ -12,15 +14,12 @@
12
14
  */
13
15
  import { MantineProvider, useMantineColorScheme, useMantineTheme } from '@mantine/core'
14
16
  import type { MantineProviderProps } from '@mantine/core'
15
- import { ModalsProvider } from '@mantine/modals'
16
17
  import { Notifications } from '@mantine/notifications'
17
- import { Spotlight } from '@mantine/spotlight'
18
- import type { SpotlightActionData } from '@mantine/spotlight'
19
18
  import { QueryClientProvider } from '@tanstack/react-query'
20
19
  import type { QueryClient } from '@tanstack/react-query'
21
20
  import { RouterProvider, useRouter } from '@tanstack/react-router'
22
21
  import type { AnyRouter } from '@tanstack/react-router'
23
- import { Component, Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react'
22
+ import { Component, Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react'
24
23
  import type { ErrorInfo, ReactNode } from 'react'
25
24
  import fallbackClasses from './error-fallback.module.css'
26
25
  import { cssVariablesResolver } from '../theme'
@@ -30,7 +29,6 @@ import type { BuildPaletteOpts } from '../tokens/core'
30
29
  import { isDefaultDeriveConfig } from '../tokens/derive'
31
30
  import { buildPaletteData } from '../tokens/palette'
32
31
  import { useMediaQuery } from '../common/use-media-query'
33
- import { registerModalsProvider } from '../commands/define-overlays'
34
32
  import { registerColorSchemeSetter } from '../commands/shell-bridge'
35
33
  import { useIsomorphicLayoutEffect } from '../common/isomorphic-layout-effect'
36
34
  import { PageTitle } from '../shell/page-title'
@@ -38,17 +36,19 @@ import { SizeClassHintContext } from '../shell/use-size-class'
38
36
  import type { SizeClass } from '../shell/use-size-class'
39
37
  import {
40
38
  TelemetryContext,
41
- bindRouterTelemetry,
39
+ bindRouteError,
42
40
  createLiveEmitter,
41
+ devConsoleSink,
43
42
  errorName,
43
+ groupingId,
44
44
  now,
45
45
  } from '../telemetry'
46
46
  import type { Telemetry } from '../telemetry'
47
47
  import type { BasaltDevDockTool } from '../dev-dock'
48
48
  import type { BasaltRouter, BasaltRouterContext } from './create-router'
49
- import { useRegistryHotkeys } from './hotkeys'
50
- import type { FlatNavItem } from '../router-tanstack/nav'
51
- import { buildSpotlightActions } from './spotlight-actions'
49
+ import type { FlatNavItem } from '../router-tanstack/nav-stash'
50
+ import { trackProvider, useSlots } from './slots'
51
+ import type { SlotProps } from './slots'
52
52
 
53
53
  type BasaltProviderCommonProps = {
54
54
  /** Theme override merged onto the Basalt base. Defaults to `createBasaltTheme()`. */
@@ -56,7 +56,7 @@ type BasaltProviderCommonProps = {
56
56
  /**
57
57
  * Typed events (V2-SPEC § 7) — navigations, route/query/mutation/render/window errors. Called
58
58
  * synchronously and wrapped in `try/catch`, so a throwing sink never breaks a render. Events carry
59
- * ids, hashes, counts and durations only; no sink, no events.
59
+ * ids, hashes, counts and durations only. No sink, no events in production; in development an unset sink logs query and mutation failures to the console.
60
60
  */
61
61
  telemetry?: Telemetry
62
62
  /** The root error boundary's UI. Unset → a minimal page with a reload button; `null` renders nothing. */
@@ -91,8 +91,10 @@ type BasaltProviderCommonProps = {
91
91
  */
92
92
  navCommandLabel?: (item: FlatNavItem) => string
93
93
  /**
94
- * Mount Basalt's `<Spotlight>` (Cmd+K) with the generated nav + command actions. Default `true`.
95
- * Set `false` when the app owns its own palette: neither the component nor its action wiring mounts.
94
+ * Mount Basalt's `<Spotlight>` (Cmd+K) with the generated nav + command actions. Default `true`, and
95
+ * it mounts only when the app calls `defineNav` or `defineCommands` (nav entries and commands are
96
+ * what it lists). Set `false` when the app owns its own palette: neither the component nor its
97
+ * action wiring mounts.
96
98
  */
97
99
  spotlight?: boolean
98
100
  } & Omit<MantineProviderProps, 'children' | 'theme' | 'defaultColorScheme' | 'cssVariablesResolver'>
@@ -101,7 +103,7 @@ type BasaltProviderCommonProps = {
101
103
  * Two modes, never both: pass a `createBasaltRouter` `router` and the provider mounts it, or pass
102
104
  * `children` and render the provider INSIDE a router the app does not own (around the `<Outlet />`
103
105
  * of TanStack Start's root route component) — the router then comes from `useRouter()` and must carry
104
- * `context.queryClient` (its `getRouter()` builds the same context `createBasaltRouter` does).
106
+ * `context.queryClient`: spread `basaltRouterOptions()` into its `createRouter` (Start's `getRouter()`).
105
107
  */
106
108
  export type BasaltProviderProps = BasaltProviderCommonProps &
107
109
  (
@@ -354,7 +356,20 @@ function useWindowErrors(emit: Telemetry): void {
354
356
  /** Router navigations and the QueryClient's caches → `route.*`, `query.error`, `mutation.error`. */
355
357
  function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetry): void {
356
358
  useEffect(() => {
357
- const unbind = bindRouterTelemetry(router, emit)
359
+ // `basaltRouterOptions`' `defaultOnCatch` reports to the handler bound here.
360
+ const routeId = (): string => router.state.matches.at(-1)?.routeId ?? 'unknown'
361
+ const onRouteError = (error: unknown): void =>
362
+ emit({
363
+ type: 'route.error',
364
+ failed: true,
365
+ start: now(),
366
+ attributes: {
367
+ 'basalt.route.id': routeId(),
368
+ 'exception.type': errorName(error),
369
+ 'basalt.error.kind': 'route',
370
+ },
371
+ })
372
+ const unbind = bindRouteError(router, onRouteError)
358
373
 
359
374
  // Keyed by the target href: a newer navigation overwrites, and a resolve for any other target
360
375
  // (a superseded or redirected navigation) is dropped rather than paired with the wrong start.
@@ -372,7 +387,7 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
372
387
  start,
373
388
  duration: now() - start,
374
389
  attributes: {
375
- 'basalt.route.id': router.state.matches.at(-1)?.routeId ?? 'unknown',
390
+ 'basalt.route.id': routeId(),
376
391
  'basalt.route.from': from,
377
392
  'url.path': ev.toLocation.pathname,
378
393
  },
@@ -386,7 +401,7 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
386
401
  failed: true,
387
402
  start: now(),
388
403
  attributes: {
389
- 'basalt.query.hash': ev.query.queryHash,
404
+ 'basalt.query.hash': groupingId(ev.query.queryHash),
390
405
  'basalt.query.failure_count': ev.query.state.fetchFailureCount,
391
406
  'exception.type': errorName(ev.action.error),
392
407
  'basalt.error.kind': 'query',
@@ -400,7 +415,9 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
400
415
  failed: true,
401
416
  start: now(),
402
417
  attributes: {
403
- 'basalt.mutation.key': JSON.stringify(ev.mutation.options.mutationKey ?? null),
418
+ 'basalt.mutation.key': groupingId(
419
+ JSON.stringify(ev.mutation.options.mutationKey ?? null),
420
+ ),
404
421
  'exception.type': errorName(ev.action.error),
405
422
  'basalt.error.kind': 'mutation',
406
423
  },
@@ -472,37 +489,29 @@ export function BasaltProvider({
472
489
  useHostAttribute()
473
490
 
474
491
  // The sink is read through a ref, so an inline `telemetry` function does not re-subscribe.
475
- const sinkRef = useRef(telemetry)
492
+ const sink = telemetry ?? (process.env.NODE_ENV === 'production' ? undefined : devConsoleSink)
493
+ const sinkRef = useRef(sink)
476
494
  useEffect(() => {
477
- sinkRef.current = telemetry
495
+ sinkRef.current = sink
478
496
  })
479
497
  const emit = useMemo(() => createLiveEmitter(() => sinkRef.current), [])
480
498
  useWindowErrors(emit)
481
- useRegistryHotkeys()
482
- // `overlays.confirm` is an imperative call; this tells it a `ModalsProvider` is live.
483
- useEffect(() => registerModalsProvider(), [])
499
+ const slots = useSlots()
500
+ // Tells the imperative overlay calls a provider is mounted to commit a slot they register late.
501
+ useEffect(trackProvider, [])
484
502
 
485
503
  const router = useEffectiveRouter(mountedRouter)
486
504
  const client = readQueryClient(router)
487
505
  useDataTelemetry(router, client, emit)
488
506
 
489
507
  const [devTool, setDevTool] = useState<BasaltDevDockTool | null>(null)
490
- // Rebuilt on mount and again at every open, so a command's `when()` is read when the palette
491
- // appears, not frozen at mount — and `detectMac` (inside the builder) never runs during render.
492
- const [actions, setActions] = useState<SpotlightActionData[]>([])
493
- const refreshActions = useCallback(
494
- () => setActions(buildSpotlightActions(router, setDevTool, navCommandLabel)),
495
- [router, navCommandLabel],
496
- )
497
- useEffect(() => {
498
- if (spotlight) refreshActions()
499
- }, [spotlight, refreshActions])
500
-
501
508
  // `createBasaltTheme(theme)` — plus, when the theme lab's "Apply" switch is on, the delta of its
502
509
  // persisted config, so the dev tool moves the numeric `defaultProps` and `theme.spacing` a `<style>`
503
510
  // tag cannot reach. No lab override (every production app) → the consumer theme merged onto the
504
511
  // Basalt base and nothing else. See `./lab-theme.ts`.
505
512
  const resolvedTheme = useLabTheme(theme)
513
+ const { modals: Modals, hotkeys: Hotkeys, spotlight: Spotlight } = slots
514
+ const slotProps: SlotProps = { router, navCommandLabel, openDevTool: setDevTool }
506
515
 
507
516
  return (
508
517
  // `...rest` spreads FIRST so a consumer's `MantineProviderProps` can never shadow the three
@@ -519,34 +528,19 @@ export function BasaltProvider({
519
528
  <TelemetryContext.Provider value={emit}>
520
529
  <SizeClassHintContext.Provider value={sizeClassHint}>
521
530
  <QueryClientProvider client={client}>
522
- {/* ModalsProvider WRAPS the router, so `useModals()` / `openContextModal` have real context. */}
523
- <ModalsProvider>
524
- {mountedRouter === undefined ? (
525
- children
526
- ) : (
527
- <RouterProvider router={mountedRouter} />
528
- )}
529
- {/* `LazyDevDock` is `null` in production (module-scope gate above), so nothing mounts. */}
530
- {LazyDevDock !== null && (
531
- <Suspense fallback={null}>
532
- <LazyDevDock
533
- tool={devTool}
534
- onClose={() => setDevTool(null)}
535
- router={router}
536
- />
537
- </Suspense>
538
- )}
539
- </ModalsProvider>
531
+ {mountedRouter === undefined ? children : <RouterProvider router={mountedRouter} />}
532
+ {/* A sibling, not a wrapper: a late `defineOverlays` mounts it without re-parenting the app. */}
533
+ {Modals !== undefined && <Modals {...slotProps} />}
534
+ {/* `LazyDevDock` is `null` in production (module-scope gate above), so nothing mounts. */}
535
+ {LazyDevDock !== null && (
536
+ <Suspense fallback={null}>
537
+ <LazyDevDock tool={devTool} onClose={() => setDevTool(null)} router={router} />
538
+ </Suspense>
539
+ )}
540
540
  </QueryClientProvider>
541
541
  <Notifications position="bottom-right" autoClose={4000} limit={5} />
542
- {spotlight && (
543
- <Spotlight
544
- actions={actions}
545
- onSpotlightOpen={refreshActions}
546
- shortcut="mod + K"
547
- maxHeight={420}
548
- />
549
- )}
542
+ {Hotkeys !== undefined && <Hotkeys {...slotProps} />}
543
+ {spotlight && Spotlight !== undefined && <Spotlight {...slotProps} />}
550
544
  </SizeClassHintContext.Provider>
551
545
  </TelemetryContext.Provider>
552
546
  </BasaltBridge>
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The modals mount: `ModalsProvider` as a SIBLING of the router, plus the live-provider declaration
3
+ * the imperative overlay calls wait on. Registered by `defineOverlays` / `overlays.*` (never imported
4
+ * by the provider), so an app using none ships none of `@mantine/modals`.
5
+ */
6
+ import { ModalsProvider } from '@mantine/modals'
7
+ import { useEffect } from 'react'
8
+ import { createLiveCounter } from './notifier'
9
+ import { hasMountedProvider, registerSlot } from './slots'
10
+
11
+ /**
12
+ * The live `ModalsProvider`s. `@mantine/modals`' imperative API is a window event bus: with nothing
13
+ * subscribed a dialog never appears and a confirm promise never settles, so the overlay calls wait for
14
+ * this to be non-zero.
15
+ */
16
+ const liveProviders = createLiveCounter()
17
+
18
+ /**
19
+ * Internal — `ModalsMount` declares its `ModalsProvider` live for as long as it is mounted and gets
20
+ * back the retraction. There is no way to detect the provider from outside React (its context is only
21
+ * readable through `useModals()`, and the overlay calls are imperative), so the registration is explicit.
22
+ * Exported for the confirm tests, which mount their own host.
23
+ */
24
+ export const registerModalsProvider = liveProviders.acquire
25
+
26
+ /** How long a call waits for a mounted `BasaltProvider` to commit the modals mount it asked for. */
27
+ const COMMIT_WAIT_MS = 5000
28
+ /** With no `BasaltProvider` mounted nothing will commit it; this is only the grace for one mounting now. */
29
+ const NO_PROVIDER_WAIT_MS = 500
30
+
31
+ /** Resolves `true` once a `ModalsProvider` is live, `false` after `timeoutMs` without one. */
32
+ function whenModalsLive(timeoutMs: number): Promise<boolean> {
33
+ if (liveProviders.count() > 0) return Promise.resolve(true)
34
+ return new Promise((resolve) => {
35
+ let timer: ReturnType<typeof setTimeout> | undefined
36
+ let unsubscribe: (() => void) | undefined
37
+ const finish = (isLive: boolean): void => {
38
+ clearTimeout(timer)
39
+ unsubscribe?.()
40
+ resolve(isLive)
41
+ }
42
+ timer = setTimeout(() => finish(false), timeoutMs)
43
+ unsubscribe = liveProviders.subscribe(() => {
44
+ if (liveProviders.count() > 0) finish(true)
45
+ })
46
+ })
47
+ }
48
+
49
+ /** @internal — put the modals mount in the provider's slots; synchronous, nothing awaited. */
50
+ export function registerModalsMount(): void {
51
+ registerSlot('modals', ModalsMount)
52
+ }
53
+
54
+ /**
55
+ * @internal — register the mount, then wait for it to go live: up to 5 s when a `BasaltProvider` is
56
+ * mounted (it commits the slot), 500 ms when none is. `false` means no dialog layer will serve the call.
57
+ */
58
+ export function ensureModalsMount(): Promise<boolean> {
59
+ registerModalsMount()
60
+ return whenModalsLive(hasMountedProvider() ? COMMIT_WAIT_MS : NO_PROVIDER_WAIT_MS)
61
+ }
62
+
63
+ export function ModalsMount() {
64
+ useEffect(() => registerModalsProvider(), [])
65
+ return <ModalsProvider>{null}</ModalsProvider>
66
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The one subscribe/notify pair behind every module-level store here (slots, the command stash, the
3
+ * modals-live waiters) — shaped for `useSyncExternalStore`. A leaf: no React, nothing at import.
4
+ */
5
+ export type Notifier = { subscribe: (listener: () => void) => () => void; notify: () => void }
6
+
7
+ export function createNotifier(): Notifier {
8
+ const listeners = new Set<() => void>()
9
+ return {
10
+ subscribe(listener) {
11
+ listeners.add(listener)
12
+ return () => void listeners.delete(listener)
13
+ },
14
+ // Deleting from a Set mid-iteration is safe, so a listener may unsubscribe itself here.
15
+ notify() {
16
+ for (const listener of listeners) listener()
17
+ },
18
+ }
19
+ }
20
+
21
+ export type LiveCounter = {
22
+ count: () => number
23
+ /** Count one more live thing, notify subscribers, and return its retraction (idempotent). */
24
+ acquire: () => () => void
25
+ subscribe: Notifier['subscribe']
26
+ }
27
+
28
+ /**
29
+ * A COUNTER of live things — not a flag: two overlapping mounts are normal (a route swap mounts the
30
+ * next one before unmounting the previous), and a last-write-wins boolean would report the OLD one's
31
+ * teardown as "none live" while the new one serves.
32
+ */
33
+ export function createLiveCounter(): LiveCounter {
34
+ let live = 0
35
+ const changes = createNotifier()
36
+ return {
37
+ count: () => live,
38
+ subscribe: changes.subscribe,
39
+ acquire() {
40
+ live++
41
+ changes.notify()
42
+ let released = false
43
+ return () => {
44
+ // A cleanup React runs twice (StrictMode remount) must not drive the count below the real one.
45
+ if (released) return
46
+ released = true
47
+ live--
48
+ changes.notify()
49
+ }
50
+ },
51
+ }
52
+ }
@@ -8,7 +8,7 @@
8
8
  * so `ready` and `finished` are dropped on the floor.
9
9
  */
10
10
  import type { AnyRouter } from '@tanstack/react-router'
11
- import { flattenNav, getActiveNav } from '../router-tanstack/nav'
11
+ import { flattenNav, getActiveNav } from '../router-tanstack/nav-stash'
12
12
 
13
13
  /** The three `:active-view-transition-type()` names `styles.css` animates. Namespaced: a consumer's own cannot collide. */
14
14
  export const ROUTE_TRANSITION_TYPES = {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The provider's feature slots — a tiny leaf store (React types only, no Mantine, no peers, nothing
3
+ * touched at import so it is SSR-safe). "The bundle follows the definitions": a feature's runtime
4
+ * (hotkeys, Spotlight, modals) enters the import graph only through the `define*` call that needs
5
+ * it, and that call registers its mount here. `BasaltProvider` reads the store with
6
+ * `useSyncExternalStore`, so a registration made after first render (a `define*` call inside a lazily
7
+ * loaded route) mounts a sibling instead of re-parenting the app tree.
8
+ */
9
+ import { useSyncExternalStore } from 'react'
10
+ import type { ComponentType } from 'react'
11
+ import type { AnyRouter } from '@tanstack/react-router'
12
+ import type { BasaltDevDockTool } from '../dev-dock'
13
+ import type { FlatNavItem } from '../router-tanstack/nav-stash'
14
+ import { createLiveCounter, createNotifier } from './notifier'
15
+
16
+ /** What the provider hands every mount; a mount that needs none of it ignores it. */
17
+ export type SlotProps = {
18
+ router: AnyRouter
19
+ navCommandLabel: ((item: FlatNavItem) => string) | undefined
20
+ openDevTool: (tool: BasaltDevDockTool) => void
21
+ }
22
+
23
+ export type SlotName = 'hotkeys' | 'spotlight' | 'modals'
24
+ export type Slots = { readonly [K in SlotName]?: ComponentType<SlotProps> }
25
+
26
+ let slots: Slots = {}
27
+ const store = createNotifier()
28
+
29
+ /** @internal — idempotent: re-registering the same component is a no-op (no notify, no new snapshot). */
30
+ export function registerSlot(name: SlotName, component: ComponentType<SlotProps>): void {
31
+ if (slots[name] === component) return
32
+ slots = { ...slots, [name]: component }
33
+ store.notify()
34
+ }
35
+
36
+ /** @internal — test isolation only. */
37
+ export function resetSlots(): void {
38
+ slots = {}
39
+ store.notify()
40
+ }
41
+
42
+ const getSlots = (): Slots => slots
43
+
44
+ /** @internal — the registered mounts, read by `BasaltProvider`. */
45
+ export function useSlots(): Slots {
46
+ return useSyncExternalStore(store.subscribe, getSlots, getSlots)
47
+ }
48
+
49
+ // ── Mounted providers ─────────────────────────────────────────────────────────
50
+
51
+ const providers = createLiveCounter()
52
+
53
+ /** @internal — `BasaltProvider` declares itself mounted; returns the retraction. */
54
+ export const trackProvider = providers.acquire
55
+
56
+ /** @internal — whether a `BasaltProvider` is mounted to commit a slot registered right now. */
57
+ export function hasMountedProvider(): boolean {
58
+ return providers.count() > 0
59
+ }