@tenphi/tasty 0.0.0-snapshot.047dfbb → 0.0.0-snapshot.05197cf

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 (121) hide show
  1. package/README.md +181 -136
  2. package/dist/babel-C5mN2_fA.d.ts +83 -0
  3. package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
  4. package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
  5. package/dist/chunks/build-config-Tkr_Z48w.js +42 -0
  6. package/dist/chunks/build-config-Tkr_Z48w.js.map +1 -0
  7. package/dist/{collector-J6LwZR0N.js → chunks/collector-BG-HTHSz.js} +64 -99
  8. package/dist/chunks/collector-BG-HTHSz.js.map +1 -0
  9. package/dist/chunks/config-engine-B9pEqzzU.js +267 -0
  10. package/dist/chunks/config-engine-B9pEqzzU.js.map +1 -0
  11. package/dist/chunks/css-definitions-BAtJQ_tP.js +875 -0
  12. package/dist/chunks/css-definitions-BAtJQ_tP.js.map +1 -0
  13. package/dist/chunks/css-resources-BN8apgxt.js +142 -0
  14. package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
  15. package/dist/chunks/debug-B7TmqIlz.js +501 -0
  16. package/dist/chunks/debug-B7TmqIlz.js.map +1 -0
  17. package/dist/chunks/dsl-C5yuAn41.js +1373 -0
  18. package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
  19. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  20. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  21. package/dist/chunks/react-runtime-5owaaB5Y.js +557 -0
  22. package/dist/chunks/react-runtime-5owaaB5Y.js.map +1 -0
  23. package/dist/chunks/runtime-engine-B3JcRKeS.js +2438 -0
  24. package/dist/chunks/runtime-engine-B3JcRKeS.js.map +1 -0
  25. package/dist/chunks/runtime-state-DDnx6lOJ.js +127 -0
  26. package/dist/chunks/runtime-state-DDnx6lOJ.js.map +1 -0
  27. package/dist/{merge-styles-CAdKaHxh.js → chunks/shared-utils-DWA4LjIa.js} +55 -54
  28. package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
  29. package/dist/chunks/style-engine-CnQoWtc_.js +5202 -0
  30. package/dist/chunks/style-engine-CnQoWtc_.js.map +1 -0
  31. package/dist/{css-writer-IC7tdnIf.js → chunks/zero-engine-B36DCc0X.js} +34 -112
  32. package/dist/chunks/zero-engine-B36DCc0X.js.map +1 -0
  33. package/dist/{collector-CddJZDOr.d.ts → collector-CViSMO84.d.ts} +64 -7
  34. package/dist/{config-C3SKYuxY.d.ts → config-CbDtZzZy.d.ts} +491 -78
  35. package/dist/core/index.d.ts +5 -5
  36. package/dist/core/index.js +9 -6
  37. package/dist/{index-ByBYTH9l.d.ts → index-CmrdZ8ay.d.ts} +421 -252
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.js +11 -732
  40. package/dist/{merge-styles-CvUi7SOD.d.ts → merge-styles-Dp3eKkK9.d.ts} +2 -2
  41. package/dist/ssr/astro-client.js +1 -14
  42. package/dist/ssr/astro-client.js.map +1 -1
  43. package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
  44. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  45. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  46. package/dist/ssr/astro-middleware-extract.d.ts +11 -0
  47. package/dist/ssr/astro-middleware-extract.js +9 -0
  48. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  49. package/dist/ssr/astro-middleware-static.d.ts +18 -0
  50. package/dist/ssr/astro-middleware-static.js +7 -0
  51. package/dist/ssr/astro-middleware-static.js.map +1 -0
  52. package/dist/ssr/astro-middleware.d.ts +11 -7
  53. package/dist/ssr/astro-middleware.js +2 -14
  54. package/dist/ssr/astro-middleware.js.map +1 -1
  55. package/dist/ssr/astro.d.ts +45 -7
  56. package/dist/ssr/astro.js +159 -86
  57. package/dist/ssr/astro.js.map +1 -1
  58. package/dist/ssr/index.d.ts +7 -14
  59. package/dist/ssr/index.js +5 -5
  60. package/dist/ssr/index.js.map +1 -1
  61. package/dist/ssr/next-config.d.ts +66 -0
  62. package/dist/ssr/next-config.js +124 -0
  63. package/dist/ssr/next-config.js.map +1 -0
  64. package/dist/ssr/next.d.ts +9 -2
  65. package/dist/ssr/next.js +27 -43
  66. package/dist/ssr/next.js.map +1 -1
  67. package/dist/static/index.d.ts +2 -2
  68. package/dist/static/index.js +4 -22
  69. package/dist/static/index.js.map +1 -1
  70. package/dist/{index-C5owZ15q.d.ts → types-Ji9PGExW.d.ts} +873 -546
  71. package/dist/zero/babel.d.ts +2 -80
  72. package/dist/zero/babel.js +42 -109
  73. package/dist/zero/babel.js.map +1 -1
  74. package/dist/zero/index.d.ts +16 -2
  75. package/dist/zero/index.js +2 -2
  76. package/dist/zero/next.d.ts +1 -1
  77. package/dist/zero/next.js +0 -31
  78. package/dist/zero/next.js.map +1 -1
  79. package/docs/README.md +17 -9
  80. package/docs/adoption.md +56 -31
  81. package/docs/ai-agents.md +250 -0
  82. package/docs/comparison.md +69 -40
  83. package/docs/configuration.md +486 -85
  84. package/docs/debug.md +26 -14
  85. package/docs/design-system.md +43 -24
  86. package/docs/dsl.md +455 -189
  87. package/docs/getting-started.md +64 -41
  88. package/docs/injector.md +120 -30
  89. package/docs/methodology.md +46 -40
  90. package/docs/migration-v3.md +285 -0
  91. package/docs/pipeline.md +36 -15
  92. package/docs/plugins.md +353 -0
  93. package/docs/react-api.md +142 -42
  94. package/docs/runtime-benchmarks.md +388 -0
  95. package/docs/ssr.md +252 -86
  96. package/docs/styles.md +126 -24
  97. package/docs/tasty-static.md +141 -106
  98. package/package.json +103 -20
  99. package/tasty.config.ts +4 -0
  100. package/dist/async-storage-DKK-wTD4.js +0 -44
  101. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  102. package/dist/collector-J6LwZR0N.js.map +0 -1
  103. package/dist/config-C3F4Ogo1.js +0 -10993
  104. package/dist/config-C3F4Ogo1.js.map +0 -1
  105. package/dist/context-CA8YKeMn.js +0 -24
  106. package/dist/context-CA8YKeMn.js.map +0 -1
  107. package/dist/core-DxHmF6S9.js +0 -1598
  108. package/dist/core-DxHmF6S9.js.map +0 -1
  109. package/dist/css-writer-IC7tdnIf.js.map +0 -1
  110. package/dist/format-global-rules-DklyaXv-.js +0 -22
  111. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  112. package/dist/format-rules-DTLY39Hm.js +0 -143
  113. package/dist/format-rules-DTLY39Hm.js.map +0 -1
  114. package/dist/hydrate-8Zglgy_C.js +0 -45
  115. package/dist/hydrate-8Zglgy_C.js.map +0 -1
  116. package/dist/index.js.map +0 -1
  117. package/dist/keyframes-DgGkipNK.js +0 -595
  118. package/dist/keyframes-DgGkipNK.js.map +0 -1
  119. package/dist/merge-styles-CAdKaHxh.js.map +0 -1
  120. package/dist/resolve-recipes-BQNdunBd.js +0 -144
  121. package/dist/resolve-recipes-BQNdunBd.js.map +0 -1
