basalt-ui 2.8.1 → 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 (137) hide show
  1. package/AGENTS.md +2 -2
  2. package/CHANGELOG.md +24 -0
  3. package/MIGRATING.md +58 -27
  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.d.ts.map +1 -1
  28. package/dist/cli/doctor.js +6 -12
  29. package/dist/cli/help.d.ts.map +1 -1
  30. package/dist/cli/help.js +2 -3
  31. package/dist/cli/index.d.ts.map +1 -1
  32. package/dist/cli/install-root.d.ts +10 -0
  33. package/dist/cli/install-root.d.ts.map +1 -0
  34. package/dist/cli/install-root.js +32 -0
  35. package/dist/cli/sync.d.ts +0 -2
  36. package/dist/cli/sync.d.ts.map +1 -1
  37. package/dist/cli/sync.js +8 -11
  38. package/dist/cli/tokens-css.d.ts.map +1 -1
  39. package/dist/cli/tokens-css.js +1 -6
  40. package/dist/common/errors.d.ts +1 -6
  41. package/dist/common/errors.d.ts.map +1 -1
  42. package/dist/common/errors.js +0 -7
  43. package/dist/common/index.d.ts +1 -1
  44. package/dist/common/index.d.ts.map +1 -1
  45. package/dist/common/index.js +1 -9
  46. package/dist/common/props.d.ts +2 -2
  47. package/dist/common/vx-family.d.ts +1 -1
  48. package/dist/content/toc-click-pin.d.ts +45 -0
  49. package/dist/content/toc-click-pin.d.ts.map +1 -0
  50. package/dist/content/toc-click-pin.js +111 -0
  51. package/dist/content/toc-spy.d.ts +25 -0
  52. package/dist/content/toc-spy.d.ts.map +1 -0
  53. package/dist/content/toc-spy.js +43 -0
  54. package/dist/content/toc.d.ts +1 -4
  55. package/dist/content/toc.d.ts.map +1 -1
  56. package/dist/content/toc.js +38 -49
  57. package/dist/controls/number-filter.d.ts.map +1 -1
  58. package/dist/controls/number-filter.js +1 -1
  59. package/dist/dashboard/index.d.ts +1 -1
  60. package/dist/dashboard/index.d.ts.map +1 -1
  61. package/dist/dashboard/index.js +1 -3
  62. package/dist/dashboard/section.d.ts +10 -2
  63. package/dist/dashboard/section.d.ts.map +1 -1
  64. package/dist/dashboard/section.js +20 -3
  65. package/dist/dashboard/stat-card.d.ts +2 -8
  66. package/dist/dashboard/stat-card.d.ts.map +1 -1
  67. package/dist/dashboard/stat-card.js +1 -1
  68. package/dist/guard/index.d.ts +13 -9
  69. package/dist/guard/index.d.ts.map +1 -1
  70. package/dist/guard/index.js +74 -37
  71. package/dist/guard/types.d.ts +8 -7
  72. package/dist/guard/types.d.ts.map +1 -1
  73. package/dist/guard/vx-names.d.ts +1 -1
  74. package/dist/guard/vx-names.d.ts.map +1 -1
  75. package/dist/guard/vx-names.js +1 -33
  76. package/dist/index.d.ts +2 -2
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/router-tanstack/search-store.d.ts +1 -11
  79. package/dist/router-tanstack/search-store.d.ts.map +1 -1
  80. package/dist/router-tanstack/search-store.js +1 -2
  81. package/dist/shell/index.d.ts +1 -0
  82. package/dist/shell/index.d.ts.map +1 -1
  83. package/dist/shell/index.js +3 -0
  84. package/dist/shell/nav-types.d.ts +1 -1
  85. package/dist/shell/page-bar.d.ts +6 -0
  86. package/dist/shell/page-bar.d.ts.map +1 -1
  87. package/dist/shell/page-bar.js +12 -2
  88. package/dist/state/fields.d.ts +1 -1
  89. package/dist/state/fields.d.ts.map +1 -1
  90. package/dist/state/fields.js +3 -1
  91. package/dist/surfaces.d.ts +1 -1
  92. package/dist/surfaces.d.ts.map +1 -1
  93. package/dist/surfaces.js +5 -11
  94. package/dist/table/data-table.d.ts +2 -2
  95. package/dist/tokens/core.d.ts +0 -10
  96. package/dist/tokens/core.d.ts.map +1 -1
  97. package/dist/tokens/core.js +6 -44
  98. package/llms.txt +24 -8
  99. package/package.json +8 -5
  100. package/src/charts/BandStrip.tsx +4 -16
  101. package/src/charts/MirroredBars.tsx +2 -11
  102. package/src/charts/band-fold.ts +26 -0
  103. package/src/charts/index.ts +1 -0
  104. package/src/cli/audit-allows.ts +1 -3
  105. package/src/cli/check-theme.ts +7 -1
  106. package/src/cli/config.ts +4 -4
  107. package/src/cli/doctor.ts +6 -17
  108. package/src/cli/help.ts +1 -4
  109. package/src/cli/index.ts +1 -2
  110. package/src/cli/install-root.ts +40 -0
  111. package/src/cli/sync.ts +9 -12
  112. package/src/cli/tokens-css.ts +0 -5
  113. package/src/common/errors.ts +1 -18
  114. package/src/common/index.ts +1 -8
  115. package/src/common/props.ts +2 -2
  116. package/src/common/vx-family.ts +1 -1
  117. package/src/content/toc-click-pin.ts +156 -0
  118. package/src/content/toc-spy.ts +61 -0
  119. package/src/content/toc.tsx +47 -95
  120. package/src/controls/form-layout.tsx +1 -1
  121. package/src/controls/number-filter.tsx +6 -1
  122. package/src/dashboard/index.ts +1 -6
  123. package/src/dashboard/section.tsx +39 -8
  124. package/src/dashboard/stat-card.tsx +4 -11
  125. package/src/guard/index.ts +114 -89
  126. package/src/guard/types.ts +8 -7
  127. package/src/guard/vx-names.ts +1 -33
  128. package/src/index.ts +1 -2
  129. package/src/router-tanstack/search-store.ts +2 -14
  130. package/src/shell/index.tsx +2 -0
  131. package/src/shell/nav-types.ts +1 -1
  132. package/src/shell/page-bar.tsx +21 -2
  133. package/src/state/fields.ts +7 -2
  134. package/src/surfaces.ts +5 -11
  135. package/src/table/data-table.tsx +2 -2
  136. package/src/tokens/core.ts +6 -67
  137. package/dist/tokens.css +0 -331
