basalt-ui 2.8.0 → 2.9.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 (179) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +209 -189
  3. package/MIGRATING.md +98 -28
  4. package/README.md +7 -8
  5. package/agent/rules/basalt-controls.md +1 -1
  6. package/agent/rules/basalt-state.md +1 -1
  7. package/agent/skills/basalt-design/SKILL.md +1 -1
  8. package/agent/templates/AGENTS-block.md.tpl +2 -2
  9. package/configs/oxlint-plugin.js +25 -68
  10. package/configs/oxlint-plugin.test.ts +19 -27
  11. package/dist/charts/BandStrip.d.ts +1 -1
  12. package/dist/charts/BandStrip.d.ts.map +1 -1
  13. package/dist/charts/BandStrip.js +1 -10
  14. package/dist/charts/MirroredBars.d.ts.map +1 -1
  15. package/dist/charts/MirroredBars.js +2 -9
  16. package/dist/charts/band-fold.d.ts +15 -0
  17. package/dist/charts/band-fold.d.ts.map +1 -0
  18. package/dist/charts/band-fold.js +19 -0
  19. package/dist/charts/index.d.ts +1 -0
  20. package/dist/charts/index.d.ts.map +1 -1
  21. package/dist/charts/index.js +3 -1
  22. package/dist/cli/audit-allows.d.ts.map +1 -1
  23. package/dist/cli/audit-allows.js +1 -1
  24. package/dist/cli/check-theme.d.ts.map +1 -1
  25. package/dist/cli/check-theme.js +4 -1
  26. package/dist/cli/config.d.ts +4 -4
  27. package/dist/cli/doctor-upgrade.d.ts +5 -4
  28. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  29. package/dist/cli/doctor-upgrade.js +23 -99
  30. package/dist/cli/doctor.d.ts +2 -1
  31. package/dist/cli/doctor.d.ts.map +1 -1
  32. package/dist/cli/doctor.js +23 -25
  33. package/dist/cli/help.d.ts.map +1 -1
  34. package/dist/cli/help.js +2 -3
  35. package/dist/cli/index.d.ts +15 -6
  36. package/dist/cli/index.d.ts.map +1 -1
  37. package/dist/cli/index.js +16 -27
  38. package/dist/cli/init.d.ts.map +1 -1
  39. package/dist/cli/init.js +9 -6
  40. package/dist/cli/install-root.d.ts +10 -0
  41. package/dist/cli/install-root.d.ts.map +1 -0
  42. package/dist/cli/install-root.js +32 -0
  43. package/dist/cli/router-wiring.d.ts +37 -0
  44. package/dist/cli/router-wiring.d.ts.map +1 -0
  45. package/dist/cli/router-wiring.js +116 -0
  46. package/dist/cli/source-text.d.ts +12 -0
  47. package/dist/cli/source-text.d.ts.map +1 -0
  48. package/dist/cli/source-text.js +46 -0
  49. package/dist/cli/sync.d.ts +0 -2
  50. package/dist/cli/sync.d.ts.map +1 -1
  51. package/dist/cli/sync.js +23 -21
  52. package/dist/cli/tokens-css.d.ts.map +1 -1
  53. package/dist/cli/tokens-css.js +1 -6
  54. package/dist/common/errors.d.ts +1 -6
  55. package/dist/common/errors.d.ts.map +1 -1
  56. package/dist/common/errors.js +0 -7
  57. package/dist/common/index.d.ts +1 -1
  58. package/dist/common/index.d.ts.map +1 -1
  59. package/dist/common/index.js +1 -9
  60. package/dist/common/props.d.ts +2 -2
  61. package/dist/common/vx-family.d.ts +1 -1
  62. package/dist/content/code-block.d.ts.map +1 -1
  63. package/dist/content/code-block.js +36 -27
  64. package/dist/content/code-block.module.css +19 -1
  65. package/dist/content/mermaid-sanitize.d.ts +15 -0
  66. package/dist/content/mermaid-sanitize.d.ts.map +1 -0
  67. package/dist/content/mermaid-sanitize.js +28 -0
  68. package/dist/content/mermaid.d.ts +6 -0
  69. package/dist/content/mermaid.d.ts.map +1 -1
  70. package/dist/content/mermaid.js +3 -1
  71. package/dist/content/toc-click-pin.d.ts +45 -0
  72. package/dist/content/toc-click-pin.d.ts.map +1 -0
  73. package/dist/content/toc-click-pin.js +111 -0
  74. package/dist/content/toc-spy.d.ts +25 -0
  75. package/dist/content/toc-spy.d.ts.map +1 -0
  76. package/dist/content/toc-spy.js +43 -0
  77. package/dist/content/toc.d.ts +1 -4
  78. package/dist/content/toc.d.ts.map +1 -1
  79. package/dist/content/toc.js +38 -49
  80. package/dist/controls/number-filter.d.ts.map +1 -1
  81. package/dist/controls/number-filter.js +1 -1
  82. package/dist/dashboard/index.d.ts +1 -1
  83. package/dist/dashboard/index.d.ts.map +1 -1
  84. package/dist/dashboard/index.js +1 -3
  85. package/dist/dashboard/section.d.ts +10 -2
  86. package/dist/dashboard/section.d.ts.map +1 -1
  87. package/dist/dashboard/section.js +20 -3
  88. package/dist/dashboard/stat-card.d.ts +2 -8
  89. package/dist/dashboard/stat-card.d.ts.map +1 -1
  90. package/dist/dashboard/stat-card.js +1 -1
  91. package/dist/guard/index.d.ts +13 -9
  92. package/dist/guard/index.d.ts.map +1 -1
  93. package/dist/guard/index.js +74 -37
  94. package/dist/guard/types.d.ts +8 -7
  95. package/dist/guard/types.d.ts.map +1 -1
  96. package/dist/guard/vx-names.d.ts +1 -1
  97. package/dist/guard/vx-names.d.ts.map +1 -1
  98. package/dist/guard/vx-names.js +1 -33
  99. package/dist/index.d.ts +2 -2
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/provider/index.d.ts.map +1 -1
  102. package/dist/provider/index.js +3 -2
  103. package/dist/router-tanstack/search-store.d.ts +1 -11
  104. package/dist/router-tanstack/search-store.d.ts.map +1 -1
  105. package/dist/router-tanstack/search-store.js +1 -2
  106. package/dist/shell/index.d.ts +1 -0
  107. package/dist/shell/index.d.ts.map +1 -1
  108. package/dist/shell/index.js +3 -0
  109. package/dist/shell/nav-types.d.ts +1 -1
  110. package/dist/shell/page-bar.d.ts +6 -0
  111. package/dist/shell/page-bar.d.ts.map +1 -1
  112. package/dist/shell/page-bar.js +12 -2
  113. package/dist/state/fields.d.ts +1 -1
  114. package/dist/state/fields.d.ts.map +1 -1
  115. package/dist/state/fields.js +3 -1
  116. package/dist/surfaces.d.ts +1 -1
  117. package/dist/surfaces.d.ts.map +1 -1
  118. package/dist/surfaces.js +5 -11
  119. package/dist/table/data-table.d.ts +2 -2
  120. package/dist/tokens/core.d.ts +0 -10
  121. package/dist/tokens/core.d.ts.map +1 -1
  122. package/dist/tokens/core.js +6 -44
  123. package/dist/vite-boot.d.ts +25 -0
  124. package/dist/vite-boot.d.ts.map +1 -0
  125. package/dist/vite-boot.js +36 -0
  126. package/dist/vite.d.ts +24 -3
  127. package/dist/vite.d.ts.map +1 -1
  128. package/dist/vite.js +7 -16
  129. package/llms.txt +26 -9
  130. package/package.json +8 -5
  131. package/src/charts/BandStrip.tsx +4 -16
  132. package/src/charts/MirroredBars.tsx +2 -11
  133. package/src/charts/band-fold.ts +26 -0
  134. package/src/charts/index.ts +1 -0
  135. package/src/cli/audit-allows.ts +1 -3
  136. package/src/cli/check-theme.ts +7 -1
  137. package/src/cli/config.ts +4 -4
  138. package/src/cli/doctor-upgrade.ts +29 -145
  139. package/src/cli/doctor.ts +25 -31
  140. package/src/cli/help.ts +1 -4
  141. package/src/cli/index.ts +27 -43
  142. package/src/cli/init.ts +9 -6
  143. package/src/cli/install-root.ts +40 -0
  144. package/src/cli/router-wiring.ts +185 -0
  145. package/src/cli/source-text.ts +62 -0
  146. package/src/cli/sync.ts +26 -22
  147. package/src/cli/tokens-css.ts +0 -5
  148. package/src/common/errors.ts +1 -18
  149. package/src/common/index.ts +1 -8
  150. package/src/common/props.ts +2 -2
  151. package/src/common/vx-family.ts +1 -1
  152. package/src/content/code-block.module.css +19 -1
  153. package/src/content/code-block.tsx +7 -2
  154. package/src/content/mermaid-sanitize.ts +49 -0
  155. package/src/content/mermaid.tsx +3 -2
  156. package/src/content/toc-click-pin.ts +156 -0
  157. package/src/content/toc-spy.ts +61 -0
  158. package/src/content/toc.tsx +47 -95
  159. package/src/controls/form-layout.tsx +1 -1
  160. package/src/controls/number-filter.tsx +6 -1
  161. package/src/dashboard/index.ts +1 -6
  162. package/src/dashboard/section.tsx +39 -8
  163. package/src/dashboard/stat-card.tsx +4 -11
  164. package/src/guard/index.ts +114 -89
  165. package/src/guard/types.ts +8 -7
  166. package/src/guard/vx-names.ts +1 -33
  167. package/src/index.ts +1 -2
  168. package/src/provider/index.tsx +6 -3
  169. package/src/router-tanstack/search-store.ts +2 -14
  170. package/src/shell/index.tsx +2 -0
  171. package/src/shell/nav-types.ts +1 -1
  172. package/src/shell/page-bar.tsx +21 -2
  173. package/src/state/fields.ts +7 -2
  174. package/src/surfaces.ts +5 -11
  175. package/src/table/data-table.tsx +2 -2
  176. package/src/tokens/core.ts +6 -67
  177. package/src/vite-boot.ts +109 -0
  178. package/src/vite.ts +32 -61
  179. package/dist/tokens.css +0 -331