@@ -1,6 +1,8 @@
1
1
  # Getting Started
2
2
 
3
- This guide walks you from zero to a working Tasty component, then through the optional shared configuration and tooling layers. It is the right starting point when you already want to try Tasty in code. If you are still deciding whether Tasty fits your team, start with [Comparison](comparison.md) and [Adoption Guide](adoption.md) first. For a feature overview, see the [README](../README.md). For the full style language reference, see the [Style DSL](dsl.md). For the React API, see the [React API](react-api.md). For the rest of the docs by role or task, see the [Docs Hub](README.md).
3
+ Build one stateful component first. You will see how Tasty expresses priority as a state map, why overlapping states do not compete, and where shared design-system configuration fits afterward.
4
+
5
+ This is the right starting point when you are ready to try Tasty in code. If you are still evaluating it, read the [Introduction](../README.md), [Comparison](comparison.md), and [Adoption Guide](adoption.md).
4
6
 
5
7
  ---
6
8
 
@@ -10,7 +12,7 @@ This guide walks you from zero to a working Tasty component, then through the op
10
12
  - **React** >= 18 (peer dependency)
11
13
  - **Package manager**: pnpm, npm, or yarn
12
14
 
13
- Tasty can be used immediately in a React app, but it is most compelling for teams building reusable components with intersecting states, variants, tokens, and design-system conventions.
15
+ No Tasty configuration is required for the first component.
14
16
 
15
17
  ---
16
18
 
@@ -22,36 +24,57 @@ pnpm add @tenphi/tasty
22
24
 
23
25
  ---
24
26
 
25
- ## Your first component
27
+ ## Build a button whose states don’t fight
26
28
 
