@tenphi/tasty 0.0.0-snapshot.047dfbb → 0.0.0-snapshot.04fb534

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 (134) hide show
  1. package/README.md +452 -370
  2. package/dist/babel-types-Dc5zghyE.d.ts +18 -0
  3. package/dist/chunks/async-storage-f9j9JRtq.js +37 -0
  4. package/dist/chunks/async-storage-f9j9JRtq.js.map +1 -0
  5. package/dist/chunks/build-config--0qoqt_P.js +60 -0
  6. package/dist/chunks/build-config--0qoqt_P.js.map +1 -0
  7. package/dist/{collector-J6LwZR0N.js → chunks/collector-zp5BrLF0.js} +68 -101
  8. package/dist/chunks/collector-zp5BrLF0.js.map +1 -0
  9. package/dist/chunks/config-engine-BaLq8HrX.js +272 -0
  10. package/dist/chunks/config-engine-BaLq8HrX.js.map +1 -0
  11. package/dist/chunks/config-file-DlZXJMj8.js +25 -0
  12. package/dist/chunks/config-file-DlZXJMj8.js.map +1 -0
  13. package/dist/chunks/css-definitions-CfXZ3tU9.js +910 -0
  14. package/dist/chunks/css-definitions-CfXZ3tU9.js.map +1 -0
  15. package/dist/chunks/css-resources-P7IBUUZs.js +142 -0
  16. package/dist/chunks/css-resources-P7IBUUZs.js.map +1 -0
  17. package/dist/chunks/debug--OC-WA-Q.js +502 -0
  18. package/dist/chunks/debug--OC-WA-Q.js.map +1 -0
  19. package/dist/chunks/dsl-CsFl9LGn.js +1458 -0
  20. package/dist/chunks/dsl-CsFl9LGn.js.map +1 -0
  21. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  22. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  23. package/dist/chunks/react-runtime-DnZ6M1Iv.js +691 -0
  24. package/dist/chunks/react-runtime-DnZ6M1Iv.js.map +1 -0
  25. package/dist/chunks/runtime-engine-J9X_h-Pw.js +2435 -0
  26. package/dist/chunks/runtime-engine-J9X_h-Pw.js.map +1 -0
  27. package/dist/chunks/runtime-state-o_v3Bj7b.js +152 -0
  28. package/dist/chunks/runtime-state-o_v3Bj7b.js.map +1 -0
  29. package/dist/{merge-styles-CAdKaHxh.js → chunks/shared-utils-y-HjvPN4.js} +60 -55
  30. package/dist/chunks/shared-utils-y-HjvPN4.js.map +1 -0
  31. package/dist/chunks/style-engine-D6lC3O3G.js +5626 -0
  32. package/dist/chunks/style-engine-D6lC3O3G.js.map +1 -0
  33. package/dist/{css-writer-IC7tdnIf.js → chunks/zero-engine-BnjoV04F.js} +95 -136
  34. package/dist/chunks/zero-engine-BnjoV04F.js.map +1 -0
  35. package/dist/{collector-CddJZDOr.d.ts → collector-D2OT6I2G.d.ts} +64 -8
  36. package/dist/{config-C3SKYuxY.d.ts → config-C4ftFxgI.d.ts} +514 -92
  37. package/dist/core/index.d.ts +5 -5
  38. package/dist/core/index.js +9 -6
  39. package/dist/hydrate-CRyjjAyl.d.ts +22 -0
  40. package/dist/{index-ByBYTH9l.d.ts → index-DxQNRj50.d.ts} +586 -400
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +11 -732
  43. package/dist/{merge-styles-CvUi7SOD.d.ts → merge-styles-D39qBtox.d.ts} +2 -3
  44. package/dist/ssr/astro-client.d.ts +1 -1
  45. package/dist/ssr/astro-client.js +1 -14
  46. package/dist/ssr/astro-client.js.map +1 -1
  47. package/dist/ssr/astro-middleware-extract-static.d.ts +10 -0
  48. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  49. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  50. package/dist/ssr/astro-middleware-extract.d.ts +10 -0
  51. package/dist/ssr/astro-middleware-extract.js +9 -0
  52. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  53. package/dist/ssr/astro-middleware-static.d.ts +17 -0
  54. package/dist/ssr/astro-middleware-static.js +7 -0
  55. package/dist/ssr/astro-middleware-static.js.map +1 -0
  56. package/dist/ssr/astro-middleware.d.ts +11 -8
  57. package/dist/ssr/astro-middleware.js +2 -14
  58. package/dist/ssr/astro-middleware.js.map +1 -1
  59. package/dist/ssr/astro.d.ts +40 -10
  60. package/dist/ssr/astro.js +160 -86
  61. package/dist/ssr/astro.js.map +1 -1
  62. package/dist/ssr/client.d.ts +2 -0
  63. package/dist/ssr/client.js +2 -0
  64. package/dist/ssr/index.d.ts +5 -32
  65. package/dist/ssr/index.js +6 -6
  66. package/dist/ssr/index.js.map +1 -1
  67. package/dist/ssr/next-config.d.ts +64 -0
  68. package/dist/ssr/next-config.js +123 -0
  69. package/dist/ssr/next-config.js.map +1 -0
  70. package/dist/ssr/next.d.ts +9 -8
  71. package/dist/ssr/next.js +29 -44
  72. package/dist/ssr/next.js.map +1 -1
  73. package/dist/static/index.d.ts +8 -9
  74. package/dist/static/index.js +4 -22
  75. package/dist/static/index.js.map +1 -1
  76. package/dist/static/inject.d.ts +1 -2
  77. package/dist/{index-C5owZ15q.d.ts → types-CYQIhUg1.d.ts} +874 -598
  78. package/dist/zero/babel.d.ts +12 -19
  79. package/dist/zero/babel.js +97 -156
  80. package/dist/zero/babel.js.map +1 -1
  81. package/dist/zero/index.d.ts +76 -7
  82. package/dist/zero/index.js +25 -2
  83. package/dist/zero/index.js.map +1 -0
  84. package/dist/zero/next.d.ts +4 -5
  85. package/dist/zero/next.js +3 -38
  86. package/dist/zero/next.js.map +1 -1
  87. package/docs/README.md +20 -9
  88. package/docs/adoption.md +69 -36
  89. package/docs/ai-agents.md +259 -0
  90. package/docs/comparison.md +77 -47
  91. package/docs/configuration.md +617 -98
  92. package/docs/debug.md +28 -15
  93. package/docs/design-system.md +166 -33
  94. package/docs/dsl.md +637 -205
  95. package/docs/getting-started.md +130 -50
  96. package/docs/injector.md +160 -69
  97. package/docs/llms.txt +31 -0
  98. package/docs/methodology.md +82 -51
  99. package/docs/migration-v3.md +285 -0
  100. package/docs/pipeline.md +57 -33
  101. package/docs/plugins.md +333 -0
  102. package/docs/react-api.md +215 -50
  103. package/docs/runtime-benchmarks.md +388 -0
  104. package/docs/ssr.md +310 -118
  105. package/docs/styles.md +209 -41
  106. package/docs/tasty-static.md +289 -136
  107. package/harness/dev.harnesspm/rules/usage.md +12 -0
  108. package/harness/dev.harnesspm/scripts/render.mjs +441 -0
  109. package/harness/dev.harnesspm/scripts/styles.mjs +412 -0
  110. package/harness/plugin.json +20 -0
  111. package/package.json +148 -49
  112. package/tasty.config.ts +5 -0
  113. package/dist/async-storage-DKK-wTD4.js +0 -44
  114. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  115. package/dist/collector-J6LwZR0N.js.map +0 -1
  116. package/dist/config-C3F4Ogo1.js +0 -10993
  117. package/dist/config-C3F4Ogo1.js.map +0 -1
  118. package/dist/context-CA8YKeMn.js +0 -24
  119. package/dist/context-CA8YKeMn.js.map +0 -1
  120. package/dist/core-DxHmF6S9.js +0 -1598
  121. package/dist/core-DxHmF6S9.js.map +0 -1
  122. package/dist/css-writer-IC7tdnIf.js.map +0 -1
  123. package/dist/format-global-rules-DklyaXv-.js +0 -22
  124. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  125. package/dist/format-rules-DTLY39Hm.js +0 -143
  126. package/dist/format-rules-DTLY39Hm.js.map +0 -1
  127. package/dist/hydrate-8Zglgy_C.js +0 -45
  128. package/dist/hydrate-8Zglgy_C.js.map +0 -1
  129. package/dist/index.js.map +0 -1
  130. package/dist/keyframes-DgGkipNK.js +0 -595
  131. package/dist/keyframes-DgGkipNK.js.map +0 -1
  132. package/dist/merge-styles-CAdKaHxh.js.map +0 -1
  133. package/dist/resolve-recipes-BQNdunBd.js +0 -144
  134. package/dist/resolve-recipes-BQNdunBd.js.map +0 -1