@@ -77,7 +77,13 @@
77
77
  );
78
78
  }
79
79
 
80
- .body :global(pre.shiki) {
80
+ /* Both body states — the highlighted wrapper's `pre.shiki` and the bare fallback `<pre class=body>`
81
+ * — outrank Prose's `.root.article pre` block margin (0,2,1): at a tie, stylesheet order decided
82
+ * whether the inner pre kept 18px, so the fallback was ~36px taller than the highlighted fence and
83
+ * the swap jumped. `.body.body` lifts the fallback to (0,3,0); the outer `.container` margin alone
84
+ * owns the rhythm. */
85
+ .container .body.body,
86
+ .container .body :global(pre.shiki) {
81
87
  margin: 0;
82
88
  padding: 0;
83
89
  background: transparent !important;
@@ -93,6 +99,18 @@ html[data-mantine-color-scheme='light'] .body :global(.shiki span) {
93
99
  color: var(--shiki-light);
94
100
  }
95
101
 
102
+ /* The floating button sits over the body's top-right corner, so the body reserves its box: the
103
+ * first line starts below offset + button height instead of running underneath it on touch (always
104
+ * visible) or on hover. `--code-block-copy-size` mirrors ActionIcon size="sm" (Mantine scopes its
105
+ * own `--ai-size-sm` to the button, out of the body's reach); the layout suite pins the two. */
106
+ .container[data-floating-copy] {
107
+ --code-block-copy-size: calc(1.375rem * var(--mantine-scale, 1));
108
+ }
109
+
110
+ .container[data-floating-copy] .body {
111
+ padding-top: calc(var(--vx-space-code-block-floating-copy-offset) + var(--code-block-copy-size));
112
+ }
113
+
96
114
  /* Floating copy button — shown only when there is no header (no title), revealed on hover/focus. */
97
115
  .floatingCopy {
98
116
  position: absolute;
@@ -88,9 +88,14 @@ export function CodeBlock({
88
88
  }, [html, code])
89
89
 
90
90
  const containerClass = [classes.container, className].filter(Boolean).join(' ')
91
+ const showFloatingCopy = title === undefined && showCopy
91
92
 
92
93
  return (
93
- <div className={containerClass} {...(style !== undefined && { style })}>
94
+ <div
95
+ className={containerClass}
96
+ {...(showFloatingCopy && { 'data-floating-copy': true })}
97
+ {...(style !== undefined && { style })}
98
+ >
94
99
  {title !== undefined && (
95
100
  <div className={classes.header}>
96
101
  <span className={classes.title}>{title}</span>
@@ -116,7 +121,7 @@ export function CodeBlock({
116
121
  <code>{code}</code>
117
122
  </pre>
118
123
  )}
119
- {title === undefined && showCopy && (
124
+ {showFloatingCopy && (
120
125
  <div className={classes.floatingCopy}>
121
126
  <CopyAction value={code} ariaLabel="Copy code" />
122
127
  </div>
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Post-process for beautiful-mermaid's SVG (consumed by `./mermaid`).
3
+ *
4
+ * `buildStyleBlock(font)` treats the font as a family NAME: it emits a Google Fonts `@import` (plus
5
+ * a JetBrains Mono one when `mono` is set) and writes `text { font-family: '<font>', … }`. basalt
6
+ * feeds it `var(--basalt-font-sans)`, so the import is a broken request and the quoted `'var(…)'`
7
+ * is an invalid family. basalt self-hosts its fonts: drop the import, unquote the var().
8
+ *
9
+ * Patterns verified against beautiful-mermaid 1.1.3 (peer range ^1.1.0): the style block is a
10
+ * single `<style>` holding the `@import`s and one `text { font-family }` rule; `font-family`
11
+ * never appears as a presentation attribute. Only `<style>` content is rewritten — a node label
12
+ * that happens to contain the same text is left alone.
13
+ */
14
+
15
+ const STYLE_BLOCK = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi
16
+
17
+ // One `@import` statement, built from fragments. The family URL itself contains `;` (`wght@400;500`,
18
+ // `&amp;`), so each form is bounded by its closing quote / `)` — never by `;` — and never crosses
19
+ // a newline or `}`: a truncated import cannot eat unrelated CSS.
20
+ const HOST = String.raw`(?:https?:)?\/\/fonts\.googleapis\.com`
21
+ const QUOTED_FORM = String.raw`(?:url\(\s*)?(['"])${HOST}[^'"}\n]*\1(?:\s*\))?` // 'url' | url('url') | url("url")
22
+ const URL_FORM = String.raw`url\(\s*${HOST}[^}'"\n]*?\)` // url(url)
23
+ const MEDIA_LIST = String.raw`(?:[ \t]+[^;{}\n]*)?` // `url(…) screen`
24
+ const GOOGLE_FONTS_IMPORT = new RegExp(
25
+ String.raw`@import\s+(?:${QUOTED_FORM}|${URL_FORM})${MEDIA_LIST}[ \t]*;?`,
26
+ 'g',
27
+ )
28
+
29
+ // `font-family: 'var(--x)'` — a value that is exactly a quoted var(). `var(--a, 'fallback')` has a
30
+ // quote inside and `'Inter', var(--x)` does not start with var(, so neither matches.
31
+ const QUOTED_VAR_FONT_FAMILY = /(font-family\s*:\s*)(['"])(var\([^'"]*\))\2/g
32
+
33
+ function sanitizeStyle(css: string): string {
34
+ const cleaned = css.replace(GOOGLE_FONTS_IMPORT, '').replace(QUOTED_VAR_FONT_FAMILY, '$1$3')
35
+ if (process.env.NODE_ENV !== 'production' && /googleapis/i.test(cleaned)) {
36
+ console.warn(
37
+ '[basalt] MermaidDiagram: a remote font import survived sanitization — beautiful-mermaid ' +
38
+ 'changed its <style> output; update src/content/mermaid-sanitize.ts.',
39
+ )
40
+ }
41
+ return cleaned
42
+ }
43
+
44
+ export function sanitizeMermaidFonts(svg: string): string {
45
+ return svg.replace(
46
+ STYLE_BLOCK,
47
+ (_block, open: string, css: string, close: string) => open + sanitizeStyle(css) + close,
48
+ )
49
+ }
@@ -23,6 +23,7 @@ import type { CSSProperties, ReactNode } from 'react'
23
23
  import { useEffect, useMemo, useState } from 'react'
24
24
  import { CodeBlock } from './code-block'
25
25
  import classes from './mermaid.module.css'
26
+ import { sanitizeMermaidFonts } from './mermaid-sanitize'
26
27
 
27
28
  // Import the type only — erased at runtime (verbatimModuleSyntax safe). `beautiful-mermaid` is a
28
29
  // devDependency purely so this type resolves; the runtime import below is fully dynamic.
@@ -36,7 +37,7 @@ type MermaidModule = {
36
37
  * Static theme mapping onto the `--vx-*` token layer — every value is a `var(--vx-*)` string, so
37
38
  * this object never changes across renders/schemes and can live at module scope.
38
39
  */
39
- const MERMAID_THEME_OPTIONS: RenderOptions = {
40
+ export const MERMAID_THEME_OPTIONS: RenderOptions = {
40
41
  bg: 'var(--vx-surface-panel)',
41
42
  fg: 'var(--vx-ink)',
42
43
  line: 'var(--vx-line)',
@@ -87,7 +88,7 @@ export function MermaidDiagram({ code, className, style, fallback }: MermaidDiag
87
88
  const rendered = useMemo(() => {
88
89
  if (!mod) return null
89
90
  try {
90
- return mod.renderMermaidSVG(code, MERMAID_THEME_OPTIONS)
91
+ return sanitizeMermaidFonts(mod.renderMermaidSVG(code, MERMAID_THEME_OPTIONS))
91
92
  } catch {
92
93
  return undefined
93
94
  }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Which TOC entry the reader just ASKED for, until the page has caught up.
3
+ *
4
+ * idle ──click──▶ pinned{id} ──scrollend / 200 ms without scrolling──▶ held{id, top}
5
+ * ▲ │ scroll intent │ scroll moves > ε (any cause),
6
+ * └────────────────┴──────────────────────────────────────────┘ scroll intent, id gone, unmount
7
+ *
8
+ * The clicked heading rests under the sticky header, above the spy's band, so the spy cannot be
9
+ * trusted while the click's scroll is in flight; once it has settled the spy's own answer is right
10
+ * and the hold only has to cover the short-tail case. So: pinned while the scroll runs (until its
11
+ * `scrollend`, or until the scroller has been quiet for a moment where there is none), held where it
12
+ * settled, and handed back the moment
13
+ * the position moves for ANY reason — reader, find-in-page, focus, layout shift, app scroll.
14
+ */
15
+ import { useEffect, useState } from 'react'
16
+
17
+ /**
18
+ * How long the scroller must be quiet before a pinned click counts as settled: the fallback for a
19
+ * browser without a reliable `scrollend`, and the only signal for a click that needs no scroll.
20
+ */
21
+ export const QUIET_MS = 200
22
+ /** Scroll movement tolerated while held (sub-pixel offsets, fractional DPR). */
23
+ export const HOLD_EPSILON_PX = 2
24
+
25
+ const SCROLL_KEYS: ReadonlySet<string> = new Set([
26
+ 'PageUp',
27
+ 'PageDown',
28
+ 'Home',
29
+ 'End',
30
+ 'ArrowUp',
31
+ 'ArrowDown',
32
+ ' ',
33
+ ])
34
+
35
+ /** Where the reader's input is aimed at text entry — through shadow roots, via the composed path. */
36
+ const isEditable = (event: Event): boolean =>
37
+ event
38
+ .composedPath()
39
+ .some(
40
+ (node) =>
41
+ node instanceof HTMLElement &&
42
+ (node.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(node.tagName)),
43
+ )
44
+
45
+ /** The document-level events that mean the reader is about to scroll (or may have). */
46
+ export const INTENT_EVENTS = ['wheel', 'touchstart', 'keydown', 'pointerdown'] as const
47
+
48
+ /**
49
+ * Did the reader just do something that scrolls (or may scroll) the page? `link` is the rail link
50
+ * that was activated: pointing at it is the click itself, and Enter on it is not a scroll key.
51
+ */
52
+ export function isScrollIntent(event: Event, link: Element | null): boolean {
53
+ switch (event.type) {
54
+ case 'wheel':
55
+ case 'touchstart':
56
+ return true
57
+ case 'pointerdown':
58
+ return !(event.target instanceof Node && link?.contains(event.target))
59
+ case 'keydown':
60
+ return event instanceof KeyboardEvent && SCROLL_KEYS.has(event.key) && !isEditable(event)
61
+ default:
62
+ return false
63
+ }
64
+ }
65
+
66
+ function scrollTopOf(scroller: HTMLElement | null): number {
67
+ return scroller ? scroller.scrollTop : window.scrollY
68
+ }
69
+
70
+ type ClickPinState =
71
+ | { readonly kind: 'idle' }
72
+ | { readonly kind: 'pinned'; readonly id: string }
73
+ | { readonly kind: 'held'; readonly id: string; readonly top: number }
74
+
75
+ export class ClickPin {
76
+ private current: ClickPinState = { kind: 'idle' }
77
+ private stop: (() => void) | null = null
78
+
79
+ /** `onIdle` runs when the machine hands the rail back, so the spy can re-resolve. */
80
+ constructor(private readonly onIdle: () => void) {}
81
+
82
+ get state(): ClickPinState {
83
+ return this.current
84
+ }
85
+
86
+ /** The entry the click owns (pinned or held), or `null` when the spy answers. A pure query. */
87
+ get activeId(): string | null {
88
+ return this.current.kind === 'idle' ? null : this.current.id
89
+ }
90
+
91
+ /** `link` is the rail link just activated; `scroller` the element the spy watches (`null` = document). */
92
+ click(id: string, link: Element | null, scroller: HTMLElement | null): void {
93
+ this.stop?.()
94
+ this.current = { kind: 'pinned', id }
95
+
96
+ const target: Window | HTMLElement = scroller ?? window
97
+ let quiet: ReturnType<typeof setTimeout> | undefined
98
+ const hold = () => {
99
+ clearTimeout(quiet)
100
+ if (this.current.kind !== 'pinned') return
101
+ this.current = { kind: 'held', id, top: scrollTopOf(scroller) }
102
+ }
103
+ const onScroll = () => {
104
+ const state = this.current
105
+ if (state.kind === 'pinned') {
106
+ clearTimeout(quiet)
107
+ quiet = setTimeout(hold, QUIET_MS)
108
+ } else if (
109
+ state.kind === 'held' &&
110
+ Math.abs(scrollTopOf(scroller) - state.top) > HOLD_EPSILON_PX
111
+ ) {
112
+ this.release()
113
+ }
114
+ }
115
+ const onIntent = (event: Event) => {
116
+ if (isScrollIntent(event, link)) this.release()
117
+ }
118
+ quiet = setTimeout(hold, QUIET_MS)
119
+ target.addEventListener('scrollend', hold, { once: true })
120
+ target.addEventListener('scroll', onScroll, { passive: true })
121
+ for (const type of INTENT_EVENTS) document.addEventListener(type, onIntent, { capture: true })
122
+ this.stop = () => {
123
+ clearTimeout(quiet)
124
+ target.removeEventListener('scrollend', hold)
125
+ target.removeEventListener('scroll', onScroll)
126
+ for (const type of INTENT_EVENTS) {
127
+ document.removeEventListener(type, onIntent, { capture: true })
128
+ }
129
+ }
130
+ }
131
+
132
+ /** Items changed: a click on an id that no longer exists cannot stand. */
133
+ prune(ids: readonly string[]): void {
134
+ if (this.current.kind !== 'idle' && !ids.includes(this.current.id)) this.release()
135
+ }
136
+
137
+ release(): void {
138
+ if (this.current.kind === 'idle') return
139
+ this.dispose()
140
+ this.onIdle()
141
+ }
142
+
143
+ /** Unmount: idle, timer and listeners gone, no callback. */
144
+ dispose(): void {
145
+ this.stop?.()
146
+ this.stop = null
147
+ this.current = { kind: 'idle' }
148
+ }
149
+ }
150
+
151
+ /** `onIdle` must be stable (a state setter): it is captured once, at construction. */
152
+ export function useClickPin(onIdle: () => void): ClickPin {
153
+ const [pin] = useState(() => new ClickPin(onIdle))
154
+ useEffect(() => () => pin.dispose(), [pin])
155
+ return pin
156
+ }
@@ -0,0 +1,61 @@
1
+ /** The TOC scroll-spy's pure half: scroll geometry in, the reader's section out. */
2
+
3
+ /** Sub-pixel / fractional-DPR slack when asking "is the scrollport at its end". */
4
+ export const BOTTOM_EPSILON_PX = 2
5
+ /** Distance below the scrollport's top where a heading counts as reached (the observer's top inset). */
6
+ export const ACTIVATION_TOP_PX = 80
7
+ /** The observer's band: below the activation line, down to 30% of the scrollport. */
8
+ export const OBSERVER_ROOT_MARGIN = `-${ACTIVATION_TOP_PX}px 0px -70% 0px`
9
+
10
+ export type ScrollMetrics = {
11
+ readonly top: number
12
+ readonly scrollTop: number
13
+ readonly clientHeight: number
14
+ readonly scrollHeight: number
15
+ }
16
+
17
+ /** The scrollport's geometry; `null` is the document, whose "top" is the viewport's. */
18
+ export function scrollMetrics(port: HTMLElement | null): ScrollMetrics {
19
+ if (port) {
20
+ return {
21
+ top: port.getBoundingClientRect().top,
22
+ scrollTop: port.scrollTop,
23
+ clientHeight: port.clientHeight,
24
+ scrollHeight: port.scrollHeight,
25
+ }
26
+ }
27
+ return {
28
+ top: 0,
29
+ scrollTop: window.scrollY,
30
+ clientHeight: window.innerHeight,
31
+ scrollHeight: document.documentElement.scrollHeight,
32
+ }
33
+ }
34
+
35
+ /** Is there a scroll range at all? Content that fits has no "top" or "bottom" to be at. */
36
+ export function canScroll(m: ScrollMetrics): boolean {
37
+ return m.scrollHeight - m.clientHeight > BOTTOM_EPSILON_PX
38
+ }
39
+
40
+ export function isAtBottom(m: ScrollMetrics): boolean {
41
+ return canScroll(m) && m.scrollTop + m.clientHeight >= m.scrollHeight - BOTTOM_EPSILON_PX
42
+ }
43
+
44
+ /**
45
+ * The reader's section. Nothing to scroll: the first heading. At the end: the last (its section may
46
+ * be too short to ever reach the band). Otherwise the topmost heading inside the band, else the last
47
+ * heading at or above the activation line, else the first.
48
+ */
49
+ export function pickActive(
50
+ elements: readonly HTMLElement[],
51
+ intersecting: ReadonlySet<string>,
52
+ m: ScrollMetrics,
53
+ ): string | undefined {
54
+ if (!canScroll(m)) return elements[0]?.id
55
+ if (isAtBottom(m)) return elements[elements.length - 1]?.id
56
+ const topmost = elements.find((el) => intersecting.has(el.id))
57
+ if (topmost) return topmost.id
58
+ const line = m.top + ACTIVATION_TOP_PX
59
+ const passed = elements.filter((el) => el.getBoundingClientRect().top <= line)
60
+ return (passed[passed.length - 1] ?? elements[0])?.id
61
+ }
@@ -17,10 +17,7 @@
17
17
  * a viewport-rooted observer measures the wrong band. `null` means the document scrolls, which is
18
18
  * the shell-less case and behaves exactly as before.
19
19
  *
20
- * The active rail item carries `aria-current="location"` (WAI-ARIA APG's own recommendation for a
21
- * link set that navigates within one page, rather than `"page"`/`"true"`) — both a genuine a11y fix
22
- * (previously `activeId` drove `classes.active` alone, so a screen reader had no signal at all) and
23
- * the one DOM-observable hook for `activeId` that does not depend on a CSS Modules class hash.
20
+ * The active item carries `aria-current="location"` (WAI-ARIA APG: a link set within one page).
24
21
  *
25
22
  * @example
26
23
  * import { TableOfContents, headingSlug } from 'basalt-ui/content'
@@ -32,10 +29,12 @@
32
29
  * <TableOfContents containerRef={articleRef} />
33
30
  */
34
31
  import type { MouseEvent, RefObject } from 'react'
35
- import { useEffect, useRef, useState } from 'react'
32
+ import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
36
33
  import { useReducedMotion } from '@mantine/hooks'
37
34
  import { scrollParentOf } from '../common/scroll-parent'
38
35
  import classes from './toc.module.css'
36
+ import { useClickPin } from './toc-click-pin'
37
+ import { OBSERVER_ROOT_MARGIN, pickActive, scrollMetrics } from './toc-spy'
39
38
 
40
39
  export type TocItem = {
41
40
  readonly id: string
@@ -59,12 +58,6 @@ export type TableOfContentsProps = {
59
58
  const DEFAULT_LEVELS: readonly [number, number] = [2, 3]
60
59
  const DEFAULT_TITLE = 'On this page'
61
60
 
62
- /**
63
- * Ceiling on how long a clicked item holds the rail: released on `scrollend` where supported, so
64
- * this only covers browsers without it — and a smooth scroll that never settles.
65
- */
66
- const CLICK_PIN_MAX_MS = 1000
67
-
68
61
  /** Heading text without the hover-anchor `#` glyph the markdown/MDX heading renderers append. */
69
62
  function headingLabel(node: HTMLElement): string {
70
63
  const clone = node.cloneNode(true) as HTMLElement
@@ -93,18 +86,19 @@ export function TableOfContents({
93
86
  const [collected, setCollected] = useState<TocItem[]>([])
94
87
  const [activeId, setActiveId] = useState<string | null>(null)
95
88
  const reduceMotion = useReducedMotion()
96
- // Set while a clicked item owns the rail; `resolve` stands down until it's released.
97
- const pinnedRef = useRef<string | null>(null)
98
- const releasePinRef = useRef<(() => void) | null>(null)
99
89
  // The rail's own node — the probe `scrollParentOf` walks from when there is no `containerRef`.
100
90
  const navRef = useRef<HTMLElement | null>(null)
101
- // The resolved scrollport (`null` = the document), published by the spy effect so the click-pin
102
- // release below listens for `scrollend` on the same box the spy is watching.
91
+ // The spy's working set, resolved once per effect run: headings, scroller, and the band's members.
92
+ const elementsRef = useRef<HTMLElement[]>([])
103
93
  const portRef = useRef<HTMLElement | null>(null)
104
-
105
- useEffect(() => {
106
- return () => releasePinRef.current?.()
107
- }, [])
94
+ const intersectingRef = useRef<Set<string>>(new Set())
95
+ // Bumped when a click hands the rail back, so the rail re-resolves.
96
+ const [idleTick, bumpIdle] = useReducer((n: number) => n + 1, 0)
97
+ const pin = useClickPin(bumpIdle)
98
+ const scrollerOf = useCallback(
99
+ () => scrollParentOf(containerRef?.current ?? navRef.current),
100
+ [containerRef],
101
+ )
108
102
 
109
103
  // Auto-collection: re-scan on mount + on any childList mutation under the container.
110
104
  useEffect(() => {
@@ -122,51 +116,35 @@ export function TableOfContents({
122
116
 
123
117
  const resolvedItems = items ?? collected
124
118
 
119
+ // The spy's answer for the reader's current position — or the clicked entry, while the click owns it.
120
+ const resolve = useCallback(() => {
121
+ if (pin.activeId !== null) {
122
+ setActiveId(pin.activeId)
123
+ return
124
+ }
125
+ const id = pickActive(
126
+ elementsRef.current,
127
+ intersectingRef.current,
128
+ scrollMetrics(portRef.current),
129
+ )
130
+ if (id !== undefined) setActiveId(id)
131
+ }, [pin])
132
+
125
133
  // Scroll-spy: one IntersectionObserver over every collected heading.
126
134
  useEffect(() => {
135
+ pin.prune(resolvedItems.map((item) => item.id))
127
136
  if (resolvedItems.length === 0) return
128
137
  const elements = resolvedItems
129
138
  .map((item) => document.getElementById(item.id))
130
139
  .filter((el): el is HTMLElement => el !== null)
131
140
  if (elements.length === 0) return
132
141
 
133
- const port = scrollParentOf(containerRef?.current ?? navRef.current)
134
- portRef.current = port
142
+ const port = scrollerOf()
135
143
  const scroller: Window | HTMLElement = port ?? window
136
-
137
- const intersecting = new Set<string>()
138
-
139
- const resolve = () => {
140
- // A clicked item is the reader SAYING where they are; everything below only infers it. Stand
141
- // down until the scroll they asked for has settled.
142
- if (pinnedRef.current !== null) return
143
-
144
- // Bottom edge: the last sections are usually shorter than the observer's 70% dead zone, so
145
- // their headings can NEVER reach the activation band — the rail would stall on whichever
146
- // section last made it in. Once the page bottoms out, the final item is the honest answer.
147
- const box = port ?? document.documentElement
148
- const seen = port ? port.clientHeight + port.scrollTop : window.innerHeight + window.scrollY
149
- if (seen >= box.scrollHeight - 2) {
150
- const last = elements[elements.length - 1]
151
- if (last) setActiveId(last.id)
152
- return
153
- }
154
-
155
- if (intersecting.size > 0) {
156
- const topmost = elements.find((el) => intersecting.has(el.id))
157
- if (topmost) setActiveId(topmost.id)
158
- return
159
- }
160
-
161
- // Nothing intersecting — the last heading already scrolled past, or (above the first one,
162
- // i.e. at the very top of the article) the first heading, so the rail always marks where the
163
- // reader actually is instead of showing nothing until the first heading reaches the band.
164
- // "Past" is measured against the SCROLLER's top edge, which for the window case is 0.
165
- const originTop = port ? port.getBoundingClientRect().top : 0
166
- const passed = elements.filter((el) => el.getBoundingClientRect().top < originTop)
167
- const current = passed[passed.length - 1] ?? elements[0]
168
- if (current) setActiveId(current.id)
169
- }
144
+ const intersecting = intersectingRef.current
145
+ intersecting.clear()
146
+ elementsRef.current = elements
147
+ portRef.current = port
170
148
 
171
149
  const observer = new IntersectionObserver(
172
150
  (entries) => {
@@ -178,54 +156,34 @@ export function TableOfContents({
178
156
  },
179
157
  // `root: null` IS the viewport — the shell-less case, unchanged. Inside a shell the root has
180
158
  // to be the scrollport or the `-70%` dead zone is measured against a box nothing scrolls.
181
- { root: port, rootMargin: '-80px 0px -70% 0px' },
159
+ { root: port, rootMargin: OBSERVER_ROOT_MARGIN },
182
160
  )
183
161
 
184
162
  for (const el of elements) observer.observe(el)
185
- // The observer only fires when an intersection CHANGES; the bottom edge above resolves on
186
- // scroll position alone, so it needs a scroll signal too. Re-setting the same id is a no-op
187
- // for React, so this stays free on every frame that doesn't move the rail.
163
+ // The observer only fires when an intersection CHANGES; the bottom edge resolves on scroll
164
+ // position alone, so it needs a scroll signal too. Re-setting the same id is a no-op for React.
188
165
  scroller.addEventListener('scroll', resolve, { passive: true })
189
166
  return () => {
190
167
  observer.disconnect()
191
168
  scroller.removeEventListener('scroll', resolve)
192
- portRef.current = null
169
+ elementsRef.current = []
193
170
  }
194
- }, [resolvedItems, containerRef])
171
+ }, [resolvedItems, scrollerOf, pin, resolve])
195
172
 
196
- if (resolvedItems.length === 0) return null
197
-
198
- /**
199
- * Hold the rail on the clicked item until its scroll settles. Without this the spy overwrites the
200
- * choice mid-flight — most visibly for a section near the end, where the page bottoms out before
201
- * the heading can reach the activation band, so the bottom pin would answer with the LAST item
202
- * instead of the one that was asked for.
203
- */
204
- const pinActive = (id: string) => {
205
- releasePinRef.current?.()
206
- setActiveId(id)
207
- pinnedRef.current = id
173
+ // A click handed the rail back: answer for where the reader is, next frame.
174
+ useEffect(() => {
175
+ const frame = requestAnimationFrame(resolve)
176
+ return () => cancelAnimationFrame(frame)
177
+ }, [idleTick, resolve])
208
178
 
209
- // The same box the spy watches — `scrollend` on `window` never fires for a scroll that happened
210
- // inside `AppShell.Main`, which would leave the rail pinned for the full `CLICK_PIN_MAX_MS`.
211
- const scroller: Window | HTMLElement = portRef.current ?? window
212
- let timer: ReturnType<typeof setTimeout> | null = null
213
- const release = () => {
214
- pinnedRef.current = null
215
- if (timer !== null) clearTimeout(timer)
216
- scroller.removeEventListener('scrollend', release)
217
- releasePinRef.current = null
218
- }
219
- timer = setTimeout(release, CLICK_PIN_MAX_MS)
220
- scroller.addEventListener('scrollend', release, { once: true })
221
- releasePinRef.current = release
222
- }
179
+ if (resolvedItems.length === 0) return null
223
180
 
224
181
  const handleClick = (id: string) => (event: MouseEvent<HTMLAnchorElement>) => {
225
182
  event.preventDefault()
226
183
  const el = document.getElementById(id)
227
184
  if (el) {
228
- pinActive(id)
185
+ setActiveId(id)
186
+ pin.click(id, event.currentTarget, scrollerOf())
229
187
  el.scrollIntoView({ behavior: reduceMotion ? 'auto' : 'smooth' })
230
188
  history.replaceState(null, '', `#${id}`)
231
189
  }
@@ -249,12 +207,6 @@ export function TableOfContents({
249
207
  ]
250
208
  .filter(Boolean)
251
209
  .join(' ')}
252
- // `classes.active` alone used to be the ONLY signal of which item the spy picked —
253
- // both a real a11y gap (nothing here told assistive tech which section is current)
254
- // and, incidentally, the reason a consumer/test could not observe `activeId` without
255
- // reading CSS. `location` (not `page`/`true`) is the value WAI-ARIA's Authoring
256
- // Practices call out BY NAME for exactly this widget: a set of links navigating
257
- // within a single page, as opposed to a set of links to different pages.
258
210
  aria-current={activeId === item.id ? 'location' : undefined}
259
211
  onClick={handleClick(item.id)}
260
212
  >
@@ -2,7 +2,7 @@
2
2
  * ./controls — the form layout primitives: `FormSection`, `FormRow`, `FormGroup`, `FormActions`.
3
3
  * Mantine-coupled. They need no `@mantine/form` (layout only), which is why they live here and not
4
4
  * in `./forms`, whose barrel value-imports it: importing a row from there made a consumer install a
5
- * peer it never used. `./forms` re-exports them as deprecated aliases until 1.39.0.
5
+ * peer it never used.
6
6
  *
7
7
  * The gap they close (audit B #5 / §4): `./forms` shipped no layout at all, so the only row
8
8
  * primitive in the package was `SettingsRow` over in `./dashboard` — which is the SETTINGS-page
@@ -53,6 +53,10 @@
53
53
  * <NumberFilter field={lines.field.minDuration} label="Min duration" step={30} />
54
54
  *
55
55
  * @example
56
+ * // Naming the unset state: labels are keyed by value, at definition, like every option label.
57
+ * // store = createSearchStore({ … }).labels({ minDuration: { 0: 'Any' } }) → the pill reads "Any"
58
+ *
59
+ * @example
56
60
  * // "No filter" is the fallback, not a row: `clearable` writes it back, and the pill reads the
57
61
  * // filter's name while no preset is picked.
58
62
  * // difficulty: field.number({ fallback: 0, min: 0, max: 5, int: true })
@@ -276,7 +280,8 @@ function NumberStepper({
276
280
 
277
281
  return (
278
282
  <FilterPill
279
- label={String(value)}
283
+ // A value `.labels()` names (`{ 0: 'Any' }`) reads as that name — the unset state's wording.
284
+ label={field.options.find((option) => option.value === String(value))?.label ?? String(value)}
280
285
  numeric
281
286
  active={!isDefault}
282
287
  {...(icon !== undefined && { icon })}
@@ -1,12 +1,7 @@
1
1
  export { WidgetHeader } from './widget-header'
2
2
  export { DeltaBadge } from './delta-badge'
3
3
  export { Section } from './section'
4
- export {
5
- StatCard,
6
- type StatCardBreakdownRow,
7
- type StatCardSparklineSize,
8
- type StatCardTone,
9
- } from './stat-card'
4
+ export { StatCard, type StatCardBreakdownRow, type StatCardSparklineSize } from './stat-card'
10
5
  export { StatGroup } from './stat-group'
11
6
  export { EmptyState } from './empty-state'
12
7
  export { SettingsSection, SettingsRow, DangerZone } from './settings-section'