27
29
  ```tsx
28
30
  import { tasty } from '@tenphi/tasty';
29
31
 
30
- const Card = tasty({
31
- as: 'div',
32
+ const Button = tasty({
33
+ as: 'button',
32
34
  styles: {
33
- display: 'flex',
34
- flow: 'column',
35
- padding: '4x',
36
- gap: '2x',
37
- fill: '#white',
38
- border: true,
39
- radius: true,
35
+ padding: '12px 20px',
36
+ radius: '8px',
37
+ border: '0',
38
+ fill: {
39
+ '': 'royalblue',
40
+ ':hover': 'blue',
41
+ ':active': 'navy',
42
+ disabled: 'lightgray',
43
+ },
44
+ color: {
45
+ '': 'white',
46
+ disabled: 'dimgray',
47
+ },
48
+ cursor: {
49
+ '': 'pointer',
50
+ disabled: 'not-allowed',
51
+ },
40
52
  },
41
53
  });
42
54
 
43
55
  export default function App() {
44
- return <Card>Hello, Tasty!</Card>;
56
+ return (
57
+ <>
58
+ <Button>Save changes</Button>
59
+ <Button disabled>Disabled</Button>
60
+ </>
61
+ );
45
62
  }
46
63
  ```
47
64
 
48
- `tasty()` returns a normal React component. Values like `4x`, `#white`, `true`, and `1r` are Tasty DSL — they map to CSS custom properties, shorthand expansions, and design tokens. See [Style Properties](styles.md) for the full reference.
65
+ `tasty()` returns a normal React component. The keys in each state map define priority: later branches win over earlier ones. Because `disabled` is last, a disabled button keeps its disabled styles even while the pointer is over it.
66
+
67
+ `disabled` and `checked` are built-in automatic states. Tasty activates them from the corresponding native prop or attribute, so `disabled` is the concise Tasty form of `[disabled]`, and `checked` is the concise form of `[checked]`.
68
+
69
+ Tasty compiles that priority into selectors that exclude one another. The hover, active, and disabled background rules cannot all match and ask the CSS cascade to decide the winner.
70
+
71
+ The example uses ordinary CSS values so it works without setup. A design system will usually replace them with shared tokens, units, and state aliases in the next step. See the [Style DSL](dsl.md) for the complete state-map syntax and [Style Properties](styles.md) for Tasty’s enhanced CSS properties.
49
72
 
50
73
  ---
51
74
 
52
- ## Optional: add shared configuration
75
+ ## Add your design system’s language
53
76
 
54
- Use `configure()` once, before your app renders, when your app or design system needs shared state aliases, tokens, recipes, or parser extensions:
77
+ The first component needs no configuration. Use `configure()` once, before your app renders, when your app or design system is ready to share tokens, state aliases, recipes, units, or parser extensions:
55
78
 
56
79
  ```tsx
57
80
  // src/tasty-config.ts
@@ -91,8 +114,8 @@ configure({
91
114
  '#primary': 'oklch(55% 0.25 265)',
92
115
  '#surface': '#fff',
93
116
  '#text': '#111',
94
- '$gap': '8px',
95
- '$radius': '4px',
117
+ $gap: '8px',
118
+ $radius: '4px',
96
119
  '$border-width': '1px',
97
120
  '$outline-width': '2px',
98
121
  },
@@ -146,25 +169,25 @@ export default [
146
169
 
147
170
  ### What `recommended` catches
148
171
 
149
- The `recommended` config enables 18 of the plugin's 27 total rules. It covers the most common issues without turning on the stricter governance rules:
172
+ The `recommended` config covers common correctness and style issues:
150
173
 
151
- | Category | Rules | Examples |
152
- |----------|-------|---------|
153
- | Property validation | `known-property`, `valid-boolean-property`, `valid-sub-element` | Flags typos like `pading` or invalid boolean usage |
154
- | Value validation | `valid-value`, `valid-color-token`, `valid-custom-unit` | Catches `#nonexistent` tokens, bad unit syntax |
155
- | State validation | `valid-state-key`, `no-nested-state-map`, `require-default-state` | Validates state key syntax, ensures `''` default exists |
156
- | Structure | `valid-styles-structure`, `no-important`, `no-nested-selector` | Prevents `!important`, invalid nesting |
157
- | Static mode | `static-no-dynamic-values`, `static-valid-selector` | Enforces build-time constraints in `tastyStatic()` |
158
- | Style properties | `valid-preset`, `valid-recipe`, `valid-transition`, `valid-directional-modifier`, `valid-radius-shape` | Validates preset names, recipe references, transition syntax |
174
+ | Category | Rules | Examples |
175
+ | ------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------- |
176
+ | Property validation | `known-property`, `valid-boolean-property`, `valid-sub-element` | Flags typos like `pading` or invalid boolean usage |
177
+ | Value validation | `valid-value`, `valid-color-token`, `valid-custom-unit` | Catches `#nonexistent` tokens, bad unit syntax |
178
+ | State validation | `valid-state-key`, `no-nested-state-map`, `require-default-state` | Validates state key syntax, ensures `''` default exists |
179
+ | Structure | `valid-styles-structure`, `no-important`, `no-nested-selector` | Prevents `!important`, invalid nesting |
180
+ | Static mode | `static-no-dynamic-values`, `static-valid-selector` | Enforces build-time constraints in `tastyStatic()` |
181
+ | Style properties | `valid-preset`, `valid-recipe`, `valid-transition`, `valid-directional-modifier`, `valid-radius-shape` | Validates preset names, recipe references, transition syntax |
182
+ | Motion guidance | `no-raw-transition-duration` | Suggests timing tokens or the default timing for transition durations |
183
+ | Dynamic styles | `no-runtime-styles-mutation`, `no-style-spread` | Warns on JavaScript values and spreads inside runtime style objects |
159
184
 