package/src/cli/config.ts CHANGED
@@ -130,8 +130,8 @@ export type BasaltConfig = {
130
130
  seriesModulePath?: string
131
131
  /**
132
132
  * Per-rule, per-path exemptions, complementing whole-file `exempt`. A pattern is matched against a
133
- * finding's relative path: a path segment (`'agent'` matches `src/agent/x.tsx`, not
134
- * `src/agenting.ts`), a relative path, a directory prefix, or a glob (`*` stops at `/`, `**` does
133
+ * finding's relative path: a relative path (`'public/site.webmanifest'`), a
134
+ * directory prefix (`'src/agent'` matches `src/agent/x.tsx`, not `src/agenting.ts`), or a glob (`*` stops at `/`, `**` does
135
135
  * not; a slash-free glob also matches the basename). An entry that suppresses nothing is reported
136
136
  * and `check-theme --audit-allows` exits 1 on it. Default: `{}`.
137
137
  *
@@ -139,9 +139,9 @@ export type BasaltConfig = {
139
139
  * `.webmanifest` finding's only escape is this key), which `--audit-allows` prints.
140
140
  *
141
141
  * @example
142
- * { exemptRules: { 'inline-display': ['agent'] } } // inline-display never fires under src/agent/**
142
+ * { exemptRules: { 'inline-display': ['src/agent'] } } // inline-display never fires under src/agent/**
143
143
  * @example
144
- * { exemptRules: { 'raw-hex': { paths: ['site.webmanifest'],
144
+ * { exemptRules: { 'raw-hex': { paths: ['public/site.webmanifest'],
145
145
  * reason: 'a PWA manifest theme_color MUST be a literal hex — JSON cannot reference a CSS var' } } }
146
146
  */
147
147
  exemptRules?: Partial<Record<GuardKind, ExemptRuleEntry>>
package/src/cli/doctor.ts CHANGED
@@ -9,6 +9,7 @@ import { relative, resolve } from 'node:path'
9
9
  import {
10
10
  AGENTS_MD,
11
11
  LEGACY_BLOCK_HOST,
12
+ scanBlock,
12
13
  MANIFEST_PATH,
13
14
  basaltBinCommand,
14
15
  basaltPresetEntry,
@@ -31,7 +32,6 @@ import {
31
32
  ROUTER_SEED_DESTS,
32
33
  sameFile,
33
34
  scannableFiles,
34
- scanBlock,
35
35
  shippedAssetPath,
36
36
  } from './index'
37
37
  import { resolveRoots } from './config'
@@ -47,7 +47,8 @@ import {
47
47
  unknownConfigKeysCheck,
48
48
  } from './doctor-upgrade'
49
49
  import type { Check } from './doctor-upgrade'
50
- import { findManifestAbove, parentInstallAdvice } from './sync'
50
+ import { findManifestAbove, installRootAbove } from './install-root'
51
+ import { parentInstallAdvice } from './sync'
51
52
 
52
53
  /** `sameFile`, but doctor never crashes: a path that cannot be inspected is "not provably the same". */
53
54
  function isSameFile(a: string, b: string): boolean {
@@ -123,17 +124,9 @@ export function doctor(invocationCwd: string = process.cwd(), flags: string[] =
123
124
  if (conflictingProfileFlags('doctor', flags)) return 1
124
125
  const project = resolveProjectDir(invocationCwd)
125
126
  // Inside the app package of a monorepo the manifest is above: read the install root instead.
126
- const aboveRoot =
127
- project.relocatedFrom === null && !existsSync(resolve(project.dir, MANIFEST_PATH))
128
- ? findManifestAbove(project.dir)
129
- : null
130
- const insideApp =
131
- aboveRoot !== null &&
132
- (() => {
133
- const app = resolveAppDir(aboveRoot)
134
- return !('error' in app) && app.dir === project.dir
135
- })()
136
- const cwd = insideApp && aboveRoot !== null ? aboveRoot : project.dir
127
+ const aboveRoot = project.relocatedFrom === null ? installRootAbove(project.dir) : null
128
+ const insideApp = aboveRoot !== null
129
+ const cwd = aboveRoot ?? project.dir
137
130
  const cfg = readBasaltConfig(cwd)
138
131
  const result: DoctorResult = { hardFailures: 0, warnings: 0, skipped: 0 }
139
132
  const lines: string[] = [`\nbasalt-ui doctor — ${cwd}\n`]
@@ -319,10 +312,6 @@ export function doctor(invocationCwd: string = process.cwd(), flags: string[] =
319
312
  const issues: string[] = []
320
313
  if (scan.problem !== null) {
321
314
  issues.push(`has a malformed basalt block (${scan.problem}) — fix it by hand, then \`sync\``)
322
- } else if (scan.region !== null) {
323
- issues.push(
324
- `still carries a stale basalt block — delete it by hand; \`sync\` keeps ${AGENTS_MD} current`,
325
- )
326
315
  }
327
316
  if (!importsAgentsMd(legacy)) {
328
317
  issues.push(
package/src/cli/help.ts CHANGED
@@ -41,7 +41,6 @@ export const COMMAND_OPTIONS: Record<string, Record<string, { type: 'string' | '
41
41
  'default-scheme': { type: 'string' },
42
42
  'media-fallback': { type: 'boolean' },
43
43
  only: { type: 'string' },
44
- 'no-legacy-aliases': { type: 'boolean' },
45
44
  },
46
45
  'fonts:css': { out: { type: 'string' }, check: { type: 'boolean' } },
47
46
  }
@@ -75,12 +74,10 @@ export const USAGE =
75
74
  'tokens:css [--out <path>] [--check] [--selector-attribute <attr> | --selector-class <class>]\n' +
76
75
  ' [--light-class <class>] [--dark-value <v>] [--light-value <v>]\n' +
77
76
  ' [--default-scheme <dark|light|none>] [--media-fallback] [--only <core|all>]\n' +
78
- ' [--no-legacy-aliases]\n' +
79
77
  ' Emit the --vx-* stylesheet (stdout unless --out). Defaults emit the stock identity; commit the output as your tokens file.\n' +
80
78
  ' --selector-class emits `:root.dark` instead of an attribute selector (the Tailwind convention).\n' +
81
79
  ' --check writes nothing and exits 1 when --out differs from what would be emitted (a CI gate).\n' +
82
- ' --no-legacy-aliases drops the deprecated camelCase spellings (--vx-accentFill and friends),\n' +
83
- ' which are emitted by default as aliases of the canonical kebab-case names.\n\n' +
80
+ '\n' +
84
81
  'fonts:css [--out <path>] [--check]\n' +
85
82
  ' Emit the shipped --basalt-font-* stacks as plain CSS — the typeface half of the token layer,\n' +
86
83
  ' otherwise reachable only by importing styles.css.\n\n' +
package/src/cli/index.ts CHANGED
@@ -845,8 +845,7 @@ export function managedFiles(placement: PlacementFlags = ROOT_PLACEMENT): Manage
845
845
  },
846
846
  }
847
847
 
848
- // Scaffold destination is `.oxfmtrc.json` — oxfmt auto-discovers that filename, not `oxfmt.json`
849
- // (the pre-rename scaffold; see migrateLegacyOxfmt for the one-time cleanup of the old dest).
848
+ // Scaffold destination is `.oxfmtrc.json` — oxfmt auto-discovers that filename, not `oxfmt.json`.
850
849
  // Content is a starting copy, not a reference — oxfmt has no `extends` mechanism.
851
850
  const oxfmt: ManagedFile = {
852
851
  dest: '.oxfmtrc.json',
@@ -0,0 +1,40 @@
1
+ /** Which install root a project-scoped command run inside a workspace package reads — one answer for `doctor` and `sync`. */
2
+ import { existsSync, realpathSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+
5
+ import { MANIFEST_PATH, findBasaltInstall, resolveAppDir } from './index'
6
+ import { hasDependency } from './source-text'
7
+
8
+ /** The nearest ANCESTOR of `dir` (exclusive) carrying a basalt manifest, or null. */
9
+ export function findManifestAbove(dir: string): string | null {
10
+ let current = resolve(dir, '..')
11
+ for (;;) {
12
+ if (existsSync(resolve(current, MANIFEST_PATH))) return current
13
+ const parent = resolve(current, '..')
14
+ if (parent === current) return null
15
+ current = parent
16
+ }
17
+ }
18
+
19
+ function sameInstall(a: string | null, b: string | null): boolean {
20
+ if (a === null || b === null) return false
21
+ return a === b || realpathSync(a) === realpathSync(b)
22
+ }
23
+
24
+ /**
25
+ * The install root above `dir`, when `dir` is the APP package of that install: no manifest here,
26
+ * basalt-ui declared here, an ancestor manifest, `resolveAppDir(root)` naming `dir`, and the
27
+ * basalt-ui that resolves from `dir` the same copy (or version) the root uses. Anything else is
28
+ * null — a sub-package with its own basalt-ui is a competing install, not part of the root's.
29
+ */
30
+ export function installRootAbove(dir: string): string | null {
31
+ if (existsSync(resolve(dir, MANIFEST_PATH)) || !hasDependency(dir, 'basalt-ui')) return null
32
+ const root = findManifestAbove(dir)
33
+ if (root === null) return null
34
+ const app = resolveAppDir(root)
35
+ if ('error' in app || app.dir !== dir) return null
36
+ const here = findBasaltInstall(dir)
37
+ const there = findBasaltInstall(root)
38
+ const sameVersion = here.version !== null && here.version === there.version
39
+ return sameInstall(here.dir, there.dir) || sameVersion ? root : null
40
+ }
package/src/cli/sync.ts CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  writeFileEnsuringDir,
40
40
  writeUnit,
41
41
  } from './index'
42
+ import { findManifestAbove, installRootAbove } from './install-root'
42
43
 
43
44
  /** The oxlint plugins the shipped preset switches on — read from the preset, never restated. */
44
45
  export function readOxlintPresetPlugins(pkgRoot: string): string[] {
@@ -64,17 +65,6 @@ export function parentInstallAdvice(cwd: string, parent: string, verb: string):
64
65
  )
65
66
  }
66
67
 
67
- /** The nearest ANCESTOR of `dir` (exclusive) carrying a basalt manifest, or null. */
68
- export function findManifestAbove(dir: string): string | null {
69
- let current = resolve(dir, '..')
70
- for (;;) {
71
- if (existsSync(resolve(current, MANIFEST_PATH))) return current
72
- const parent = resolve(current, '..')
73
- if (parent === current) return null
74
- current = parent
75
- }
76
- }
77
-
78
68
  /**
79
69
  * Reconcile managed files with the shipped versions via a sha256 three-way compare.
80
70
  *
@@ -89,8 +79,15 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
89
79
  const syncFlags = opts.flags ?? []
90
80
  if (conflictingProfileFlags('sync', syncFlags)) return 1
91
81
  const project = resolveProjectDir(invocationCwd)
92
- const cwd = project.dir
93
82
  noteRelocation('sync', project)
83
+ // Inside the app package of a workspace the manifest is at the install root above: sync there.
84
+ const installAbove = project.relocatedFrom === null ? installRootAbove(project.dir) : null
85
+ const cwd = installAbove ?? project.dir
86
+ if (installAbove !== null) {
87
+ console.log(
88
+ `basalt-ui sync: ${project.dir} is a package of the install at ${installAbove}; syncing there.`,
89
+ )
90
+ }
94
91
 
95
92
  // Profile before the refusal: init is NOT the fix for a tokens-only consumer. Declared, never
96
93
  // inferred (the answer silences the whole reconciliation); exits 0 so `sync --check` is wirable.
@@ -168,11 +168,6 @@ export function tokensCss(flags: string[], cwd: string = process.cwd()): number
168
168
  : { defaultScheme: defaultScheme as 'dark' | 'light' | 'none' }),
169
169
  ...(flags.includes('--media-fallback') ? { mediaFallback: true } : {}),
170
170
  ...(only === undefined ? {} : { only: only as 'core' | 'all' }),
171
- // The tokens-only consumer is exactly the one who writes these names by hand, so they are also
172
- // the one who wants the deprecated camelCase aliases gone — and this command is their only
173
- // entry point. Without the flag the CLI and the API could disagree about what basalt's tokens
174
- // are, which is the one thing this command is documented never to allow.
175
- ...(flags.includes('--no-legacy-aliases') ? { legacyAliases: false } : {}),
176
171
  })
177
172
 
178
173
  if (schemeClass !== undefined) {
@@ -39,28 +39,11 @@ export function oneOf(
39
39
  )
40
40
  }
41
41
 
42
- /**
43
- * A prop still shipped and still working, with a named successor and the version it goes away in.
44
- * Majors are banned here, so the deprecation notice IS the migration channel.
45
- */
46
- export function deprecatedProp(
47
- component: string,
48
- oldProp: string,
49
- newProp: string,
50
- removeIn: string,
51
- note?: string,
52
- ): string {
53
- return message(
54
- component,
55
- `prop "${oldProp}" is deprecated — use "${newProp}" instead. "${oldProp}" is removed in ${removeIn}.${note === undefined ? '' : ` ${note}`}`,
56
- )
57
- }
58
-
59
42
  /**
60
43
  * A prop the component ACCEPTS, reads nothing from, and cannot report as wrong — because a SECOND
61
44
  * prop it was passed alongside decides the same thing and won.
62
45
  *
63
- * Distinct from {@link deprecatedProp} (still read, going away) and {@link oneOf} (read, and the
46
+ * Distinct from {@link oneOf} (read, and the
64
47
  * value is out of range): this one renders something the caller did not ask for and nothing in the
65
48
  * type system, the linter or the console says so. A 1.x chart's `height` under `fill` was the
66
49
  * reference case — weatherorb passed both for the life of the file and never learnt that eight height
@@ -9,14 +9,7 @@
9
9
  export { type BasaltProps, type SlotClassNames, type SlotStylesProps } from './props'
10
10
  export { type Tone, type ToneWithNeutral, type Tier, cx } from './props'
11
11
  export { assignRef, mergeRefs } from './refs'
12
- export {
13
- BASALT_PREFIX,
14
- requiredProp,
15
- oneOf,
16
- deprecatedProp,
17
- duplicateMount,
18
- missingLayer,
19
- } from './errors'
12
+ export { BASALT_PREFIX, requiredProp, oneOf, duplicateMount, missingLayer } from './errors'
20
13
  export { useValidateProps, assertRequiredProps, resetValidatedProps } from './validate'
21
14
  export { scrollParentOf, SCROLLPORT_ATTRIBUTE } from './scroll-parent'
22
15
  export { useCoarsePointer } from './use-media-query'
@@ -45,8 +45,8 @@ export interface SlotStylesProps<S extends string> {
45
45
  }
46
46
 
47
47
  /**
48
- * The ONE status vocabulary (audit A13). Five forks exist today — `StatCardTone` and
49
- * `SidebarBlockTone` are byte-identical to this, `CalloutKind` / `AccountBadgeTone` /
48
+ * The ONE status vocabulary (audit A13). Forks exist today — `SidebarBlockTone` is
49
+ * byte-identical to this, `CalloutKind` / `AccountBadgeTone` /
50
50
  * `NotificationIntent` each differ — and they stay put for now: an adopter aliases its fork to this
51
51
  * type, it does not get renamed out from under a consumer.
52
52
  */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A `--vx-*` name's FAMILY — its leading lowercase run: `--vx-surface-bg` → `surface`, `--vx-ink2`
3
- * → `ink`, `--vx-tooltipBg` → `tooltip`, `--vx-fillHover-cyan` → `fill`. Dependency-free, because
3
+ * → `ink`, `--vx-tooltip-bg` → `tooltip`, `--vx-fill-hover-cyan` → `fill`. Dependency-free, because
4
4
  * three sides must agree on it byte for byte: the generator that writes `BASALT_VX_FAMILIES`, the
5
5
  * guard that judges every name inside one of those families, and the token factories that refuse a
6
6
  * consumer name inside one — the refusal is what makes the guard's judgement honest.
@@ -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
+ }