basalt-ui 1.2.0 → 1.3.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.
@@ -68,6 +68,47 @@ const LAYOUT_SURFACE_PROP =
68
68
  const INLINE_SPACING =
69
69
  /\b(?:padding(?:Top|Bottom|Left|Right)?|margin(?:Top|Bottom|Left|Right)?|gap|rowGap|columnGap)\s*:\s*(?!var\()['"]?-?(?!0\b)\d/g
70
70
 
71
+ /**
72
+ * The sub-scale micro-spacing ceiling, in px — the largest literal `inline-spacing` tolerates in a
73
+ * CSS file. Below the smallest spacing scale stop (`SPACE_SCALE.xs`), which is the whole point: a
74
+ * value under that stop has NO token to prefer, so flagging it asks for something that does not
75
+ * exist. Pinned against the real scale by `check-source.test.ts` so a density retune of the ladder
76
+ * cannot leave this stranded above it.
77
+ *
78
+ * Deliberately CSS-ONLY. In TSX the same shape means something different: `pl={4}` is a Mantine
79
+ * PROP and never matches this pattern in the first place, while `style={{ paddingLeft: 4 }}` does —
80
+ * and there the finding is right, because the prop form exists and should have been used. In CSS
81
+ * there is no prop form, and the emitted `--vx-space-*` set is basalt's own component one-offs
82
+ * (`--vx-space-toc-sub-indent`), not a consumer surface. Without this escape a consumer's CSS
83
+ * module had no legal way to write a 4px cluster gap: no token to reach for, `theme-allow` on every
84
+ * line (which `basalt-tokens.md` explicitly warns against), or `exemptRules` — which matches whole
85
+ * path segments and so cannot express `*.module.css`.
86
+ */
87
+ const MICRO_SPACING_CEILING_PX = 10
88
+
89
+ /**
90
+ * Is this CSS declaration entirely sub-scale? True when every literal in the value is a bare px (or
91
+ * unitless) number at or below {@link MICRO_SPACING_CEILING_PX}. `var(...)` components are dropped
92
+ * before the check — a value that mixes a token with a micro literal (`padding: 4px var(--x)`) is
93
+ * already tokenized where it counts.
94
+ *
95
+ * Multi-value shorthands are judged as a whole: `padding: 4px 8px` passes, `padding: 4px 16px` does
96
+ * not — the 16 has a scale stop and should use it. Any other unit (`rem`, `em`, `%`) fails, because
97
+ * the doctrine is stated in px and a rem value is a different axis, not a micro-spacing one.
98
+ */
99
+ function isSubScaleCssSpacing(line: string, matchIndex: number): boolean {
100
+ const colon = line.indexOf(':', matchIndex)
101
+ if (colon === -1) return false
102
+ const rest = line.slice(colon + 1)
103
+ const end = rest.search(/[;}]/)
104
+ const value = (end === -1 ? rest : rest.slice(0, end)).replace(/var\([^)]*\)/g, ' ').trim()
105
+ if (value === '') return true
106
+ return value.split(/\s+/).every((part) => {
107
+ const literal = /^-?(\d+(?:\.\d+)?)(?:px)?$/.exec(part)
108
+ return literal !== null && Number(literal[1]) <= MICRO_SPACING_CEILING_PX
109
+ })
110
+ }
111
+
71
112
  // display:flex/grid/inline-flex/inline-grid in an inline style.
