@tenphi/tasty 0.0.0-snapshot.0003ae6

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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +685 -0
  3. package/dist/babel-rZcEwPLM.d.ts +82 -0
  4. package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
  5. package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
  6. package/dist/chunks/build-config-_cm7XDZ0.js +42 -0
  7. package/dist/chunks/build-config-_cm7XDZ0.js.map +1 -0
  8. package/dist/chunks/collector-DZh0frqA.js +208 -0
  9. package/dist/chunks/collector-DZh0frqA.js.map +1 -0
  10. package/dist/chunks/config-engine-B9arIU78.js +272 -0
  11. package/dist/chunks/config-engine-B9arIU78.js.map +1 -0
  12. package/dist/chunks/css-definitions-LxHlQWqa.js +876 -0
  13. package/dist/chunks/css-definitions-LxHlQWqa.js.map +1 -0
  14. package/dist/chunks/css-resources-P7IBUUZs.js +142 -0
  15. package/dist/chunks/css-resources-P7IBUUZs.js.map +1 -0
  16. package/dist/chunks/debug-Cp6kyH_o.js +502 -0
  17. package/dist/chunks/debug-Cp6kyH_o.js.map +1 -0
  18. package/dist/chunks/dsl-MW8TZusz.js +1377 -0
  19. package/dist/chunks/dsl-MW8TZusz.js.map +1 -0
  20. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  21. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  22. package/dist/chunks/react-runtime-DFK-u-KU.js +562 -0
  23. package/dist/chunks/react-runtime-DFK-u-KU.js.map +1 -0
  24. package/dist/chunks/runtime-engine-BNE2KUiS.js +2412 -0
  25. package/dist/chunks/runtime-engine-BNE2KUiS.js.map +1 -0
  26. package/dist/chunks/runtime-state-BsBWQeBn.js +127 -0
  27. package/dist/chunks/runtime-state-BsBWQeBn.js.map +1 -0
  28. package/dist/chunks/shared-utils-CGMsLq--.js +148 -0
  29. package/dist/chunks/shared-utils-CGMsLq--.js.map +1 -0
  30. package/dist/chunks/style-engine-BuW7q07d.js +5260 -0
  31. package/dist/chunks/style-engine-BuW7q07d.js.map +1 -0
  32. package/dist/chunks/zero-engine-DzsBXgfk.js +275 -0
  33. package/dist/chunks/zero-engine-DzsBXgfk.js.map +1 -0
  34. package/dist/collector-w4mBj5gd.d.ts +164 -0
  35. package/dist/config-CZWCzBr6.d.ts +1349 -0
  36. package/dist/core/index.d.ts +5 -0
  37. package/dist/core/index.js +9 -0
  38. package/dist/index-G9JuwM9p.d.ts +1920 -0
  39. package/dist/index.d.ts +5 -0
  40. package/dist/index.js +11 -0
  41. package/dist/merge-styles-VXwJ0Frr.d.ts +6 -0
  42. package/dist/ssr/astro-client.d.ts +1 -0
  43. package/dist/ssr/astro-client.js +6 -0
  44. package/dist/ssr/astro-client.js.map +1 -0
  45. package/dist/ssr/astro-middleware-extract-static.d.ts +10 -0
  46. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  47. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  48. package/dist/ssr/astro-middleware-extract.d.ts +10 -0
  49. package/dist/ssr/astro-middleware-extract.js +9 -0
  50. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  51. package/dist/ssr/astro-middleware-static.d.ts +17 -0
  52. package/dist/ssr/astro-middleware-static.js +7 -0
  53. package/dist/ssr/astro-middleware-static.js.map +1 -0
  54. package/dist/ssr/astro-middleware.d.ts +18 -0
  55. package/dist/ssr/astro-middleware.js +7 -0
  56. package/dist/ssr/astro-middleware.js.map +1 -0
  57. package/dist/ssr/astro.d.ts +127 -0
  58. package/dist/ssr/astro.js +221 -0
  59. package/dist/ssr/astro.js.map +1 -0
  60. package/dist/ssr/index.d.ts +36 -0
  61. package/dist/ssr/index.js +10 -0
  62. package/dist/ssr/index.js.map +1 -0
  63. package/dist/ssr/next-config.d.ts +64 -0
  64. package/dist/ssr/next-config.js +128 -0
  65. package/dist/ssr/next-config.js.map +1 -0
  66. package/dist/ssr/next.d.ts +46 -0
  67. package/dist/ssr/next.js +60 -0
  68. package/dist/ssr/next.js.map +1 -0
  69. package/dist/static/index.d.ts +90 -0
  70. package/dist/static/index.js +32 -0
  71. package/dist/static/index.js.map +1 -0
  72. package/dist/static/inject.d.ts +4 -0
  73. package/dist/static/inject.js +17 -0
  74. package/dist/static/inject.js.map +1 -0
  75. package/dist/types-JEY8PVYP.d.ts +1567 -0
  76. package/dist/zero/babel.d.ts +2 -0
  77. package/dist/zero/babel.js +412 -0
  78. package/dist/zero/babel.js.map +1 -0
  79. package/dist/zero/index.d.ts +80 -0
  80. package/dist/zero/index.js +2 -0
  81. package/dist/zero/next.d.ts +84 -0
  82. package/dist/zero/next.js +112 -0
  83. package/dist/zero/next.js.map +1 -0
  84. package/docs/README.md +39 -0
  85. package/docs/adoption.md +323 -0
  86. package/docs/ai-agents.md +250 -0
  87. package/docs/comparison.md +448 -0
  88. package/docs/configuration.md +839 -0
  89. package/docs/debug.md +332 -0
  90. package/docs/design-system.md +455 -0
  91. package/docs/dsl.md +1065 -0
  92. package/docs/getting-started.md +240 -0
  93. package/docs/injector.md +634 -0
  94. package/docs/methodology.md +648 -0
  95. package/docs/migration-v3.md +285 -0
  96. package/docs/pipeline.md +765 -0
  97. package/docs/plugins.md +353 -0
  98. package/docs/react-api.md +683 -0
  99. package/docs/runtime-benchmarks.md +388 -0
  100. package/docs/ssr.md +610 -0
  101. package/docs/styles.md +715 -0
  102. package/docs/tasty-static.md +582 -0
  103. package/package.json +314 -0
  104. package/tasty.config.ts +20 -0