@@ -1,6 +1,8 @@
1
1
  # Configuration
2
2
 
3
- Configure the Tasty style system before your app renders using the `configure()` function. Configuration must be done **before any styles are generated** (before first render). For a higher-level docs map, see the [Docs Hub](README.md).
3
+ Tasty works without upfront configuration. Use `configure()` when your app or design system is ready to define shared tokens, state aliases, units, recipes, presets, or extension points.
4
+
5
+ Call it **before any styles are generated** (before first render). For a guided setup, see [Getting Started](getting-started.md). For the higher-level docs map, see the [Docs Hub](README.md).
4
6
 
5
7
  ```jsx
6
8
  import { configure } from '@tenphi/tasty';
@@ -21,17 +23,19 @@ configure({
21
23
 
22
24
  // Custom units (merged with built-in units)
23
25
  units: {
24
- vh: 'vh',
25
- vw: 'vw',
26
- custom: (n) => `${n * 10}px`, // Function-based unit
26
+ gu: '4px', // `2gu` → `8px`
27
+ cols: (n) => `calc(${n} * var(--col-width))`, // function-based unit
27
28
  },
28
29
 
29
- // Custom functions for the parser
30
- funcs: {
30
+ // Custom functions — a single map for both flavors, discriminated by value type:
31
+ functions: {
32
+ // Bare key + function value → parse-time function, called as `double(...)`
31
33
  double: (groups) => {
32
34
  const value = parseFloat(groups[0]?.output || '0');
33
35
  return `${value * 2}px`;
34
36
  },
37
+ // `$$name` key + object value → declarative CSS @function, called as `$$negative(...)`
38
+ $$negative: { args: ['$value'], result: '(-1 * $value)' },
35
39
  },
36
40
  });
37
41
  ```
@@ -42,52 +46,246 @@ These docs use `data-schema="dark"` in examples. If your app already standardize
42
46
 
43
47
  ## Options
44
48
 