160
185
  ### Strict config
161
186
 
162
- For stricter governance, use `tasty.configs.strict`. It adds rules that enforce best practices like preferring shorthand properties, consistent token usage, and flagging direct `styles` prop usage:
187
+ For stricter governance, use `tasty.configs.strict`. It adds rules that flag direct `styles` prop usage and other patterns:
163
188
 
164
189
  ```js
165
- export default [
166
- tasty.configs.strict,
167
- ];
190
+ export default [tasty.configs.strict];
168
191
  ```
169
192
 
170
193
  ---
@@ -179,19 +202,19 @@ export default [
179
202
 
180
203
  ## Choosing a rendering mode
181
204
 
182
- `tasty()` is the default for all React apps. All `tasty()` components and style functions are hook-free and work as React Server Components without `'use client'`. In server-only contexts, they produce zero client JavaScript with the full feature set.
205
+ `tasty()` is the default for all React apps. All `tasty()` components and style functions are hook-free and work as React Server Components without `'use client'`. Zero-runtime delivery is not tied to one API: both server-only `tasty()` and build-time `tastyStatic()` can ship no Tasty styling runtime to the browser.
183
206
 
184
- | Approach | Entry point | Best for | Trade-off |
185
- |------|-------------|----------|-----------|
186
- | **Runtime (default)** | `tasty()` from `@tenphi/tasty` | All React apps — server-rendered by default, zero client JS until you need interactivity | Full feature set (styleProps, sub-elements, variants); CSS computed during rendering |
187
- | **Runtime + SSR integration** | Add `@tenphi/tasty/ssr/*` | Apps with client-side hydration (Next.js client components, Astro islands) | Adds CSS batching, deduplication, FOUC prevention, and client cache hydration |
188
- | **Zero-runtime** | `tastyStatic()` from `@tenphi/tasty/static` | Non-React frameworks or build-time extraction without React | Requires Babel plugin; no `styleProps` or runtime-only APIs |
207
+ | Approach | Authoring API | CSS is generated | Tasty runtime in the browser | Best for |
208
+ | ------------------------- | ------------------------------------------- | ----------------------------------- | ---------------------------- | ---------------------------------------------------------------- |
209
+ | **Server-only React** | `tasty()`; optional `@tenphi/tasty/ssr/*` | During server or static rendering | None | Astro without islands, server-only RSC, SSG |
210
+ | **Hydrated React** | `tasty()` plus `@tenphi/tasty/ssr/*` | During SSR, then on demand in React | Only in hydrated components | Interactive React apps, Next.js client components, Astro islands |
211
+ | **Build-time extraction** | `tastyStatic()` from `@tenphi/tasty/static` | During the build | None in file mode | Non-React frameworks or extraction before rendering |
189
212
 
190
213
  Both `tasty()` and `tastyStatic()` share the same DSL, tokens, units, and state mappings.
191
214
 
192
- - **Runtime** is the default and requires no extra setup beyond `@tenphi/tasty`. In server-only contexts (Next.js RSC, Astro without `client:*` directives, SSG), `tasty()` produces static HTML + CSS with zero client JavaScript — the same end result as `tastyStatic()` but with the full feature set. For example, `tasty()` + `tastyIntegration()` in Astro without islands gives you the complete API with zero JS shipped.
193
- - **SSR integration** is only needed when your app also has client-side rendering. Add `@tenphi/tasty/ssr/next`, `@tenphi/tasty/ssr/astro`, or the core SSR API to get CSS deduplication and cache hydration. See [Server-Side Rendering](ssr.md).
194
- - **Zero-runtime** requires the Babel plugin and additional peer dependencies. Use it when you need build-time extraction without a React runtime. See [Zero Runtime (tastyStatic)](tasty-static.md).
215
+ - **Server-only `tasty()`** keeps the full feature set (`styleProps`, sub-elements, variants) while generating CSS during server rendering. `tasty()` plus `tastyIntegration({ islands: false })` in Astro is the verified concrete setup and ships no client JavaScript. The same server-only architecture applies to Next.js RSC; verify the generated output for your deployment.
216
+ - **Hydrated `tasty()`** uses the SSR integrations to batch and deduplicate server CSS, prevent FOUC, and hydrate the client cache. The browser styling pipeline is available only where React components hydrate. See [Server-Side Rendering](ssr.md).
217
+ - **Build-time extraction** uses the Babel plugin and additional peer dependencies. Choose `tastyStatic()` when CSS must be generated before rendering or when the consumer is not React. File mode ships no styling runtime; inject mode intentionally includes a tiny CSS injector. See [Build-Time Extraction (`tastyStatic`)](tasty-static.md).
195
218
 
196
219
  ---
197
220
 
@@ -214,4 +237,4 @@ Both `tasty()` and `tastyStatic()` share the same DSL, tokens, units, and state
214
237
 
215
238
  - Styles are missing on first render: make sure the file that calls `configure()` is imported before any `tasty()` component renders.
216
239
  - Token or unit values are not what you expect: check your `configure({ tokens, units })` setup, then inspect the generated CSS variables with [Debug Utilities](debug.md).
217
- - You need build-time extraction or server-rendered CSS delivery: use [Zero Runtime (tastyStatic)](tasty-static.md) for extraction, or add [Server-Side Rendering](ssr.md) on top of runtime `tasty()` when your framework renders on the server.
240
+ - You need zero-runtime delivery: use server-only [`tasty()` with server rendering](ssr.md) to keep the full React API, or use [`tastyStatic()` build-time extraction](tasty-static.md) when styles must be compiled before rendering.
package/docs/injector.md CHANGED
@@ -9,9 +9,9 @@ A high-performance CSS-in-JS solution that powers the Tasty design system with e
9
9
  The Style Injector is the core engine behind Tasty's styling system, providing:
10
10
 
11
11
  - **Hash-based deduplication** - Identical CSS gets the same className
12
- - **Reference counting** - Automatic cleanup when components unmount (refCount = 0)
12
+ - **DOM-driven lifetime** - Styles are collected once nothing renders them
13
13
  - **CSS nesting flattening** - Handles `&`, `.Class`, `SubElement` patterns
14
- - **Keyframes injection** - First-class `@keyframes` support with immediate disposal
14
+ - **At-rule injection** - First-class `@keyframes`, `@property`, `@font-face`, `@counter-style`, and `@function` support
15
15
  - **Smart cleanup** - CSS rules batched cleanup, keyframes disposed immediately
16
16
  - **SSR support** - Deterministic class names and CSS extraction
17
17
  - **Multiple roots** - Works with Document and ShadowRoot
@@ -63,10 +63,16 @@ const result = inject([{
63
63
 
64
64
  console.log(result.className); // 't-abc123'
65
65
 
66
- // Cleanup when component unmounts (refCount decremented)
66
+ // Release the pin; the class becomes collectible once nothing renders it
67
67
  result.dispose();
68
68
  ```
69
69
 
70
+ `inject()` **pins** the class it returns, and `gc()` never evicts a pinned class
71
+ — that is what `dispose()` releases. Pass `{ pin: false }` when the caller keeps
72
+ no handle and the DOM is the only record that the class is in use; `dispose()`
73
+ is then a no-op. The render path (`tasty()` / `computeStyles()`) injects this
74
+ way, because a hook-free render has no unmount signal to dispose on.
75
+
70
76
  ### `injectGlobal(rules, options?): { dispose: () => void }`
71
77
 
72
78
  Injects global styles that don't reserve tasty class names.
@@ -226,12 +232,73 @@ configure({
226
232
  - `devMode`: Automatically enabled in development environments (detected via `isDevEnv()`)
227
233
  - `forceTextInjection`: Automatically enabled in test environments (Jest, Vitest, Mocha, happy-dom, jsdom)
228
234
 
235
+ **Injection Modes:**
236
+
237
+ Each sheet picks its write mode once, when it is created, and keeps it for its
238
+ lifetime:
239
+
240
+ | Mode | How rules are written | How rules are removed |
241
+ |---|---|---|
242
+ | CSSOM (default) | `styleSheet.insertRule(rule, index)` | `styleSheet.deleteRule(index)` |
243
+ | Text (`forceTextInjection`, or when `styleElement.sheet` is unavailable) | appended to `<style>.textContent` | rule texts are tracked per sheet and the element's text is rebuilt without them |
244
+ | Adopted (ShadowRoot with constructable sheets) | `insertRule` on the constructable sheet | `deleteRule` on the constructable sheet |
245
+
246
+ Text mode cannot edit a single rule in place the way CSSOM can, so the sheet
247
+ keeps the inserted rule texts in index order and rewrites the element on delete.
248
+ Dispose, ref-counted cleanup and GC therefore behave identically in every mode.
249
+
229
250
  **Configuration Notes:**
230
251
  - Most options have sensible defaults and auto-detection
231
252
  - `configure()` is optional - the injector works with defaults
232
253
  - **Configuration is locked after styles are generated** - calling `configure()` after first render will emit a warning and be ignored
233
- - `gc.touchInterval`: Number of touch events between GC cycles. Each style render counts as a touch. When the counter reaches this value, GC is scheduled via `requestIdleCallback`.
234
- - `gc.capacity`: Maximum number of unused styles (refCount = 0, not in DOM) to retain. When exceeded, the oldest are evicted first. Actively referenced styles don't count against this limit.
254
+ - `gc.touchInterval`: Number of renders between sweeps. When the counter reaches this value, a sweep is scheduled via `requestIdleCallback`; without idle callbacks nothing is collected automatically.
255
+ - `gc.grace`: How long a class is left alone after collection first notices nothing is carrying it, in milliseconds (default `10000`).
256
+
257
+ **What a sweep does.** Everything the injector holds falls into one of five bands, and only the last is ever deleted:
258
+
259
+ | Band | | Deleted |
260
+ |---|---|---|
261
+ | 1 | **Rendered** — some element carries the class right now | never |
262
+ | 2 | **Not ours** — queued for a batched write, pre-allocated, or server-rendered | never |
263
+ | 3 | **Hot** — nothing carries it, but that was noticed less than `grace` ago | never |
264
+ | 4 | **Cached** — cold, but within `capacity` when ordered by when it went cold | never |
265
+ | 5 | Everything else | on every sweep |
266
+
267
+ `gc({ force: true })` and `cleanup()` take bands 4 and 5 together, ignoring capacity. Band 3 is spared even then: an explicit cleanup is still no reason to take rules from a render that has not committed yet.
268
+
269
+ > **Why band 3 exists.** Rendering is not commit-aware: a render can resolve a class and commit it a little later, and in between nothing on the page carries it. From outside React that is indistinguishable from a class that is finished, so collection does not try to tell them apart — it leaves alone anything only just noticed to be cold. A render would have to stay pending for the whole window to lose its rules, and it gets them back on its next render.
270
+ >
271
+ > The clock starts when a sweep *notices*, not when the element actually left — nothing observes that moment, so starting it at the sighting is what gives every class the same full window however long ago it went.
272
+ >
273
+ > This is also why collection costs nothing to run: the timestamps are written by the sweep's own DOM scan, so rendering tracks nothing per class.
274
+ - `gc.capacity`: Maximum number of unused styles (not in the DOM, not pinned) to retain. When exceeded, the least recently used are evicted first. Rendered and pinned styles don't count against this limit.
275
+
276
+ ---
277
+
278
+ ### At-rule injection
279
+
280
+ Beyond ordinary rules, the injector has a dedicated entry point per at-rule. All of them deduplicate by name and are **permanent** — there is no ref-counting or dispose, because a rule that other CSS references by name cannot be safely removed while any of it might still apply.
281
+
282
+ | Function | Injects | Notes |
283
+ |---|---|---|
284
+ | `keyframes(steps, nameOrOptions?)` | `@keyframes` | The exception: ref-counted and disposed immediately when unused. Returns the injected name, which may differ from the requested one. |
285
+ | `property(name, options?)` | `@property` | `name` accepts `$name`, `#name`, or `--name`. Usually unnecessary — types are inferred automatically unless `configure({ autoPropertyTypes: false })`. |
286
+ | `fontFace(family, descriptors, options?)` | `@font-face` | Deduplicated by family **and** descriptor content, so several faces of one family coexist. |
287
+ | `counterStyle(name, descriptors, options?)` | `@counter-style` | |
288
+ | `func(name, definition, options?)` | `@function` | `name` accepts `$$name`, `$name`, or `--name`. Abbreviated because `function` is a reserved word. |
289
+
290
+ Every one of these takes an optional `root` (a `Document` or `ShadowRoot`).
291
+
292
+ `func()` also accepts `weak: true`, which registers the rule **without** overriding an existing one of the same name. `configure()` uses it for global `@function` definitions so a component-local definition always wins over the global default, regardless of which is injected first.
293
+
294
+ ```ts
295
+ import { counterStyle, fontFace, func, property } from '@tenphi/tasty';
296
+
297
+ property('$card-elevation', { syntax: '<number>', initialValue: '0' });
298
+ fontFace('Inter', { src: 'url(/inter.woff2)', fontWeight: '400 700' });
299
+ counterStyle('dashes', { system: 'cyclic', symbols: '"—"', suffix: ' ' });
300
+ func('$$negative', { args: ['$value'], result: '(-1 * $value)' });
301
+ ```
235
302
 
236
303
  ---
237
304
 
@@ -258,6 +325,17 @@ const styleRule: StyleResult = {
258
325
  };
259
326
  ```
260
327
 
328
+ ### Batched Injection
329
+
330
+ `configure({ batchInjection: true })` queues every sheet write — component
331
+ rules, global rules, raw CSS and at-rules — into one FIFO and applies them
332
+ together, so the document is style-invalidated once per flush instead of once per
333
+ component. `<TastyBatchProvider>` flushes in `useInsertionEffect`, before any
334
+ layout effect, so a queued write can never be observed by a measurement. See
335
+ [Batched injection](configuration.md#batched-injection) for the modes and the
336
+ ordering guarantee. `flushStyles()` applies pending writes on demand; every read
337
+ API here calls it for you.
338
+
261
339
  ### Deduplication & Performance
262
340
 
263
341
  ```typescript
@@ -276,23 +354,28 @@ const button2 = inject([{
276
354
  console.log(button1.className === button2.className); // true
277
355
  ```
278
356
 
279
- ### Reference Counting
357
+ ### Pinning
280
358
 
281
359
  ```typescript
282
- // Multiple components using the same styles
360
+ // Multiple callers using the same styles
283
361
  const comp1 = inject([commonStyle]);
284
362
  const comp2 = inject([commonStyle]);
285
363
  const comp3 = inject([commonStyle]);
286
364
 
287
- // Style is kept alive while any component uses it
288
- comp1.dispose(); // refCount: 3 → 2
289
- comp2.dispose(); // refCount: 2 → 1
290
- comp3.dispose(); // refCount: 1 → 0, eligible for bulk cleanup
365
+ // Style is pinned while any caller holds a handle
366
+ comp1.dispose(); // pins: 3 → 2
367
+ comp2.dispose(); // pins: 2 → 1
368
+ comp3.dispose(); // pins: 1 → 0, now up to the DOM and gc()
291
369
 
292
- // Rule exists but refCount = 0 means unused
293
- // Next inject() with same styles will increment refCount and reuse immediately
370
+ // Unpinned does not mean deleted: the rule stays cached and is reused instantly
371
+ // by the next inject(). gc() decides when it actually goes.
294
372
  ```
295
373
 
374
+ Pinning covers callers that hold a handle. Styles that come from rendering are
375
+ never pinned — see `{ pin: false }` under
376
+ [`inject()`](#injectrules-options-injectresult) — so what keeps them alive is
377
+ being in the DOM, and nothing else.
378
+
296
379
  ### Garbage Collection
297
380
 
298
381
  ```typescript
@@ -300,6 +383,9 @@ import { configure, gc } from '@tenphi/tasty';
300
383
 
301
384
  // Keyframes: Disposed immediately when refCount = 0 (safer for global scope)
302
385
  // CSS rules: Tracked by touch count and cleaned up via gc()
386
+ //
387
+ // A CSS rule is collectible when no element carries its class AND nobody
388
+ // pinned it with inject().
303
389
 
304
390
  configure({
305
391
  gc: {
@@ -314,15 +400,19 @@ gc();
314
400
  // Force-remove ALL unused styles (e.g. on route change or test teardown):
315
401
  gc({ force: true });
316
402
 
317
- // GC is also triggered automatically by touch count during rendering.
318
- // Every `touchInterval` touches, GC is scheduled via requestIdleCallback.
403
+ // cleanup() is the same thing:
404
+ cleanup();
405
+
406
+ // Every `touchInterval` renders, a sweep is scheduled in idle time. It scans
407
+ // the DOM for the classes actually on the page and sorts everything the
408
+ // injector holds into five bands — only the last one is deleted. See below.
319
409
 
320
410
  // Benefits:
321
411
  // - Activity-proportional: busy apps trigger GC more often
322
412
  // - DOM-safe: styles currently in the DOM are never evicted
323
413
  // - Oldest-first: least recently used styles are evicted first
324
414
  // - Keyframes: Immediate cleanup prevents global namespace pollution
325
- // - Unused styles can be instantly reactivated (just increment refCount)
415
+ // - Unused styles stay cached until evicted, so re-rendering them is a cache hit
326
416
  ```
327
417
 
328
418
  ### Shadow DOM Support
@@ -350,14 +440,14 @@ const shadowAnimation = keyframes({
350
440
  ### Server-Side Rendering
351
441
 
352
442
  ```typescript
353
- import { getCssText, getCssTextForNode } from '@tenphi/tasty';
443
+ import { getCSSText, getCSSTextForNode } from '@tenphi/tasty';
354
444
 
355
445
  // Extract all CSS for SSR
356
- const cssText = getCssText();
446
+ const cssText = getCSSText();
357
447
 
358
448
  // Extract CSS for specific DOM subtree (like jest-styled-components)
359
449
  const container = render(<MyComponent />);
360
- const componentCSS = getCssTextForNode(container);
450
+ const componentCSS = getCSSTextForNode(container);
361
451
  ```
362
452
 
363
453
  ### Test Environment Detection
@@ -417,11 +507,11 @@ const metrics = injector.instance.getMetrics();
417
507
  console.log({
418
508
  cacheHits: metrics.hits, // Successful cache hits
419
509
  cacheMisses: metrics.misses, // New styles injected
420
- unusedHits: metrics.unusedHits, // Current unused styles (calculated on demand)
510
+ unusedHits: metrics.unusedHits, // Styles currently eligible for eviction (scans the DOM)
421
511
  bulkCleanups: metrics.bulkCleanups, // Number of bulk cleanup operations
422
512
  stylesCleanedUp: metrics.stylesCleanedUp, // Total styles removed in bulk cleanups
423
513
  totalInsertions: metrics.totalInsertions, // Lifetime insertions
424
- totalUnused: metrics.totalUnused, // Total styles marked as unused (refCount = 0)
514
+ totalUnused: metrics.totalUnused, // Times a pinned style lost its last pin
425
515
  startTime: metrics.startTime, // Metrics collection start timestamp
426
516
  cleanupHistory: metrics.cleanupHistory, // Detailed cleanup operation history
427
517
  });
@@ -465,10 +555,10 @@ metrics.cleanupHistory.forEach(cleanup => {
465
555
 
466
556
  ```typescript
467
557
  // ✅ Reuse styles - identical CSS gets deduplicated
468
- const buttonBase = { padding: '8px 16px', borderRadius: '4px' };
558
+ const buttonBase = 'padding: 8px 16px; border-radius: 4px;';
469
559
 
470
560
  // ✅ Avoid frequent disposal and re-injection
471
- // Let the reference counting system handle cleanup
561
+ // Let the injector handle cleanup
472
562
 
473
563
  // ✅ Use bulk operations for global styles
474
564
  injectGlobal([
@@ -494,13 +584,13 @@ configure({
494
584
  // The injector automatically manages memory through:
495
585
 
496
586
  // 1. Hash-based deduplication - same CSS = same className
497
- // 2. Reference counting - styles stay alive while in use (refCount > 0)
498
- // 3. Immediate keyframes cleanup - disposed instantly when refCount = 0
499
- // 4. Touch-count GC - unused CSS rules are evicted oldest-first when over capacity
500
- // 5. DOM safety guard - styles visible in the DOM are never evicted
587
+ // 2. DOM-driven lifetime - a rendered class is never evicted
588
+ // 3. Pinning - inject() callers hold their classes until they dispose
589
+ // 4. Immediate keyframes cleanup - disposed instantly when refCount = 0
590
+ // 5. Touch-count GC - unused CSS rules are evicted oldest-first when over capacity
501
591
 
502
592
  // Manual cleanup is rarely needed but available:
503
- cleanup(); // Force immediate cleanup of all unused CSS rules (refCount = 0)
593
+ cleanup(); // Remove every rule that is neither rendered nor pinned
504
594
  destroy(); // Nuclear option: remove all stylesheets and reset
505
595
  ```
506
596
 
@@ -522,9 +612,9 @@ const StyledButton = tasty({
522
612
 
523
613
  // Internally uses the injector:
524
614
  // 1. Styles are parsed into StyleResult objects
525
- // 2. inject() is called with the parsed results
615
+ // 2. inject() is called with the parsed results, unpinned
526
616
  // 3. Component gets the returned className
527
- // 4. dispose() is called when component unmounts
617
+ // 4. gc() reclaims the class once no element carries it
528
618
  ```
529
619
 
530
620
  For most development, you'll use the [React API](./react-api.md) rather than the injector directly. The injector provides the high-performance foundation that makes Tasty's declarative styling possible.