@@ -0,0 +1,634 @@
1
+ # Tasty Style Injector
2
+
3
+ A high-performance CSS-in-JS solution that powers the Tasty design system with efficient style injection, automatic cleanup, and first-class SSR support.
4
+
5
+ ---
6
+
7
+ ## Overview
8
+
9
+ The Style Injector is the core engine behind Tasty's styling system, providing:
10
+
11
+ - **Hash-based deduplication** - Identical CSS gets the same className
12
+ - **DOM-driven lifetime** - Styles are collected once nothing renders them
13
+ - **CSS nesting flattening** - Handles `&`, `.Class`, `SubElement` patterns
14
+ - **At-rule injection** - First-class `@keyframes`, `@property`, `@font-face`, `@counter-style`, and `@function` support
15
+ - **Smart cleanup** - CSS rules batched cleanup, keyframes disposed immediately
16
+ - **SSR support** - Deterministic class names and CSS extraction
17
+ - **Multiple roots** - Works with Document and ShadowRoot
18
+ - **Non-stacking cleanups** - Prevents timeout accumulation for better performance
19
+
20
+ > **Note:** This is internal infrastructure that powers Tasty components. Most developers will interact with the higher-level `tasty()` API instead.
21
+
22
+ ---
23
+
24
+ ## Architecture
25
+
26
+ ```
27
+ ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
28
+ │ tasty() │────│ Style Injector │────│ Sheet Manager │
29
+ │ components │ │ │ │ │
30
+ └─────────────────┘ └──────────────────┘ └─────────────────┘
31
+ │ │ │
32
+ │ │ │
33
+ ▼ ▼ ▼
34
+ ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
35
+ │ Style Results │ │ Keyframes Manager│ │ Root Registry │
36
+ │ (CSS rules) │ │ │ │ │
37
+ └─────────────────┘ └──────────────────┘ └─────────────────┘
38
+ │ │
39
+ │ │
40
+ ▼ ▼
41
+ ┌─────────────────┐ ┌─────────────────┐
42
+ │ Hash Cache │ │ <style> elements│
43
+ │ Deduplication │ │ CSSStyleSheet │
44
+ └─────────────────┘ └─────────────────┘
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Core API
50
+
51
+ ### `inject(rules, options?): InjectResult`
52
+
53
+ Injects CSS rules and returns a className with dispose function.
54
+
55
+ ```typescript
56
+ import { inject } from '@tenphi/tasty';
57
+
58
+ // Component styling - generates tasty class names
59
+ const result = inject([{
60
+ selector: '.t-abc123',
61
+ declarations: 'color: red; padding: 10px;',
62
+ }]);
63
+
64
+ console.log(result.className); // 't-abc123'
65
+
66
+ // Release the pin; the class becomes collectible once nothing renders it
67
+ result.dispose();
68
+ ```
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
+
76
+ ### `injectGlobal(rules, options?): { dispose: () => void }`
77
+
78
+ Injects global styles that don't reserve tasty class names.
79
+
80
+ ```typescript
81
+ // Global styles - for body, resets, etc.
82
+ const globalResult = injectGlobal([
83
+ {
84
+ selector: 'body',
85
+ declarations: 'margin: 0; font-family: Arial;',
86
+ },
87
+ {
88
+ selector: '.header',
89
+ declarations: 'background: blue; color: white;',
90
+ atRules: ['@media (min-width: 768px)'],
91
+ }
92
+ ]);
93
+
94
+ // Only returns dispose function - no className needed for global styles
95
+ globalResult.dispose();
96
+ ```
97
+
98
+ ### `injectRawCSS(css, options?): { dispose: () => void }`
99
+
100
+ Injects raw CSS text directly without parsing. This is a low-overhead method for injecting CSS that doesn't need tasty processing.
101
+
102
+ ```typescript
103
+ import { injectRawCSS } from '@tenphi/tasty';
104
+
105
+ // Inject raw CSS
106
+ const { dispose } = injectRawCSS(`
107
+ body {
108
+ margin: 0;
109
+ padding: 0;
110
+ font-family: sans-serif;
111
+ }
112
+
113
+ .my-class {
114
+ color: red;
115
+ }
116
+ `);
117
+
118
+ // Later, remove the injected CSS
119
+ dispose();
120
+ ```
121
+
122
+ ### `useRawCSS(css, options?)` or `useRawCSS(factory, deps, options?)`
123
+
124
+ Inject raw CSS without parsing. Hook-free — works in client components, SSR, and React Server Components.
125
+
126
+ Supports two overloads:
127
+ - **Static CSS**: `useRawCSS(cssString, options?)` — content-based deduplication
128
+ - **Factory function**: `useRawCSS(() => cssString, deps, options?)` — factory called on every invocation, dedup handled internally
129
+
130
+ Use the `id` option for update tracking — when the CSS changes for the same id, the previous injection is replaced:
131
+
132
+ ```tsx
133
+ import { useRawCSS } from '@tenphi/tasty';
134
+
135
+ // Static CSS
136
+ function GlobalReset() {
137
+ useRawCSS(`
138
+ body { margin: 0; padding: 0; }
139
+ `);
140
+ return null;
141
+ }
142
+
143
+ // Dynamic CSS with factory function and update tracking
144
+ function ThemeStyles({ theme }: { theme: 'dark' | 'light' }) {
145
+ useRawCSS(() => `
146
+ body {
147
+ margin: 0;
148
+ background: ${theme === 'dark' ? '#000' : '#fff'};
149
+ color: ${theme === 'dark' ? '#fff' : '#000'};
150
+ }
151
+ `, [theme], { id: 'theme-body' });
152
+
153
+ return null;
154
+ }
155
+ ```
156
+
157
+ ### `createInjector(config?): StyleInjector`
158
+
159
+ Creates an isolated injector instance with custom configuration.
160
+
161
+ ```typescript
162
+ import { createInjector } from '@tenphi/tasty';
163
+
164
+ // Create isolated instance for testing
165
+ const testInjector = createInjector({
166
+ devMode: true,
167
+ forceTextInjection: true,
168
+ });
169
+
170
+ const result = testInjector.inject(rules);
171
+ ```
172
+
173
+ ### `keyframes(steps, nameOrOptions?): KeyframesResult`
174
+
175
+ Injects CSS keyframes with automatic deduplication.
176
+
177
+ ```typescript
178
+ // Generated name (k0, k1, k2...)
179
+ const fadeIn = keyframes({
180
+ from: { opacity: 0 },
181
+ to: { opacity: 1 },
182
+ });
183
+
184
+ // Custom name
185
+ const slideIn = keyframes({
186
+ '0%': { transform: 'translateX(-100%)' },
187
+ '100%': { transform: 'translateX(0)' },
188
+ }, 'slideInAnimation');
189
+
190
+ // Use in tasty styles (recommended)
191
+ const AnimatedBox = tasty({
192
+ styles: {
193
+ animation: `${fadeIn} 300ms ease-in`,
194
+ },
195
+ });
196
+
197
+ // Or use with injectGlobal for fixed selectors
198
+ injectGlobal([{
199
+ selector: '.my-animated-class',
200
+ declarations: `animation: ${slideIn} 500ms ease-out;`
201
+ }]);
202
+
203
+ // Cleanup keyframes (if needed)
204
+ fadeIn.dispose(); // Immediate keyframes deletion from DOM
205
+ slideIn.dispose(); // Immediate keyframes deletion from DOM
206
+ ```
207
+
208
+ ### `configure(config): void`
209
+
210
+ Configures the Tasty style system. `configure()` is optional, but if you use it, it must be called **before** any styles are generated (before first render).
211
+
212
+ ```typescript
213
+ import { configure } from '@tenphi/tasty';
214
+
215
+ configure({
216
+ devMode: true, // Enable development features (auto-detected)
217
+ maxRulesPerSheet: 8192, // Cap rules per stylesheet (default: 8192)
218
+ forceTextInjection: false, // Force textContent insertion (auto-detected for tests)
219
+ nonce: 'csp-nonce', // CSP nonce for security
220
+ gc: { // Garbage collection for unused styles
221
+ touchInterval: 1000, // Touch events between GC cycles (default: 1000)
222
+ capacity: 1000, // Max unused styles to retain (default: 1000)
223
+ },
224
+ states: { // Global predefined states for advanced state mapping
225
+ '@mobile': '@media(w < 768px)',
226
+ '@dark': '@root(schema=dark)',
227
+ },
228
+ });
229
+ ```
230
+
231
+ **Auto-Detection Features:**
232
+ - `devMode`: Automatically enabled in development environments (detected via `isDevEnv()`)
233
+ - `forceTextInjection`: Automatically enabled in test environments (Jest, Vitest, Mocha, happy-dom, jsdom)
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
+
250
+ **Configuration Notes:**
251
+ - Most options have sensible defaults and auto-detection
252
+ - `configure()` is optional - the injector works with defaults
253
+ - **Configuration is locked after styles are generated** - calling `configure()` after first render will emit a warning and be ignored
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
+ ```
302
+
303
+ ---
304
+
305
+ ## Advanced Features
306
+
307
+ ### Style Result Format
308
+
309
+ The injector works with `StyleResult` objects from the tasty parser:
310
+
311
+ ```typescript
312
+ interface StyleResult {
313
+ selector: string; // CSS selector
314
+ declarations: string; // CSS declarations
315
+ atRules?: string[]; // @media, @supports, etc.
316
+ nestingLevel?: number; // Nesting depth for specificity
317
+ }
318
+
319
+ // Example StyleResult
320
+ const styleRule: StyleResult = {
321
+ selector: '.t-button',
322
+ declarations: 'padding: 8px 16px; background: blue; color: white;',
323
+ atRules: ['@media (min-width: 768px)'],
324
+ nestingLevel: 0,
325
+ };
326
+ ```
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
+
339
+ ### Deduplication & Performance
340
+
341
+ ```typescript
342
+ // Identical CSS rules get the same className
343
+ const button1 = inject([{
344
+ selector: '.t-btn1',
345
+ declarations: 'padding: 8px; color: red;'
346
+ }]);
347
+
348
+ const button2 = inject([{
349
+ selector: '.t-btn2',
350
+ declarations: 'padding: 8px; color: red;' // Same declarations
351
+ }]);
352
+
353
+ // Both get the same className due to deduplication
354
+ console.log(button1.className === button2.className); // true
355
+ ```
356
+
357
+ ### Pinning
358
+
359
+ ```typescript
360
+ // Multiple callers using the same styles
361
+ const comp1 = inject([commonStyle]);
362
+ const comp2 = inject([commonStyle]);
363
+ const comp3 = inject([commonStyle]);
364
+
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()
369
+
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.
372
+ ```
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
+
379
+ ### Garbage Collection
380
+
381
+ ```typescript
382
+ import { configure, gc } from '@tenphi/tasty';
383
+
384
+ // Keyframes: Disposed immediately when refCount = 0 (safer for global scope)
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().
389
+
390
+ configure({
391
+ gc: {
392
+ touchInterval: 1000, // Schedule GC every 1000 touches
393
+ capacity: 1000, // Max unused styles to retain
394
+ },
395
+ });
396
+
397
+ // Manual GC (synchronous, returns number of swept styles):
398
+ gc();
399
+
400
+ // Force-remove ALL unused styles (e.g. on route change or test teardown):
401
+ gc({ force: true });
402
+
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.
409
+
410
+ // Benefits:
411
+ // - Activity-proportional: busy apps trigger GC more often
412
+ // - DOM-safe: styles currently in the DOM are never evicted
413
+ // - Oldest-first: least recently used styles are evicted first
414
+ // - Keyframes: Immediate cleanup prevents global namespace pollution
415
+ // - Unused styles stay cached until evicted, so re-rendering them is a cache hit
416
+ ```
417
+
418
+ ### Shadow DOM Support
419
+
420
+ ```typescript
421
+ // Works with Shadow DOM
422
+ const shadowRoot = document.createElement('div').attachShadow({ mode: 'open' });
423
+
424
+ const shadowStyles = inject([{
425
+ selector: '.shadow-component',
426
+ declarations: 'color: purple;'
427
+ }], { root: shadowRoot });
428
+
429
+ // Keyframes in Shadow DOM
430
+ const shadowAnimation = keyframes({
431
+ from: { opacity: 0 },
432
+ to: { opacity: 1 }
433
+ }, { root: shadowRoot, name: 'shadowFade' });
434
+ ```
435
+
436
+ ---
437
+
438
+ ## SSR & Testing
439
+
440
+ ### Server-Side Rendering
441
+
442
+ ```typescript
443
+ import { getCSSText, getCSSTextForNode } from '@tenphi/tasty';
444
+
445
+ // Extract all CSS for SSR
446
+ const cssText = getCSSText();
447
+
448
+ // Extract CSS for specific DOM subtree (like jest-styled-components)
449
+ const container = render(<MyComponent />);
450
+ const componentCSS = getCSSTextForNode(container);
451
+ ```
452
+
453
+ ### Test Environment Detection
454
+
455
+ ```typescript
456
+ // Automatically detected test environments:
457
+ // - NODE_ENV === 'test'
458
+ // - Jest globals (jest, describe, it, expect)
459
+ // - jsdom / HappyDOM user agent
460
+ // - Vitest globals (vitest)
461
+ // - Mocha globals (mocha)
462
+
463
+ import { configure, isTestEnvironment, resetConfig } from '@tenphi/tasty';
464
+
465
+ const isTest = isTestEnvironment();
466
+
467
+ // Reset config between tests to allow reconfiguration
468
+ beforeEach(() => {
469
+ resetConfig();
470
+ configure({
471
+ forceTextInjection: isTest, // More reliable in test environments
472
+ devMode: true, // Always enable dev features in tests
473
+ });
474
+ });
475
+ ```
476
+
477
+ ### Memory Management in Tests
478
+
479
+ ```typescript
480
+ // Clean up between tests
481
+ afterEach(() => {
482
+ cleanup(); // Force cleanup of unused styles
483
+ });
484
+
485
+ // Full cleanup after test suite
486
+ afterAll(() => {
487
+ destroy(); // Destroy all stylesheets and reset state
488
+ });
489
+ ```
490
+
491
+ ---
492
+
493
+ ## Development Features
494
+
495
+ ### Performance Metrics
496
+
497
+ When `devMode` is enabled, the injector tracks comprehensive metrics:
498
+
499
+ ```typescript
500
+ import { configure, injector } from '@tenphi/tasty';
501
+
502
+ configure({ devMode: true });
503
+
504
+ // Access metrics through the global injector
505
+ const metrics = injector.instance.getMetrics();
506
+
507
+ console.log({
508
+ cacheHits: metrics.hits, // Successful cache hits
509
+ cacheMisses: metrics.misses, // New styles injected
510
+ unusedHits: metrics.unusedHits, // Styles currently eligible for eviction (scans the DOM)
511
+ bulkCleanups: metrics.bulkCleanups, // Number of bulk cleanup operations
512
+ stylesCleanedUp: metrics.stylesCleanedUp, // Total styles removed in bulk cleanups
513
+ totalInsertions: metrics.totalInsertions, // Lifetime insertions
514
+ totalUnused: metrics.totalUnused, // Times a pinned style lost its last pin
515
+ startTime: metrics.startTime, // Metrics collection start timestamp
516
+ cleanupHistory: metrics.cleanupHistory, // Detailed cleanup operation history
517
+ });
518
+ ```
519
+
520
+ ### Debug Information
521
+
522
+ ```typescript
523
+ // Get detailed information about injected styles
524
+ const debugInfo = injector.instance.getDebugInfo();
525
+
526
+ console.log({
527
+ activeStyles: debugInfo.activeStyles, // Currently active styles
528
+ unusedStyles: debugInfo.unusedStyles, // Styles marked for cleanup
529
+ totalSheets: debugInfo.totalSheets, // Number of stylesheets
530
+ totalRules: debugInfo.totalRules, // Total CSS rules
531
+ });
532
+ ```
533
+
534
+ ### Cleanup History
535
+
536
+ ```typescript
537
+ // Track cleanup operations over time
538
+ const metrics = injector.instance.getMetrics();
539
+
540
+ metrics.cleanupHistory.forEach(cleanup => {
541
+ console.log({
542
+ timestamp: new Date(cleanup.timestamp),
543
+ classesDeleted: cleanup.classesDeleted,
544
+ rulesDeleted: cleanup.rulesDeleted,
545
+ cssSize: cleanup.cssSize, // Total CSS size removed (bytes)
546
+ });
547
+ });
548
+ ```
549
+
550
+ ---
551
+
552
+ ## Performance Optimizations
553
+
554
+ ### Best Practices
555
+
556
+ ```typescript
557
+ // ✅ Reuse styles - identical CSS gets deduplicated
558
+ const buttonBase = 'padding: 8px 16px; border-radius: 4px;';
559
+
560
+ // ✅ Avoid frequent disposal and re-injection
561
+ // Let the injector handle cleanup
562
+
563
+ // ✅ Use bulk operations for global styles
564
+ injectGlobal([
565
+ { selector: 'body', declarations: 'margin: 0;' },
566
+ { selector: '*', declarations: 'box-sizing: border-box;' },
567
+ { selector: '.container', declarations: 'max-width: 1200px;' }
568
+ ]);
569
+
570
+ // ✅ Configure GC for your app (BEFORE first render!)
571
+ import { configure } from '@tenphi/tasty';
572
+
573
+ configure({
574
+ gc: {
575
+ touchInterval: 1000, // Schedule GC every 1000 style touches
576
+ capacity: 1000, // Max unused styles to retain
577
+ },
578
+ });
579
+ ```
580
+
581
+ ### Memory Management
582
+
583
+ ```typescript
584
+ // The injector automatically manages memory through:
585
+
586
+ // 1. Hash-based deduplication - same CSS = same className
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
591
+
592
+ // Manual cleanup is rarely needed but available:
593
+ cleanup(); // Remove every rule that is neither rendered nor pinned
594
+ destroy(); // Nuclear option: remove all stylesheets and reset
595
+ ```
596
+
597
+ ---
598
+
599
+ ## Integration with Tasty
600
+
601
+ The Style Injector is seamlessly integrated with the higher-level Tasty API:
602
+
603
+ ```jsx
604
+ // High-level tasty() API
605
+ const StyledButton = tasty({
606
+ styles: {
607
+ padding: '2x 4x',
608
+ fill: '#purple',
609
+ color: '#white',
610
+ }
611
+ });
612
+
613
+ // Internally uses the injector:
614
+ // 1. Styles are parsed into StyleResult objects
615
+ // 2. inject() is called with the parsed results, unpinned
616
+ // 3. Component gets the returned className
617
+ // 4. gc() reclaims the class once no element carries it
618
+ ```
619
+
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.
621
+
622
+ ---
623
+
624
+ ## When to Use Direct Injection
625
+
626
+ Direct injector usage is recommended for:
627
+
628
+ - **Custom CSS-in-JS libraries** built on top of Tasty
629
+ - **Global styles** that don't fit the component model
630
+ - **Third-party integration** where you need low-level CSS control
631
+ - **Performance-critical scenarios** where you need direct control
632
+ - **Testing utilities** that need to inject or extract CSS
633
+
634
+ For regular component styling, prefer the [`tasty()` API](./react-api.md) which provides a more developer-friendly interface.