45
- | Option | Type | Default | Description |
46
- |--------|------|---------|-------------|
47
- | `nonce` | `string` | - | CSP nonce for style elements |
48
- | `states` | `Record<string, string>` | - | Global state aliases for advanced state mapping |
49
- | `parserCacheSize` | `number` | `1000` | Parser LRU cache size |
50
- | `units` | `Record<string, string \| Function>` | Built-in | Custom units (merged with built-in). See [built-in units](dsl.md#built-in-units) |
51
- | `funcs` | `Record<string, Function>` | - | Custom parser functions (merged with existing) |
52
- | `handlers` | `Record<string, StyleHandlerDefinition>` | Built-in | Custom style handlers (replace built-in) |
53
- | `tokens` | `Record<string, value \| stateMap>` | - | Design tokens injected as `:root` CSS custom properties |
54
- | `replaceTokens` | `Record<string, string \| number>` | - | Parse-time token substitution (inline replacement) |
55
- | `keyframes` | `Record<string, KeyframesSteps>` | - | Global keyframes for animations |
56
- | `properties` | `Record<string, PropertyDefinition>` | - | Global CSS @property definitions |
57
- | `fontFace` | `Record<string, FontFaceInput>` | - | Global @font-face definitions |
58
- | `counterStyle` | `Record<string, CounterStyleDescriptors>` | - | Global @counter-style definitions |
59
- | `autoPropertyTypes` | `boolean` | `true` | Auto-infer and register `@property` types from values |
60
- | `recipes` | `Record<string, RecipeStyles>` | - | Predefined style recipes (named style bundles) |
61
- | `presets` | `Record<string, TypographyPreset>` | - | Typography presets — shorthand for `generateTypographyTokens()` |
62
- | `globalStyles` | `Record<string, Styles>` | - | Global Tasty styles keyed by CSS selector |
63
- | `colorSpace` | `'rgb' \| 'hsl' \| 'oklch'` | `'oklch'` | Color space for decomposed color token companion variables |
64
- | `namePrefix` | `string` | `'t'` (runtime) / `'ts'` (zero-runtime) | Prefix prepended to every generated identifier (class, keyframe, counter-style names). See [Name prefix](#name-prefix). |
49
+ | Option | Type | Default | Description |
50
+ | -------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
+ | `nonce` | `string` | - | CSP nonce for style elements |
52
+ | `maxRulesPerSheet` | `number` | `8192` | Maximum rules per injected stylesheet |
53
+ | `forceTextInjection` | `boolean` | `false` (`true` in test environments only while `configure()` has never been called) | Force text-node CSS injection instead of constructable stylesheets. Set it explicitly in test setup |
54
+ | `devMode` | `boolean` | auto | Enable development-mode features: performance metrics and debug info. Does not turn on dev warnings; those follow `NODE_ENV` (or `localStorage.TASTY_DEBUG = 'true'` in a browser) |
55
+ | `states` | `Record<string, string>` | - | Global state aliases for advanced state mapping |
56
+ | `parserCacheSize` | `number` | `1000` | Parser LRU cache size |
57
+ | `units` | `Record<string, string \| UnitHandler>` | Built-in | Custom units (merged with built-in). See [built-in units](dsl.md#built-in-units) |
58
+ | `functions` | `Record<string, FunctionDefinition \| Function>` | - | Custom functions (merged). Bare keys → parse functions; `$$name` keys → declarative CSS `@function` definitions |
59
+ | `handlers` | `Record<string, StyleHandlerDefinition>` | Built-in | Custom style handlers (replace built-in). See [Custom Style Handlers](#custom-style-handlers) |
60
+ | `propHandlers` | `Record<string, PropHandlerDefinition>` | - | Props middleware for every component — props in, props out. See [Props Middleware](#props-middleware) |
61
+ | `baseStyleProps` | `readonly string[]` | - | Style names exposed as props on **every** component. See [Base Style Props](#base-style-props) |
62
+ | `tokens` | `Record<string, value \| stateMap>` | - | Design tokens injected as `:root` CSS custom properties |
63
+ | `replaceTokens` | `Record<string, string \| number \| boolean>` | `{ '#clear': 'transparent' }` | Parse-time token substitution (inline replacement). `boolean` is allowed for `#` color tokens |
64
+ | `keyframes` | `Record<string, KeyframesSteps>` | - | Global keyframes for animations |
65
+ | `properties` | `Record<string, PropertyDefinition>` | - | Global CSS @property definitions |
66
+ | `fontFaces` | `Record<string, FontFaceInput>` | - | Global @font-face definitions |
67
+ | `counterStyles` | `Record<string, CounterStyleDescriptors>` | - | Global @counter-style definitions |
68
+ | `polyfills` | `{ functions?: boolean }` | `{}` | Opt-in polyfills for not-yet-baseline features. `functions: true` inlines `@function` calls into plain CSS at parse time |
69
+ | `autoPropertyTypes` | `boolean` | `true` | Auto-infer and register `@property` types from values |
70
+ | `recipes` | `Record<string, RecipeStyles>` | - | Predefined style recipes (named style bundles) |
71
+ | `presets` | `Record<string, TypographyPreset>` | - | Typography presets — shorthand for `generateTypographyTokens()` |
72
+ | `globalStyles` | `Record<string, Styles>` | - | Global Tasty styles keyed by CSS selector |
73
+ | `plugins` | `TastyPlugin[]` | - | Plugins that bundle `functions`, `units`, `states`, `handlers`, `propHandlers`, `baseStyleProps`, `tokens`, `replaceTokens`, `recipes`, `presets`, `globalStyles`, `properties`, `keyframes`, `fontFaces`, and `counterStyles` (processed in order; later override earlier, and direct config wins over all). See [Plugins](plugins.md) |
74
+ | `gc` | `GCConfig` | - | Turns on automatic collection of unused styles: `{ touchInterval?, capacity?, grace? }` (defaults `1000`, `1000`, `10000` ms). Without it nothing is collected automatically; call `gc()` yourself |
75
+ | `batchInjection` | `boolean \| 'always'` | `false` | Defer stylesheet writes and apply them in one batch. See [Batched injection](#batched-injection) |
76
+ | `colorSpace` | `'rgb' \| 'hsl' \| 'oklch'` | - | **Deprecated** — no longer has any effect. See [Color space](#color-space) |
77
+ | `namePrefix` | `string` | `'t'` (`tasty`) / `'ts'` (build-time) | Prefix prepended to every generated identifier (class, keyframe, counter-style names). Must match `^[a-zA-Z_][a-zA-Z0-9_-]{0,31}$`. See [Name prefix](#name-prefix). |
78
+
79
+ ---
80
+
81
+ ## Batched Injection
82
+
83
+ Every `insertRule()` on a live stylesheet invalidates style for that sheet's
84
+ scope. Components inject during React's render phase, and if anything else reads
85
+ layout in the same pass, the two interleave:
86
+
87
+ ```
88
+ inject -> read (forced style recalc) -> inject -> read (forced recalc) -> ...
89
+ ```
90
+
91
+ A UI kit that measures during render — popovers, autosizing inputs, virtualized
92
+ lists — can turn one mount into a dozen full-tree recalculations. `batchInjection`
93
+ queues the writes instead and applies them together, so the tree is invalidated
94
+ once per flush.
95
+
96
+ ```tsx
97
+ import { configure, TastyBatchProvider } from '@tenphi/tasty';
98
+
99
+ configure({ batchInjection: true });
100
+
101
+ createRoot(el).render(
102
+ <TastyBatchProvider>
103
+ <App />
104
+ </TastyBatchProvider>,
105
+ );
106
+ ```
107
+
108
+ ### Why the provider is required
109
+
110
+ Deferring a write past React's layout phase would let a `useLayoutEffect`
111
+ measure an element whose rules are not in the sheet yet and read its _unstyled_
112
+ box — a wrong number, not a stale one, so it never self-corrects.
113
+
114
+ `TastyBatchProvider` closes that hole. It opens a _batch window_ during its
115
+ render and closes it — flushing — in `useInsertionEffect`, which React runs in
116
+ the mutation phase, before any layout effect:
117
+
118
+ ```
119
+ provider renders -> window OPEN
120
+ children render -> injections queued
121
+ provider insertionEffect -> FLUSH, window CLOSED
122
+ layout effects run -> rules are in the sheet
123
+ ```
124
+
125
+ With `batchInjection: true` a write is only ever queued inside such a window, so
126
+ turning the flag on can make injection cheaper but can never make a measurement
127
+ wrong. Injections outside a window are written straight through, exactly as with
128
+ batching off:
129
+
130
+ - a deep update that did not re-render the provider
131
+ - an injection from a layout effect, an event handler or an async callback
132
+ - SSR and RSC, where there is no live sheet at all
133
+
134
+ Mount the provider as high in the tree as you can: batching applies to the
135
+ commits it takes part in.
136
+
137
+ ### Modes
138
+
139
+ | Value | Behaviour |
140
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
141
+ | `false` (default) | One `insertRule()` per component, synchronously. |
142
+ | `true` | Batch inside a provider window only. Cannot affect measurement. Without the provider nothing is batched, and dev mode says so once. |
143
+ | `'always'` | Batch every injection, flushing on a microtask when no window is open. Covers more commits; a `useLayoutEffect` measuring a freshly mounted element can read its unstyled box. Paint is unaffected — microtasks always drain before the browser paints. |
144
+
145
+ ### Ordering
146
+
147
+ All writes share one FIFO queue — component rules, global rules, raw CSS,
148
+ `@property`, `@keyframes`, `@font-face`, `@counter-style` and `@function`.
149
+ Draining it in insertion order keeps the sheet byte-identical to unbatched
150
+ output, which matters because equal-specificity rules resolve by document order.
151
+
152
+ ### Client rendering, server rendering, and build-time extraction
153
+
154
+ **Server render — nothing to batch, safe to leave enabled.** SSR and RSC collect
155
+ CSS as text through `ServerStyleCollector`; the runtime injector never runs
156
+ there, so `batchInjection` changes nothing either way. `<TastyBatchProvider>`
157
+ renders its children and does nothing else: the window it opens is a no-op
158
+ without a `document`, and the `useInsertionEffect` that would close it never
159
+ fires on the server. Configure the flag once in shared code — no environment
160
+ branching needed.
161
+
162
+ **Hydration — the better your SSR coverage, the less there is to batch.**
163
+ `hydrateTastyClasses()` (wired up for you by `@tenphi/tasty/ssr/next` and the
164
+ Astro integration) pre-populates the injector from `window.__TASTY__`, so
165
+ hydrating a server-rendered class is a cache hit that produces no sheet write at
166
+ all. Batching pays off on what SSR could not cover: client-only routes, styles
167
+ that first appear after hydration (a `styles` prop that changes on interaction, a
168
+ modal or popover mounting), and dynamic tokens.
169
+
170
+ **Astro islands — one provider per island, or `'always'`.** Every island is its
171
+ own React root, so a provider inside one island does not open a window for
172
+ another. With `batchInjection: true`, wrap each island root that renders enough
173
+ tasty components to be worth it. `'always'` needs no provider and covers every
174
+ island, at the cost of the measurement hazard above. Either way, an island that
175
+ only re-hydrates server-rendered classes has nothing to batch.
176
+
177
+ **Build-time extraction (`tastyStatic`) — unaffected.** The Babel plugin never
178
+ touches the injector: the babel plugin emits either a CSS file import or an
179
+ `injectCSS()` call from `@tenphi/tasty/static/inject`, which appends text to a
180
+ single `<style data-tasty-static>` element. `batchInjection` only defers CSSOM
181
+ writes made by the browser injector, so extracted styles are unchanged. In an app
182
+ that mixes both, it still applies to the `tasty()` half.
183
+
184
+ ### `flushStyles()`
185
+
186
+ Applies every pending write immediately. Every injector read API calls it for
187
+ you — `getCSSText`, `getCSSTextForClasses`, `getCSSTextForNode`,
188
+ `getRawCSSText`, `isPropertyDefined`, `getMetrics`, `cleanup`, `gc` and
189
+ `destroy` — so a read never observes a partial sheet.
190
+ Call it directly before measuring in code that runs outside a batch window under
191
+ `'always'`:
192
+
193
+ ```tsx
194
+ import { flushStyles } from '@tenphi/tasty';
195
+
196
+ useLayoutEffect(() => {
197
+ flushStyles();
198
+ const { width } = ref.current.getBoundingClientRect();
199
+ }, []);
200
+ ```
201
+
202
+ `hasPendingStyleWrites()` reports whether anything is queued, and
203
+ `resetStyleBatch()` drops the queue without applying it (tests only).
65
204
 
66
205
  ---
67
206
 
68
207
  ## Color Space
69
208
 
70
- Controls the CSS color space used for decomposed color token companion variables. When you define `#name` color tokens, tasty generates both `--name-color` (full color) and `--name-color-{suffix}` (decomposed components for alpha composition).
209
+ > **Deprecated.** `configure({ colorSpace })` no longer has any effect and will
210
+ > be removed in the next major. Setting it warns in development.
211
+
212
+ A `#name` token's value used to be rewritten into a configured color space, so
213
+ `#brand: '#ff8800'` declared `--brand-color: oklch(0.75 0.16 55)`. That existed
214
+ to serve the opacity suffix, which needed numeric channels to write an alpha
215
+ into. Opacity now mixes the token with `transparent` —
216
+ `color-mix(in oklab, var(--brand-color) 50%, transparent)` — which the browser
217
+ resolves against any color, so there is nothing left for the setting to decide.
218
+
219
+ A color is emitted exactly as authored:
71
220
 
72
221
  ```jsx
73
- configure({
74
- colorSpace: 'oklch', // default
75
- });
222
+ configure({ tokens: { '#brand': '#ff8800' } });
223
+ // → --brand-color: #ff8800
76
224
  ```
77
225
 
78
- | Color Space | Suffix | Components Format | Alpha Syntax |
79
- |---|---|---|---|
80
- | `rgb` | `-rgb` | `255 128 0` | `rgb(var(--name-color-rgb) / .5)` |
81
- | `hsl` | `-hsl` | `300 100% 25%` | `hsl(var(--name-color-hsl) / .5)` |
82
- | `oklch` | `-oklch` | `0.42 0.16 328` | `oklch(var(--name-color-oklch) / .5)` |
226
+ That holds for every form: a hex literal, a native color function, a bare CSS
227
+ color name, a `color-mix()`, a `light-dark()`, a fallback chain. A `#token`
228
+ reference still resolves to its `var()` chain, and a plugin color function such
229
+ as `okhsl()` is still resolved by the parser to the color it denotes.
230
+
231
+ To address a token's channels, use relative color syntax against the token:
232
+
233
+ ```css
234
+ background: oklch(from var(--brand-color) calc(l * 1.2) c h);
235
+ ```
236
+
237
+ This works on any `<color>`, including the ones no build-time conversion could
238
+ have evaluated, and `oklch` is unbounded, so a wide-gamut color survives a round
239
+ trip a narrower space would clamp. Relative color syntax is Baseline 2024 (Chrome
240
+ 125, Firefox 128, Safari 18), so the [opacity suffix](dsl.md#color-tokens--opacity)
241
+ uses the widely available `color-mix()` instead.
242
+
243
+ ### Migrating off `colorSpace`
244
+
245
+ Drop the option. If you relied on the uniform output format, nothing in Tasty
246
+ needs it — author your tokens in the space you want them emitted in, since the
247
+ value now passes through untouched:
248
+
249
+ ```jsx
250
+ // before: any input, normalized to the configured space on the way out
251
+ configure({ colorSpace: 'oklch', tokens: { '#brand': '#ff8800' } });
252
+
253
+ // after: author it in the space you want
254
+ configure({ tokens: { '#brand': 'oklch(0.75 0.16 55)' } });
255
+ ```
256
+
257
+ ### Migrating off the channel companions
258
+
259
+ A `#name` token used to declare a second variable beside `--name-color` holding
260
+ its channels decomposed, suffixed with the configured space —
261
+ `--brand-color-oklch: 0.75 0.16 55` — and a `color` style emitted
262
+ `--current-color-{space}` beside `--current-color`. Both are gone, for the same
263
+ reason: they existed so an opacity suffix had channels to write an alpha into.
83
264
 
84
- The `oklch` color space is the default because it provides perceptually uniform color manipulation — alpha fading and color mixing produce more natural-looking results.
265
+ These were never part of the public API, but they were visible in the emitted
266
+ CSS, so hand-authored CSS may reference one. Address the token itself instead:
267
+
268
+ ```css
269
+ /* before */
270
+ color: oklch(var(--brand-color-oklch) / 0.5);
271
+ background: oklch(var(--brand-color-oklch));
272
+
273
+ /* after */
274
+ color: color-mix(in oklab, var(--brand-color) 50%, transparent);
275
+ background: var(--brand-color);
276
+ ```
277
+
278
+ The replacement is strictly more capable — the companion could only be
279
+ decomposed for a color the engine could evaluate at build time, while
280
+ `color-mix()` works on every `<color>`, including a `color-mix()`, a
281
+ `light-dark()`, and a variable Tasty never defined. It is also what
282
+ `#brand.5` emits.
85
283
 
86
284
  ---
87
285
 
88
286
  ## Name Prefix
89
287
 
90
- Every identifier Tasty generates — class names, keyframe names, counter-style names — starts with a configurable prefix. The runtime, SSR, and RSC paths default to `'t'`; the zero-runtime build path (`tastyStatic` via the Babel plugin) defaults to `'ts'` so static-extracted classes can never collide with runtime classes when both are loaded on the same page.
288
+ Every identifier Tasty generates — class names, keyframe names, counter-style names — starts with a configurable prefix. The `tasty()` client, SSR, and RSC paths default to `'t'`; the build-time extraction path (`tastyStatic` via the Babel plugin) defaults to `'ts'` so extracted classes can never collide with `tasty()` classes when both are loaded on the same page.
91
289
 
92
290
  ```jsx
93
291
  configure({
@@ -97,12 +295,12 @@ configure({
97
295
 
98
296
  The prefix is prepended verbatim to the hash, so include any separator inside the prefix string itself:
99
297
 
100
- | Setting | Class | Keyframe | Counter-style |
101
- |---|---|---|---|
102
- | `'t'` (runtime default) | `t1a2b3` | `tk1a2b3` | `tc1a2b3` |
103
- | `'ts'` (zero-runtime default) | `ts1a2b3` | `tsk1a2b3` | `tsc1a2b3` |
104
- | `'mb'` | `mb1a2b3` | `mbk1a2b3` | `mbc1a2b3` |
105
- | `'myapp-'` | `myapp-1a2b3` | `myapp-k1a2b3` | `myapp-c1a2b3` |
298
+ | Setting | Class | Keyframe | Counter-style |
299
+ | --------------------------- | ------------- | -------------- | -------------- |
300
+ | `'t'` (`tasty` default) | `t1a2b3` | `tk1a2b3` | `tc1a2b3` |
301
+ | `'ts'` (build-time default) | `ts1a2b3` | `tsk1a2b3` | `tsc1a2b3` |
302
+ | `'mb'` | `mb1a2b3` | `mbk1a2b3` | `mbc1a2b3` |
303
+ | `'myapp-'` | `myapp-1a2b3` | `myapp-k1a2b3` | `myapp-c1a2b3` |
106
304
 
107
305
  The single-letter discriminators (`k` for keyframes, `c` for counter-styles) keep the three kinds visually distinct in devtools — they are not required for correctness because CSS keeps these in separate namespaces.
108
306
 
@@ -112,12 +310,12 @@ The single-letter discriminators (`k` for keyframes, `c` for counter-styles) kee
112
310
  - Validated at `configure()` time; an invalid prefix throws synchronously rather than silently producing broken hydration.
113
311
  - Locked once styles have been generated, like all other config.
114
312
 
115
- ### Coexistence with the zero-runtime build
313
+ ### Coexistence with build-time extraction
116
314
 
117
- The runtime and zero-runtime builds **must use different prefixes** when both are loaded on the same page. Defaults already guarantee this; if you customize one, customize the other accordingly:
315
+ The `tasty()` and `tastyStatic()` paths **must use different prefixes** when both are loaded on the same page. Defaults already guarantee this; if you customize one, customize the other accordingly:
118
316
 
119
317
  ```jsx
120
- // app config (runtime / SSR / RSC)
318
+ // app config (client / SSR / RSC)
121
319
  configure({ namePrefix: 'mb' });
122
320
 
123
321
  // tasty-zero.config.ts (Babel plugin)
@@ -137,8 +335,7 @@ Tokens support state maps for responsive or theme-aware values:
137
335
  ```jsx
138
336
  configure({
139
337
  tokens: {
140
- '$gap': '4px',
141
- '$radius': '6px',
338
+ '$sidebar-width': '280px',
142
339
  '#primary': {
143
340
  '': '#purple',
144
341
  '@dark': '#light-purple',
@@ -152,9 +349,11 @@ configure({
152
349
  ```
153
350
 
154
351
  - `$name` keys become `--name` CSS custom properties
155
- - `#name` keys become `--name-color` and `--name-color-{colorSpace}` properties (suffix depends on `colorSpace`, default `oklch`)
352
+ - `#name` keys become `--name-color` custom properties
353
+ - Tokens do not change units: `2x` stays `16px` whatever `$gap` is. To drive a unit from a token, point the unit at it: `units: { x: 'var(--gap)' }` makes `2x` compile to `calc(2 * var(--gap))`
354
+ - Names keep their case, since CSS custom properties are case-sensitive: `$myVar` is `--myVar` and is referenced as `$myVar`. A leading capital is not supported and folds — `$Foo` and `#Purple` become `--foo` and `--purple-color` — so start names lowercase. Kebab-case (`$my-var`) remains the convention.
156
355
 
157
- Tokens are automatically emitted in all rendering modes: runtime (client), SSR, and zero-runtime (Babel plugin).
356
+ Tokens are emitted by the client injector, by the SSR collector (`TastyRegistry`, `tastyIntegration()`, `runWithCollector()`), by the `withTastyNext()` shared stylesheet, and by the Babel plugin. The inline React Server Component path without a collector does not emit them — see [Server-Side Rendering](ssr.md).
158
357
 
159
358
  ---
160
359
 
@@ -177,6 +376,17 @@ configure({
177
376
 
178
377
  When a component uses `padding: '$card-padding'`, the parser replaces it with `'4x'` before generating CSS. When a component uses `fill: '#accent'`, it is replaced with `'#purple'`, which in turn resolves to `var(--purple-color)`.
179
378
 
379
+ Tasty includes `'#clear': 'transparent'` as a default replace token, available
380
+ without calling `configure()`. It survives `resetConfig()`, and explicit
381
+ `replaceTokens` entries can override it. A replace token resolving to the literal
382
+ `transparent` ignores numeric and custom-property opacity suffixes:
383
+ `#clear`, `#clear.5`, and `#clear.$opacity` all emit `transparent`.
384
+
385
+ `#clear` no longer reads `--clear-color`, and Tasty no longer registers that
386
+ property by default. If you previously customized `#clear` through `tokens`,
387
+ local token definitions, or CSS, use a different color token or explicitly
388
+ override `replaceTokens['#clear']` instead.
389
+
180
390
  See [Replace Tokens](dsl.md#replace-tokens) in the Style DSL reference.
181
391
 
182
392
  ---
@@ -187,7 +397,7 @@ Register custom fonts globally so every component can reference them by family n
187
397
 
188
398
  ```ts
189
399
  configure({
190
- fontFace: {
400
+ fontFaces: {
191
401
  'Brand Sans': [
192
402
  {
193
403
  src: 'url("/fonts/brand-regular.woff2") format("woff2")',
@@ -208,9 +418,9 @@ configure({
208
418
  });
209
419
  ```
210
420
 
211
- Now any component can use `fontFamily: '"Brand Sans", sans-serif'` and the browser will already have the `@font-face` rules in the stylesheet.
421
+ Now any component can use `font: '"Brand Sans", sans-serif'` and the browser will already have the `@font-face` rules in the stylesheet.
212
422
 
213
- See [Font Face (`@fontFace`)](dsl.md#font-face-fontface) for inline usage inside component styles and the full list of supported descriptors.
423
+ See [Font Face (`@font-face`)](dsl.md#font-face-font-face) for inline usage inside component styles and the full list of supported descriptors.
214
424
 
215
425
  ---
216
426
 
@@ -220,7 +430,7 @@ Define custom list-marker algorithms globally. Rules are injected eagerly when s
220
430
 
221
431
  ```ts
222
432
  configure({
223
- counterStyle: {
433
+ counterStyles: {
224
434
  thumbs: {
225
435
  system: 'cyclic',
226
436
  symbols: '"👍"',
@@ -236,7 +446,102 @@ configure({
236
446
 
237
447
  Components can then reference `listStyleType: 'thumbs'` directly.
238
448
 
239
- See [Counter Style (`@counterStyle`)](dsl.md#counter-style-counterstyle) for inline usage inside component styles and the full list of supported descriptors.
449
+ See [Counter Style (`@counter-style`)](dsl.md#counter-style-counter-style) for inline usage inside component styles and the full list of supported descriptors.
450
+
451
+ ---
452
+
453
+ ## Functions
454
+
455
+ The single `functions` map holds both kinds of custom functions, discriminated by the value type:
456
+
457
+ - **Parse functions** — a **bare key** with a **function value** `(groups) => string`. Runs at parse time and is called as `name(...)`. Use these for computed/derived CSS that JavaScript produces (e.g. color-space conversions).
458
+ - **CSS `@function` definitions** — a **`$$name` key** with an **object value** (a [`FunctionDefinition`](https://developer.mozilla.org/en-US/docs/Web/CSS/@function)). Injected eagerly as a native `@function` rule and called as `$$name(...)` (→ `--name(...)`).
459
+
460
+ ```ts
461
+ configure({
462
+ functions: {
463
+ // Parse function — bare key, function value
464
+ double: (groups) => `calc(2 * ${groups[0]?.output ?? '0'})`,
465
+
466
+ // CSS @function — `$$` key, object value
467
+ $$negative: { args: ['$value'], result: '(-1 * $value)' },
468
+ $$shadow: {
469
+ args: { '$shadow-color': { syntax: '<color>', default: 'inherit' } },
470
+ returns: '<color>',
471
+ $offset: '2px',
472
+ result: '$offset $offset ($shadow-color, black)',
473
+ },
474
+ },
475
+ });
476
+ ```
477
+
478
+ Components then invoke parse functions as `double(...)` and CSS functions with the `$$name(...)` sugar, e.g. `margin: '$$negative(10px) top'`.
479
+
480
+ > A key whose prefix doesn't match its value type (an object under a bare key, or a function under a `$$` key) is **ignored with a dev-mode warning**.
481
+
482
+ See [Functions (`@function`)](dsl.md#functions-function) for inline usage inside component styles, the full descriptor shape, and token conventions. `@function` is an experimental CSS feature — unsupported browsers safely ignore the native rule (see the polyfill below).
483
+
484
+ ### Custom color functions
485
+
486
+ A parse function whose output is an already-supported color (`rgb`, `hsl`, `#…`, `oklch`, …) is treated as a **color function**: it works everywhere a color is accepted — style values, `parseColor`, and the `#token.alpha` opacity suffix, which calls the function with a `/ alpha` part appended (read `groups[0].parts[1]`, as below) — with no extra registration. This is the same mechanism the built-in `okhsl`/`okhst` plugins use; they are ordinary plugins registered by default.
487
+
488
+ ```ts
489
+ import { configure, createColorFunc } from '@tenphi/tasty';
490
+
491
+ // A custom color space is just a `functions` entry.
492
+ const myColorPlugin = () => ({
493
+ name: 'mycolor',
494
+ functions: {
495
+ // Hand-written parse function:
496
+ mycolor: (groups) => {
497
+ // `mycolor(255 0 0 / .5)` and `#brand.5` both arrive as two parts
498
+ const [main, alpha] = groups[0].parts;
499
+ const [r, g, b] = main.all;
500
+ return alpha?.all.length
501
+ ? `rgb(${r} ${g} ${b} / ${alpha.output})`
502
+ : `rgb(${r} ${g} ${b})`;
503
+ },
504
+ },
505
+ });
506
+
507
+ configure({ plugins: [myColorPlugin()] });
508
+
509
+ // Now `mycolor(...)` is a color in every context:
510
+ // fill: 'mycolor(255 0 0)'
511
+ // fill: '#brand.5' (with replaceTokens: { '#brand': 'mycolor(255 0 0)' })
512
+ ```
513
+
514
+ For HSL-style color spaces (a hue angle plus two percentages), the exported `createColorFunc(name, convert, label?)` helper handles angle/percentage parsing, clamping, alpha, and caching. `convert` returns sRGB `[r, g, b]` in 0-1; `label` is an optional string used only in dev warnings (e.g. `'H S L'`) and has no effect on output. This is exactly how `okhslPlugin`/`okhstPlugin` are implemented.
515
+
516
+ ---
517
+
518
+ ## Polyfills
519
+
520
+ `@function` only ships natively in Chromium 139+. To use CSS functions in browsers that don't support the at-rule yet (Firefox, Safari), enable the **functions polyfill**, which expands every `$$name(...)` call into plain CSS (`calc()`/`var()`/`color-mix()`) at parse time instead of emitting the native `@function` rule:
521
+
522
+ ```ts
523
+ configure({
524
+ polyfills: {
525
+ functions: true, // default: false
526
+ },
527
+ functions: {
528
+ $$negative: { args: ['$value'], result: '(-1 * $value)' },
529
+ },
530
+ });
531
+
532
+ // Now `margin: '$$negative(10px) top'` renders `margin: calc(-1 * 10px) 0 0 0`
533
+ // — no native @function rule is emitted.
534
+ ```
535
+
536
+ This works across all rendering modes (client, SSR/RSC, and `tastyStatic`) because expansion happens in the parser. Note `polyfills.functions` (the feature toggle) is distinct from the top-level `functions` (the definitions map).
537
+
538
+ **Decided limitations when the polyfill is on:**
539
+
540
+ - **No native fallback** — functions are always inlined; we do exactly what is configured.
541
+ - **Conditional results** (`@media`/`@supports`/`if()` inside `result`) are inlined verbatim; the conditional nuance is not resolved per-element.
542
+ - **Typed params / `returns`** are dropped (inlining is purely lexical substitution).
543
+ - **Param name collisions** are avoided by fully inlining argument values (no function-internal custom properties are emitted) and by namespacing the function's own variables.
544
+ - **Recursion** — self/mutually-recursive functions are not expanded; the cycle guard bails and leaves the call untouched.
240
545
 
241
546
  ---
242
547
 
@@ -260,7 +565,23 @@ configure({
260
565
  });
261
566
  ```
262
567
 
263
- Recipe values are flat tasty styles (no sub-element keys). They may contain base styles, tokens, local states, `@keyframes`, and `@properties`. Recipes cannot reference other recipes.
568
+ Recipe values are flat tasty styles (no sub-element keys). They may contain base styles, tokens, local states, `@keyframes`, and `@property`.
569
+
570
+ **Recipes cannot reference other recipes.** A `recipe` key inside a configured recipe's value is not recursively resolved:
571
+
572
+ ```jsx
573
+ // Unsupported: applying 'elevatedCard' does not expand 'card elevated'.
574
+ configure({
575
+ recipes: {
576
+ elevatedCard: {
577
+ recipe: 'card elevated',
578
+ padding: '6x',
579
+ },
580
+ },
581
+ });
582
+ ```
583
+
584
+ Instead, compose the names where you apply the styles: `styles: { recipe: 'card elevated', padding: '6x' }`. Recipe references are resolved on the component root and independently inside each sub-element's styles (for example, `styles: { Panel: { recipe: 'card elevated' } }`). This sub-element support does not allow one recipe definition to inherit another. Tasty warns in development when a recipe definition contains a `recipe` key.
264
585
 
265
586
  For how to apply, compose, and override recipes in components, see [Recipes](dsl.md#recipes) in the Style DSL reference.
266
587
 
@@ -317,7 +638,7 @@ configure({
317
638
  color: '#text',
318
639
  preset: 't2',
319
640
  margin: 0,
320
- fontFamily: 'system-ui, sans-serif',
641
+ font: 'system-ui, sans-serif',
321
642
  },
322
643
  html: {
323
644
  overflow: 'hidden',
@@ -326,9 +647,9 @@ configure({
326
647
  });
327
648
  ```
328
649
 
329
- Each key is a CSS selector, and each value is a Tasty `Styles` object supporting the full style syntax including style properties, tokens, state maps, and selector-based sub-styling (e.g. `$: '> .app'` for elements outside React scope). Global styles are injected alongside `:root` tokens when the first style is rendered.
650
+ Each key is a CSS selector (a list such as `'.uni-checkbox, uni-checkbox'` styles every item), and each value is a Tasty `Styles` object supporting the full style syntax including style properties, tokens, state maps, `@keyframes`, and selector-based sub-styling (e.g. `$: '> .app'` for elements outside React scope). Global styles are injected alongside `:root` tokens when the first style is rendered.
330
651
 
331
- Global styles are automatically emitted in all rendering modes: runtime (client), SSR, and zero-runtime (Babel plugin). Plugins can also provide `globalStyles`; they are merged per selector with config global styles (config wins on conflict).
652
+ Global styles are automatically emitted in all delivery modes: client rendering, server rendering, and build-time extraction with the Babel plugin. Plugins can also provide `globalStyles`; they are merged per selector with config global styles (config wins on conflict).
332
653
 
333
654
  ---
334
655
 
@@ -336,25 +657,25 @@ Global styles are automatically emitted in all rendering modes: runtime (client)
336
657
 
337
658
  CSS cannot transition or animate custom properties unless their type is declared via [`@property`](https://developer.mozilla.org/en-US/docs/Web/CSS/@property). Tasty handles this automatically — when a custom property is assigned a concrete value (e.g. `'$scale': 1`, `'$gap': '10px'`, `'#accent': 'purple'`), the type is inferred and a `@property` rule is registered.
338
659
 
339
- This works across all declaration contexts: component styles, `@keyframes`, global config, and the zero-runtime Babel plugin. It also resolves `var()` chains — if `$a` references `var(--b)`, the type propagates once `--b` is resolved.
660
+ This works across all declaration contexts: component styles, `@keyframes`, global config, and build-time extraction with the Babel plugin. It also resolves `var()` chains — if `$a` references `var(--b)`, the type propagates once `--b` is resolved.
340
661
 
341
662
  Supported types:
342
663
 
343
- | Detection | Inferred syntax |
344
- |-----------|-----------------|
345
- | `1`, `0.5`, `-3` (bare numbers) | `<number>` |
346
- | `10px`, `2rem`, `100vw` (length units) | `<length>` |
347
- | `50%` | `<percentage>` |
348
- | `45deg`, `0.5turn` (angle units) | `<angle>` |
349
- | `300ms`, `1s` (time units) | `<time>` |
350
- | `#name` tokens (by naming convention) | `<color>` |
664
+ | Detection | Inferred syntax |
665
+ | -------------------------------------- | --------------- |
666
+ | `1`, `0.5`, `-3` (bare numbers) | `<number>` |
667
+ | `10px`, `2rem`, `100vw` (length units) | `<length>` |
668
+ | `50%` | `<percentage>` |
669
+ | `45deg`, `0.5turn` (angle units) | `<angle>` |
670
+ | `300ms`, `1s` (time units) | `<time>` |
671
+ | `#name` tokens (by naming convention) | `<color>` |
351
672
 
352
- Auto-inferred properties use `inherits: true` (the CSS default). Use explicit `@properties` when you need different settings:
673
+ Auto-inferred properties use `inherits: true` (the CSS default). Use explicit `@property` when you need different settings:
353
674
 
354
675
  ```jsx
355
676
  // In component styles
356
677
  styles: {
357
- '@properties': {
678
+ '@property': {
358
679
  '$scale': { syntax: '<number>', inherits: false, initialValue: 1 },
359
680
  },
360
681
  }
@@ -367,7 +688,7 @@ configure({
367
688
  });
368
689
  ```
369
690
 
370
- To disable auto-inference entirely (only explicit `@properties` will be used):
691
+ To disable auto-inference entirely (only explicit `@property` will be used):
371
692
 
372
693
  ```jsx
373
694
  configure({ autoPropertyTypes: false });
@@ -379,27 +700,25 @@ configure({ autoPropertyTypes: false });
379
700
 
380
701
  Override or extend the built-in style property handlers. A handler definition can take three forms:
381
702
 
382
- | Form | Syntax | Description |
383
- |------|--------|-------------|
384
- | Function only | `handler` | Triggered by its key name; receives only that property |
385
- | Single dep | `['styleName', handler]` | Triggered by the specified style property |
386
- | Multi dep | `[['dep1', 'dep2', ...], handler]` | Triggered by any of the listed properties; receives all of them |
703
+ | Form | Syntax | Description |
704
+ | ------------- | ---------------------------------- | --------------------------------------------------------------- |
705
+ | Function only | `handler` | Triggered by its key name; receives only that property |
706
+ | Single dep | `['styleName', handler]` | Triggered by the specified style property |
707
+ | Multi dep | `[['dep1', 'dep2', ...], handler]` | Triggered by any of the listed properties; receives all of them |
387
708
 
388
- The multi-dep form is useful when output depends on several style properties together (e.g., `gap` needs to know `display` and `flow` to decide the CSS strategy).
709
+ The multi-dep form is useful when output depends on several style properties together (e.g., `gap` needs to know `display` and `flow` to decide the CSS strategy). A handler whose dependencies include a built-in style takes over that style's whole group — see [Replacing a built-in handler](#replacing-a-built-in-handler). Use `defineHandler` for it and the dependency types are inferred from the dependency list, so a typo in the destructure is a type error instead of a silent `undefined`.
389
710
 
390
711
  ```jsx
391
- import { configure, styleHandlers } from '@tenphi/tasty';
712
+ import {
713
+ configure,
714
+ defineHandler,
715
+ parseColor,
716
+ parseStyle,
717
+ styleHandlers,
718
+ } from '@tenphi/tasty';
392
719
 
393
720
  configure({
394
721
  handlers: {
395
- // Function only — overrides built-in fill handler
396
- fill: ({ fill }) => {
397
- if (fill?.startsWith('gradient:')) {
398
- return { background: fill.slice(9) };
399
- }
400
- return styleHandlers.fill({ fill });
401
- },
402
-
403
722
  // Function only — new single-prop handler
404
723
  elevation: ({ elevation }) => {
405
724
  const level = parseInt(elevation) || 1;
@@ -409,30 +728,230 @@ configure({
409
728
  };
410
729
  },
411
730
 
412
- // Multi dep — handler reads multiple style properties
413
- gap: [['display', 'flow', 'gap'], ({ display, flow, gap }) => {
414
- if (!gap) return;
415
- const isGrid = display?.includes('grid');
416
- return { gap: isGrid ? gap : `/* custom logic for ${flow} */` };
417
- }],
731
+ // Overriding a built-in: declare every style the built-in handled and pass
732
+ // them all through, or the ones you leave out stop working (see below).
733
+ fill: defineHandler(
734
+ [
735
+ 'fill',
736
+ 'backgroundColor',
737
+ 'image',
738
+ 'backgroundImage',
739
+ 'backgroundPosition',
740
+ 'backgroundSize',
741
+ 'backgroundRepeat',
742
+ 'backgroundAttachment',
743
+ 'backgroundOrigin',
744
+ 'backgroundClip',
745
+ 'background',
746
+ ],
747
+ (props) => {
748
+ if (
749
+ typeof props.fill === 'string' &&
750
+ props.fill.startsWith('gradient:')
751
+ ) {
752
+ return { background: props.fill.slice(9) };
753
+ }
754
+ return styleHandlers.fill(props);
755
+ },
756
+ ),
757
+
758
+ // Multi dep — triggered by either name, receives both
759
+ stripe: defineHandler(
760
+ ['stripe', 'stripeColor'],
761
+ ({ stripe, stripeColor }) => {
762
+ if (!stripe) return;
763
+ const width = parseStyle(String(stripe)).output;
764
+ const color = stripeColor
765
+ ? parseColor(String(stripeColor)).color
766
+ : 'currentcolor';
767
+ return { 'border-left': `${width} solid ${color}` };
768
+ },
769
+ ),
418
770
  },
419
771
  });
420
772
  ```
421
773
 
774
+ ### Return shape
775
+
776
+ A handler returns a `CSSMap`, an array of them, or nothing:
777
+
778
+ - Keys are **kebab-case** CSS property names (`'background-color'`, not `backgroundColor`) or `--custom-property` names. A camelCase key warns in development and is emitted verbatim, which the browser ignores.
779
+ - Values are stringified, so numbers are fine (`{ '-webkit-line-clamp': 3 }`).
780
+ - An array value emits one declaration per entry, in order, so the browser keeps the last one it supports: `{ width: ['-webkit-fill-available', '-moz-available', 'stretch'] }` emits three `width` declarations.
781
+ - The reserved `$` key is a **selector suffix**: `{ $: '& > *:not(:last-child)', 'margin-right': gap }` applies the declarations to a nested selector. It accepts an array to fan out over several.
782
+ - Return an array of maps to emit several declaration sets, each with its own `$`.
783
+
784
+ Values arrive **state-resolved but unparsed** — the raw authored DSL string (`'2x'`, `'#purple.5'`, `true`, `4`). Call the exported `parseStyle()` / `parseColor()` yourself; nothing parses them for you.
785
+
786
+ ### Replacing a built-in handler
787
+
788
+ Built-in handlers are shared across several style names. Registering a handler for one of those names unregisters the built-in from **all** of them, and the displaced names then fall back to auto-generated CSS aliases — so `hide: true` starts emitting a literal `hide: true` declaration. A development-mode warning lists exactly what was displaced.
789
+
790
+ The shared groups worth knowing:
791
+
792
+ | Registering a handler for | Also takes over |
793
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
794
+ | `fill` | `backgroundColor`, `image`, `backgroundImage`, `backgroundPosition`, `backgroundSize`, `backgroundRepeat`, `backgroundAttachment`, `backgroundOrigin`, `backgroundClip`, `background` |
795
+ | `display` | `hide`, `whiteSpace`, `textOverflow`, `flow`, `gap` |
796
+ | `flow` | `gap` |
797
+ | `preset` | `font`, `fontFamily`, `fontSize`, `fontWeight`, `fontStyle`, `lineHeight`, `letterSpacing`, `textTransform` |
798
+ | `padding` / `margin` | their `Top`/`Right`/`Bottom`/`Left` longhands (`paddingTop`, `marginLeft`, …) |
799
+ | `inset` | `top`, `right`, `bottom`, `left` |
800
+ | `width` / `height` | `minWidth`/`maxWidth`, `minHeight`/`maxHeight` |
801
+
802
+ A multi-dep handler takes over every group its dependencies touch: `defineHandler(['display', 'flow', 'gap'], …)` takes over `display`, `flow`, and `gap` together, so it must emit `display` and `flex-flow` itself.
803
+
804
+ Either declare the whole group and delegate the rest to `styleHandlers.*`, or pick a name that isn't shared.
805
+
806
+ ### Chunk membership
807
+
808
+ Tasty renders and caches CSS in independent chunks, and a chunk's cache key covers only its own style values. All of a handler's dependencies must therefore live in one chunk. Custom style names are pulled into their handler's chunk automatically at registration; a handler whose dependencies span two _built-in_ chunks (say `fill` and `padding`) warns, because it would be invoked once per chunk with a subset of its inputs.
809
+
810
+ `configure({ handlers })` must run before the first render, like every other config option.
811
+
422
812
  ---
423
813
 
424
- ## Extending Style Types (TypeScript)
814
+ ## Props Middleware
425
815
 
426
- Use module augmentation to extend the `StylesInterface`:
816
+ `propHandlers` are middleware over a component's props — props in, props out. Where a style _handler_ turns a style property into CSS declarations, a prop handler turns a **component prop** into other props, including `styles`. It is the extension point for props whose value isn't a style value.
817
+
818
+ ```jsx
819
+ import { configure, mergeStyles } from '@tenphi/tasty';
820
+
821
+ configure({
822
+ propHandlers: {
823
+ glaze: (props) => {
824
+ const { glaze, ...rest } = props;
825
+ if (!glaze) return rest;
826
+
827
+ return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };
828
+ },
829
+ },
830
+ });
831
+
832
+ <Element glaze="purple" />;
833
+ ```
834
+
835
+ The map key is the handler's name and, by default, the prop that triggers it, so an absent prop costs one property check rather than a call. A tuple overrides that: `['glaze', fn]`, `[['glaze', 'tint'], fn]`, or `['*', fn]` for unconditional.
836
+
837
+ Handlers run at the very top of every component's render, before any prop is destructured, so one can rewrite `styles`, `mods`, `tokens`, `variant`, `as`, `element`, and `qa`. They run in registration order — plugins first, then direct config — each receiving the previous one's output.
838
+
839
+ Handlers must be **pure** and must not mutate their input, and should memoize the styles they build per input value: style values are cached by object identity, so mutating one in place yields stale CSS, and a reference-stable object avoids re-serializing on every render.
840
+
841
+ Injected styles occupy the `styles` slot, so they beat a component's own default styles and lose to a style prop at the call site. Prop handlers do not apply to sub-elements or to build-time `tastyStatic()`, which has no props.
842
+
843
+ See [Plugins → Props middleware](plugins.md#props-middleware) for the full contract and a worked example.
844
+
845
+ ---
846
+
847
+ ## Base Style Props
848
+
849
+ `baseStyleProps` exposes style properties as props on **every** `tasty()` component, on top of the built-in base styles (`display`, `font`, `preset`, `hide`, `whiteSpace`, `opacity`, `transition`):
850
+
851
+ ```jsx
852
+ configure({ baseStyleProps: ['radius', 'shadow'] });
853
+
854
+ <Card radius="1r" shadow />;
855
+ ```
856
+
857
+ `configure()` may run after your components are defined — each factory resolves its prop list lazily.
858
+
859
+ Each name costs one property check per render of every component, and the effect is app-global, so keep the list short and use a factory's own `styleProps` for anything narrower. Avoid names that collide with real DOM or component props (`width`, `size`, `color`), since every component will then swallow them as styles.
860
+
861
+ ---
862
+
863
+ ## TypeScript
864
+
865
+ Component props are typed from the `tasty()` definition with no setup. Module augmentation adds the names your design system defines and the extensions your plugins add.
866
+
867
+ ### Component props
868
+
869
+ | In `tasty({ … })` | Adds the props |
870
+ | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
871
+ | `styleProps: ['gap', 'padding'] as const` | `gap`, `padding`, each typed like the style: a value or a state map |
872
+ | `modProps: { isLoading: Boolean, size: ['sm', 'md', 'lg'] as const }` | `isLoading?: boolean`, `size?: 'sm' \| 'md' \| 'lg'` (`String` gives `string`, `Number` gives `number`) |
873
+ | `modProps: ['isLoading'] as const` | `isLoading?: ModValue` |
874
+ | `tokenProps: ['progress', 'accentColor'] as const` | `progress?: TokenValue`, `accentColor?: TokenValue` |
875
+ | `variants: { default: {…}, danger: {…} }` | `variant?: 'default' \| 'danger'` |
876
+ | `elements: { Title: 'h3' }` | `Card.Title`, with the `h3` props plus `qa`, `qaVal`, `mods`, `tokens`, `isDisabled`, `isHidden`, `isChecked`, and a `ref` typed as `HTMLHeadingElement`; no `styles` |
877
+ | `as: SomeComponent` | `SomeComponent`'s own props, required ones still required |
878
+
879
+ Write the array forms with `as const`. Without it, `modProps: ['isLoading']` widens to `string[]` and every prop on the component is typed `ModValue`, so an `onClick` handler no longer type-checks. A `modProps` value list without `as const` widens to `string`.
880
+
881
+ `tasty(Base, { … })` keeps `Base`'s prop types and sub-elements, and adds the props and sub-elements its own options above declare. Its `variant` accepts both its own variant names and `Base`'s. See [Extend an existing component](react-api.md#extend-an-existing-component).
882
+
883
+ ### Registering your names and extensions
884
+
885
+ ```ts
886
+ // tasty.d.ts — keep the import: it makes this file a module, so the block
887
+ // below extends '@tenphi/tasty' instead of replacing it.
888
+ import '@tenphi/tasty';
427
889
 
428
- ```tsx
429
- // tasty.d.ts
430
890
  declare module '@tenphi/tasty' {
891
+ interface TastyNamedColors {
892
+ surface: true;
893
+ text: true;
894
+ primary: true;
895
+ }
896
+ interface TastyPresetNames {
897
+ h1: true;
898
+ t2: true;
899
+ }
900
+ interface TastyThemeNames {
901
+ danger: true;
902
+ success: true;
903
+ }
431
904
  interface StylesInterface {
432
- elevation?: string;
433
- gradient?: string;
905
+ stripe?: string;
906
+ }
907
+ interface TastyCustomProps {
908
+ glaze: 'soft' | 'strong' | { tone: string; intensity?: number };
909
+ }
910
+ interface TastyBaseStylePropNames {
911
+ radius: true;
912
+ stripe: true;
434
913
  }
435
914
  }
436
915
  ```
437
916
 
917
+ | Interface | Register | What it types |
918
+ | ------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------ |
919
+ | `TastyNamedColors` | Color token names from `tokens` and `replaceTokens`, without the `#` | Suggestions for `#name` and `#name.50` in `fill`, `color`, and `svgFill` |
920
+ | `TastyPresetNames` | `presets` names | The `preset` style and prop |
921
+ | `TastyThemeNames` | Theme names | The `theme` prop (rendered as `data-theme`) |
922
+ | `StylesInterface` | Style properties added with `handlers` | Their value type in `styles`, `styleProps`, and base style props |
923
+ | `TastyCustomProps` | Props added with `propHandlers` | An optional prop on every `tasty()` component (not on sub-elements) |
924
+ | `TastyBaseStylePropNames` | Names passed to `baseStyleProps` | A prop on every component, typed like the style it names |
925
+
926
+ - The first three add autocomplete, not checking: any other string still type-checks (`preset: 'h9'` compiles). The ESLint plugin is what reports unknown names.
927
+ - In `StylesInterface`, declare the plain value type (`stripe?: string`). Tasty adds state-map support itself, as it does for built-in styles.
928
+ - A custom style name in `styles` type-checks without augmentation, but `styleProps` and `TastyBaseStylePropNames` accept only names in `StylesInterface`. A base style prop name missing from it adds no prop.
929
+ - `TastyCustomProps` types the component prop, not the handler. A prop handler receives `Record<string, unknown>`, so cast inside it (`rest.styles as Styles`).
930
+ - State keys, `$` value tokens, units, and recipe names have no TypeScript types. The ESLint plugin checks them against `tasty.config.ts`.
931
+
932
+ ### `tasty.config.ts`
933
+
934
+ TypeScript augmentation does not reach the linter or the editor. [`@tenphi/eslint-plugin-tasty`](https://github.com/tenphi/eslint-plugin-tasty) and the Tasty VS Code extension read a `tasty.config.ts` (or `.js`, `.json`) at the project root instead. It only lists names: it is not passed to `configure()`, and it is unrelated to the Babel plugin's `configFile` (such as `tasty-zero.config.ts`).
935
+
936
+ ```ts
937
+ // tasty.config.ts
938
+ import type { TastyExtensionConfig } from '@tenphi/tasty';
939
+ import type { TastyValidationConfig } from '@tenphi/eslint-plugin-tasty';
940
+
941
+ export default {
942
+ tokens: ['#surface', '#text', '#primary', '$sidebar-width'],
943
+ units: ['cols'],
944
+ states: ['@mobile', '@dark'],
945
+ presets: ['h1', 't2'],
946
+ recipes: ['card', 'elevated'],
947
+ styles: ['stripe'],
948
+ importSources: ['@my-org/ui'],
949
+ presetDescriptions: { h1: 'Heading 1 (32px, bold)' },
950
+ } satisfies TastyExtensionConfig & TastyValidationConfig;
951
+ ```
952
+
953
+ `TastyExtensionConfig` from `@tenphi/tasty` types the fields the VS Code extension reads: `extends`, `tokens`, `units`, `functions`, `states`, `presets`, `styles`, `presetDescriptions`, and `stateDescriptions`. It has no `recipes`, `importSources`, `ownedSources`, or `styleFunctions`, so annotating the file with it alone rejects those ESLint fields; intersect it with the plugin's `TastyValidationConfig`, as above. An omitted list is not checked; `tokens: false`, `units: false`, or `functions: false` turns a check off even when an `extends` parent sets it.
954
+
955
+ Keep it in step with `configure()`: token names with their `#` or `$`, custom units, parse-function names, state aliases, presets, recipes, and custom style names.
956
+
438
957
  See [Style DSL](dsl.md) for state maps, tokens, units, and extending semantics, and [React API](react-api.md) for `tasty()`, style functions, and component props.