72
113
  const INLINE_DISPLAY = /\bdisplay\s*:\s*['"](?:inline-)?(?:flex|grid)['"]/g
73
114
 
@@ -130,7 +171,21 @@ const SUB_16_FONT_SIZE = /font-?[Ss]ize\s*:\s*['"]?(-?\d+(?:\.\d+)?)(?:px)?['"]?
130
171
  // ── Defaults ─────────────────────────────────────────────────────────────────────────────────────
131
172
 
132
173
  /** Default spacing steps (px) flagged as raw spacing props. */
133
- const DEFAULT_SPACING_STEPS: readonly number[] = [10, 12, 16, 20, 32]
174
+ /**
175
+ * The `xs…xl` spacing scale, as raw numbers — what `raw-spacing` flags, because a prop value that
176
+ * EQUALS a step should be written as the token (`p="md"`, not `p={18}`).
177
+ *
178
+ * Mirrors `SPACE_SCALE` at level 0. Kept as a literal rather than imported from `tokens/palette` so
179
+ * the headless guard core stays a single file: it runs on every Write/Edit through the PreToolUse
180
+ * hook, and pulling the palette in would drag `derive.ts` + `hct.ts`'s color math along with it.
181
+ * `check-source.test.ts` asserts the two agree, so the copy cannot drift — which it did: this list
182
+ * still read `[10, 12, 16, 20, 32]` after the level-0 retune, telling consumers to replace `p={16}`
183
+ * with a `p="md"` that resolves to 18.
184
+ *
185
+ * A consumer whose theme moves the scale (`createBasaltTheme({ density })`, or its own overrides)
186
+ * sets `basalt.spacingSteps` in package.json rather than living with this default.
187
+ */
188
+ const DEFAULT_SPACING_STEPS: readonly number[] = [11, 13, 18, 20, 26]
134
189
  /** Default off-identity Mantine accent families. */
135
190
  const DEFAULT_FORBIDDEN_ACCENTS: readonly string[] = ['teal', 'violet', 'grape', 'indigo', 'pink']
136
191
 
@@ -635,7 +690,8 @@ export function checkSource(text: string, relPath: string, cfg: GuardConfig): Fi
635
690
  // the stripped text has already blanked out. Same length / same newline positions as `text`, so
636
691
  // line numbers computed off either one agree.
637
692
  const lines = text.split('\n')
638
- const codeText = stripComments(text, guardSyntaxFor(relPath))
693
+ const syntax = guardSyntaxFor(relPath)
694
+ const codeText = stripComments(text, syntax)
639
695
  const codeLines = codeText.split('\n')
640
696
 
641
697
  for (let i = 0; i < lines.length; i++) {
@@ -708,9 +764,10 @@ export function checkSource(text: string, relPath: string, cfg: GuardConfig): Fi
708
764
  findings.push({ relPath, line: i + 1, token: '<raw-html style>', kind: 'raw-html-layout' })
709
765
  }
710
766
 
711
- // inline-spacing — pattern + gating from GUARD_RULES.
767
+ // inline-spacing — pattern + gating from GUARD_RULES, plus the CSS-only sub-scale escape.
712
768
  if (GUARD_RULES['inline-spacing'].enabled!(cfg)) {
713
769
  for (const m of line.matchAll(GUARD_RULES['inline-spacing'].pattern as RegExp)) {
770
+ if (syntax === 'css' && isSubScaleCssSpacing(line, m.index)) continue
714
771
  findings.push({ relPath, line: i + 1, token: m[0], kind: 'inline-spacing' })
715
772
  }
716
773
  }
package/src/styles.css CHANGED
@@ -24,6 +24,11 @@
24
24
  /* Font stack — overridable via the --basalt-font-* custom properties. */
25
25
  @layer base {
26
26
  :root {
27
+ /* Hubot Sans is a condensed display face; the spec pins it at 88% wherever it lands. A knob
28
+ rather than a literal at the rule below, because that rule reaches BARE h1–h6: a consumer
29
+ that layers its own base type would otherwise have no way to keep its own heading width
30
+ short of out-specifying the framework. `normal` opts out entirely. */
31
+ --basalt-font-head-stretch: 88%;
27
32
  --basalt-font-sans:
28
33
  'Nunito Sans Variable', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto,
29
34
  Helvetica, Arial, sans-serif;
@@ -75,7 +80,9 @@
75
80
  }
76
81
 
77
82
  /* Hubot Sans is a condensed display face — the spec pins it at 88% font-stretch everywhere it
78
- lands (headings + the Mantine Title component). */
83
+ lands (headings + the Mantine Title component). Read from the knob declared above rather than
84
+ hardcoded here, so a consumer retunes it in one declaration instead of fighting these bare
85
+ element selectors with a more specific rule of their own. */
79
86
  h1,
80
87
  h2,
81
88
  h3,
@@ -83,7 +90,7 @@
83
90
  h5,
84
91
  h6,
85
92
  .mantine-Title-root {
86
- font-stretch: 88%;
93
+ font-stretch: var(--basalt-font-head-stretch, 88%);
87
94
  }
88
95
 
89
96
  /* Scrollbars (docs/DESIGN-SPEC.md §5): 9px, ink-mix thumb (stronger on hover), radius 6,
@@ -153,14 +160,18 @@
153
160
  .mantine-ScrollArea-scrollbar:active .mantine-ScrollArea-thumb {
154
161
  background-color: var(--basalt-scrollbar-thumb-hover);
155
162
  }
156
- }
157
163
 
158
- /* Print: hide the BasaltShell chrome so only page content prints.
159
- * AppShell.Navbar → <nav>, AppShell.Header → <header>, AppShell.Footer → <footer>. */
160
- @media print {
161
- nav,
162
- header,
163
- footer {
164
- display: none !important;
164
+ /* Print: hide the BasaltShell chrome so only page content prints.
165
+ Scoped to AppShell's own class hooks, NOT to bare nav/header/footer. The element form matched
166
+ any landmark on the page — a consumer with a real <nav> and no BasaltShell silently printed a
167
+ blank one, and being unlayered with `!important` there was nothing they could do about it
168
+ either. `@layer basalt` already outranks `@layer mantine`, so no `!important` is needed to win
169
+ against the AppShell's own display rules. */
170
+ @media print {
171
+ .mantine-AppShell-navbar,
172
+ .mantine-AppShell-header,
173
+ .mantine-AppShell-footer {
174
+ display: none;
175
+ }
165
176
  }
166
177
  }
package/src/surfaces.ts CHANGED
@@ -424,6 +424,13 @@ export const SURFACES = {
424
424
  'Mandatory CSS import (after the Mantine styles.layer.css bundles) — @layer basalt base styles, iOS input safety net, font stack',
425
425
  forbiddenImports: [],
426
426
  },
427
+ './tokens.css': {
428
+ kind: 'tooling',
429
+ layer: 'non-js-asset',
430
+ description:
431
+ 'Prebuilt --vx-* token stylesheet — the default buildPaletteCss() output as a plain file, for a consumer with no bundler, no React and no Mantine; retune the selector or trim the spacing set with `basalt-ui tokens:css`',
432
+ forbiddenImports: [],
433
+ },
427
434
  './configs/*': {
428
435
  kind: 'tooling',
429
436
  layer: 'non-js-asset',
@@ -488,6 +488,28 @@ function spaceDecls(space: SpaceValues): string[] {
488
488
  ]
489
489
  }
490
490
 
491
+ /**
492
+ * The `--vx-space-*` names that survive `only: 'core'` — DERIVED from the `SPACE` anchor keys, never
493
+ * hand-listed, so a new `SPACE_STEP` one-off is excluded the moment it is added and a renamed anchor
494
+ * follows automatically. `SPACE` is the generic ladder (the stack rhythm, the two control heights,
495
+ * the row insets); everything else `spaceDecls` emits is named for a basalt COMPONENT and is dead
496
+ * weight outside this framework — including `--vx-space-row-line-height`, which is the NavLink row's
497
+ * line-height rather than a general anchor and so is (deliberately) in neither set.
498
+ */
499
+ const CORE_SPACE_VARS = new Set(
500
+ Object.keys(SPACE).map((key) => `space-${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`),
501
+ )
502
+
503
+ /**
504
+ * Does this `spaceDecls` line declare a core anchor? The name is read back out of the emitted line
505
+ * because {@link decl} is the single formatter for every one of them — the shape is fixed at one
506
+ * call site, so parsing it cannot drift, whereas tagging 104 declarations by hand could.
507
+ */
508
+ function isCoreSpaceDecl(line: string): boolean {
509
+ const name = /^ {2}--vx-([\w-]+):/.exec(line)?.[1]
510
+ return name !== undefined && CORE_SPACE_VARS.has(name)
511
+ }
512
+
491
513
  /** The shipped, level-0 spacing values — `frameworkDerived`'s `spaceDecls(...)` call below. No
492
514
  * `createBasaltTheme({ density })` retuning applies here; that path calls `buildDensityCss` with a
493
515
  * different resolved {@link SpaceValues} instead (see `../theme` and `../provider`). */
@@ -504,7 +526,8 @@ const DEFAULT_SPACE_VALUES: SpaceValues = {
504
526
  * Area-gradient strength is a global knob (the theme lab overrides these two on `:root`
505
527
  * to retune every line-area fill live). 0%/0% disables gradients app-wide.
506
528
  */
507
- function frameworkDerived(data: PaletteData): string {
529
+ function frameworkDerived(data: PaletteData, only: 'core' | 'all'): string {
530
+ const space = spaceDecls(DEFAULT_SPACE_VALUES)
508
531
  return [
509
532
  decl('radius-card', `${RADIUS.card}px`),
510
533
  decl('radius-ctrl', `${RADIUS.ctrl}px`),
@@ -519,7 +542,7 @@ function frameworkDerived(data: PaletteData): string {
519
542
  // only in this static block, never in `buildRadiusCss`'s dynamic override (see
520
543
  // `RADIUS_STEP.pill`'s doc).
521
544
  decl('radius-pill', `${RADIUS_STEP.pill}px`),
522
- ...spaceDecls(DEFAULT_SPACE_VALUES),
545
+ ...(only === 'core' ? space.filter(isCoreSpaceDecl) : space),
523
546
  // Article-density Prose measure (docs/CONTENT-SPEC.md §5) — theme-independent, like the radii.
524
547
  decl('prose-measure', '72ch'),
525
548
  // The fill band (see FILL in palette.ts). Emitted on `:root`, NOT per scheme — a filled surface
@@ -585,14 +608,89 @@ export function groupTokens<const T extends SeriesMap>(
585
608
  return seriesTokens(map, `${name}-`)
586
609
  }
587
610
 
611
+ /**
612
+ * The attribute + values the per-scheme blocks key off. Defaults reproduce Mantine's own toggle
613
+ * (`data-mantine-color-scheme` = `dark` / `light`), so a consumer only names the axis it differs
614
+ * on. Supplying this object at all switches the emitter onto the framework-neutral selector shape
615
+ * — see {@link BuildPaletteOpts.scheme}.
616
+ */
617
+ export type ColorSchemeSelector = {
618
+ attribute?: string
619
+ darkValue?: string
620
+ lightValue?: string
621
+ }
622
+
588
623
  /** Options for {@link buildPaletteCss}. */
589
624
  export type BuildPaletteOpts = {
590
625
  /** Extra named series maps to emit under the given prefixes (e.g. `{ '': SERIES, 'activity-': ACTIVITY }`). */
591
626
  groups?: Record<string, SeriesMap>
592
627
  /** Theme-independent derived declarations (gradients, semantic fills) emitted once on `:root`. */
593
628
  derived?: string[]
629
+ /**
630
+ * Attribute + values the per-scheme blocks key off — for a consumer whose scheme toggle is not
631
+ * Mantine's (a static site on `data-theme`, say). Default: Mantine's own
632
+ * `data-mantine-color-scheme` = `dark` / `light`.
633
+ *
634
+ * Setting ANY of `scheme` / `defaultScheme` / `mediaFallback` moves the emitter off the legacy
635
+ * `html[…]` selector onto `:root[…]`. That is deliberate and load-bearing, NOT cosmetic:
636
+ *
637
+ * `:root[data-theme='dark']` 0-2-0 ← what this path emits
638
+ * `html[data-theme='dark']` 0-1-1
639
+ * `[data-theme='dark']` 0-1-0 ← same as a bare `:root`, so source order decides
640
+ *
641
+ * A light-default site whose own `:root` block happens to come last would beat the third form
642
+ * outright — dark mode silently does nothing. `:root[…]` sits above both a bare `:root` and
643
+ * `html[…]`, and carries no assumption about the element the attribute lands on.
644
+ *
645
+ * The no-options path keeps emitting `html[data-mantine-color-scheme='…']` verbatim, because a
646
+ * basalt consumer may already override `--vx-*` under that exact selector — raising basalt's own
647
+ * specificity would silently win over their override.
648
+ */
649
+ scheme?: ColorSchemeSelector
650
+ /**
651
+ * Which scheme rides along on the bare `:root` block — the one that applies when the attribute
652
+ * is absent. Default: `'dark'` (the framework's own default scheme).
653
+ *
654
+ * `'none'` emits no bare-`:root` primitives at all: each scheme gets only its attribute block,
655
+ * and an unattributed document falls back to the theme-independent scalars alone. Pair it with
656
+ * `mediaFallback` unless the consumer always sets the attribute.
657
+ */
658
+ defaultScheme?: 'dark' | 'light' | 'none'
659
+ /**
660
+ * Also emit an `@media (prefers-color-scheme: …)` block for every scheme that is not the bare
661
+ * `:root` default, so a document with no attribute set follows the OS. Default: `false`.
662
+ *
663
+ * The block is a bare `:root` (0-1-0), so an explicit attribute block (0-2-0) always wins over
664
+ * it regardless of source order — the OS preference is a fallback, never an override.
665
+ */
666
+ mediaFallback?: boolean
667
+ /**
668
+ * How much of the SPACING set to emit. Default: `'all'` (every one of the 104 `--vx-space-*`
669
+ * declarations the framework's own components read).
670
+ *
671
+ * `'core'` keeps the 9 generic anchors — the stack rhythm, the two control heights, the row
672
+ * insets — and drops the 95 named for a specific basalt component
673
+ * (`--vx-space-agent-transcript-inset`, `--vx-space-toc-sub-indent`, …), taking the emitted set
674
+ * from 197 variables to 102. Nothing outside basalt's own React components reads those, so a
675
+ * framework-free consumer is carrying them for nothing.
676
+ *
677
+ * This is a SPACING filter only: color, radius, shadow, type and status variables are identical
678
+ * in both modes. The partition is derived from the `SPACE` key set rather than a maintained list
679
+ * — see {@link CORE_SPACE_VARS}.
680
+ */
681
+ only?: 'core' | 'all'
594
682
  }
595
683
 
684
+ /** Mantine's own color-scheme attribute — the default {@link ColorSchemeSelector.attribute}. */
685
+ const MANTINE_SCHEME_ATTRIBUTE = 'data-mantine-color-scheme'
686
+
687
+ /** Indent an already-2-space-indented declaration block one level deeper (for `@media` nesting). */
688
+ const indent = (block: string): string =>
689
+ block
690
+ .split('\n')
691
+ .map((line) => (line === '' ? line : ` ${line}`))
692
+ .join('\n')
693
+
596
694
  /**
597
695
  * Emit the `--vx-*` stylesheet: a `:root` block of theme-independent scalars, then the
598
696
  * dark (default) and light primitive blocks under `html[data-mantine-color-scheme='…']`.
@@ -608,6 +706,14 @@ export type BuildPaletteOpts = {
608
706
  *
609
707
  * Dark is the default (`:root`) since the framework defaults to dark; the
610
708
  * `[data-mantine-color-scheme]` selectors track Mantine's toggle on `<html>`.
709
+ *
710
+ * A non-Mantine consumer retargets all three of those choices — the attribute, which scheme rides
711
+ * the bare `:root`, and whether the OS preference is honoured — via `opts.scheme` /
712
+ * `opts.defaultScheme` / `opts.mediaFallback`. Setting any of them also moves the per-scheme
713
+ * selector from `html[…]` to the framework-neutral, higher-specificity `:root[…]`; see
714
+ * `BuildPaletteOpts.scheme` for why that is not cosmetic. With none of them set the output is
715
+ * byte-identical to what the framework has always emitted (pinned by
716
+ * `tests/palette-css.test.ts`).
611
717
  */
612
718
  export function buildPaletteCss(
613
719
  opts: BuildPaletteOpts = {},
@@ -615,7 +721,7 @@ export function buildPaletteCss(
615
721
  ): string {
616
722
  const groups = opts.groups ?? {}
617
723
  const extraDerived = (opts.derived ?? []).map((d) => ` ${d}`).join('\n')
618
- const derivedBlock = frameworkDerived(data)
724
+ const derivedBlock = frameworkDerived(data, opts.only ?? 'all')
619
725
  const derived = extraDerived ? `${derivedBlock}\n${extraDerived}` : derivedBlock
620
726
  const side = (s: Side): string => {
621
727
  const extra = Object.entries(groups)
@@ -624,9 +730,11 @@ export function buildPaletteCss(
624
730
  const framework = frameworkPrimitives(s, data)
625
731
  return extra ? `${framework}\n${extra}` : framework
626
732
  }
627
- return `:root {
628
- ${derived}
629
- }
733
+ const rootBlock = `:root {\n${derived}\n}`
734
+
735
+ // The legacy shape — kept verbatim, and only reachable when the caller asked for nothing.
736
+ if (opts.scheme === undefined && opts.defaultScheme === undefined && !opts.mediaFallback) {
737
+ return `${rootBlock}
630
738
  :root,
631
739
  html[data-mantine-color-scheme='dark'] {
632
740
  ${side('dark')}
@@ -634,6 +742,34 @@ ${side('dark')}
634
742
  html[data-mantine-color-scheme='light'] {
635
743
  ${side('light')}
636
744
  }`
745
+ }
746
+
747
+ const attribute = opts.scheme?.attribute ?? MANTINE_SCHEME_ATTRIBUTE
748
+ const value: Record<Side, string> = {
749
+ dark: opts.scheme?.darkValue ?? 'dark',
750
+ light: opts.scheme?.lightValue ?? 'light',
751
+ }
752
+ const defaultScheme = opts.defaultScheme ?? 'dark'
753
+ // Default scheme first, so its attribute block can absorb the bare `:root` instead of repeating
754
+ // ~40 declarations; `'none'` keeps the framework's dark-then-light order.
755
+ const order: Side[] = defaultScheme === 'light' ? ['light', 'dark'] : ['dark', 'light']
756
+
757
+ const blocks = [rootBlock]
758
+ for (const s of order) {
759
+ const selector =
760
+ s === defaultScheme
761
+ ? `:root,\n:root[${attribute}='${value[s]}']`
762
+ : `:root[${attribute}='${value[s]}']`
763
+ // The OS fallback for a scheme goes immediately before that scheme's own attribute block. It is
764
+ // a bare `:root` (0-1-0), so the attribute block (0-2-0) outranks it on specificity rather than
765
+ // on order — an explicit toggle always beats the OS preference, and the OS preference always
766
+ // beats the hardcoded default that a bare `:root` above it carries.
767
+ if (opts.mediaFallback === true && s !== defaultScheme) {
768
+ blocks.push(`@media (prefers-color-scheme: ${s}) {\n :root {\n${indent(side(s))}\n }\n}`)
769
+ }
770
+ blocks.push(`${selector} {\n${side(s)}\n}`)
771
+ }
772
+ return blocks.join('\n')
637
773
  }
638
774
 
639
775
  /**