@tenphi/tasty 0.0.0-snapshot.fafcbfe → 0.0.0-snapshot.fc19da9

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 (330) hide show
  1. package/README.md +497 -266
  2. package/dist/babel-types-DpUCD2L_.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-BDLYGmKn.js +60 -0
  6. package/dist/chunks/build-config-BDLYGmKn.js.map +1 -0
  7. package/dist/chunks/collector-DqcB0UUT.js +210 -0
  8. package/dist/chunks/collector-DqcB0UUT.js.map +1 -0
  9. package/dist/chunks/config-engine-CGIMO2PV.js +272 -0
  10. package/dist/chunks/config-engine-CGIMO2PV.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-BibU6ZnP.js +904 -0
  14. package/dist/chunks/css-definitions-BibU6ZnP.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-BzYPQ0H2.js +502 -0
  18. package/dist/chunks/debug-BzYPQ0H2.js.map +1 -0
  19. package/dist/chunks/dsl-DRhFWQzo.js +1378 -0
  20. package/dist/chunks/dsl-DRhFWQzo.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-B2e-Wha-.js +689 -0
  24. package/dist/chunks/react-runtime-B2e-Wha-.js.map +1 -0
  25. package/dist/chunks/runtime-engine-yeyCAx2e.js +2431 -0
  26. package/dist/chunks/runtime-engine-yeyCAx2e.js.map +1 -0
  27. package/dist/chunks/runtime-state-C0u1jp-Q.js +141 -0
  28. package/dist/chunks/runtime-state-C0u1jp-Q.js.map +1 -0
  29. package/dist/{utils/merge-styles.js → chunks/shared-utils-y-HjvPN4.js} +61 -58
  30. package/dist/chunks/shared-utils-y-HjvPN4.js.map +1 -0
  31. package/dist/chunks/style-engine-D35rvcdB.js +5420 -0
  32. package/dist/chunks/style-engine-D35rvcdB.js.map +1 -0
  33. package/dist/chunks/zero-engine-DpkieEPZ.js +310 -0
  34. package/dist/chunks/zero-engine-DpkieEPZ.js.map +1 -0
  35. package/dist/collector-D4POJ53X.d.ts +164 -0
  36. package/dist/config-DvPUj4cw.d.ts +1364 -0
  37. package/dist/core/index.d.ts +5 -33
  38. package/dist/core/index.js +9 -26
  39. package/dist/hydrate-CRyjjAyl.d.ts +22 -0
  40. package/dist/index-DC4q-xDq.d.ts +1946 -0
  41. package/dist/index.d.ts +5 -40
  42. package/dist/index.js +11 -33
  43. package/dist/{utils/merge-styles.d.ts → merge-styles-Jb5iZ-Jf.d.ts} +3 -4
  44. package/dist/ssr/astro-client.d.ts +1 -0
  45. package/dist/ssr/astro-client.js +6 -0
  46. package/dist/ssr/astro-client.js.map +1 -0
  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 +18 -0
  57. package/dist/ssr/astro-middleware.js +7 -0
  58. package/dist/ssr/astro-middleware.js.map +1 -0
  59. package/dist/ssr/astro.d.ts +127 -0
  60. package/dist/ssr/astro.js +221 -0
  61. package/dist/ssr/astro.js.map +1 -0
  62. package/dist/ssr/client.d.ts +2 -0
  63. package/dist/ssr/client.js +2 -0
  64. package/dist/ssr/index.d.ts +17 -0
  65. package/dist/ssr/index.js +10 -0
  66. package/dist/ssr/index.js.map +1 -0
  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 +46 -0
  71. package/dist/ssr/next.js +60 -0
  72. package/dist/ssr/next.js.map +1 -0
  73. package/dist/static/index.d.ts +90 -5
  74. package/dist/static/index.js +31 -4
  75. package/dist/static/index.js.map +1 -0
  76. package/dist/static/inject.d.ts +4 -0
  77. package/dist/static/inject.js +17 -0
  78. package/dist/static/inject.js.map +1 -0
  79. package/dist/types-ZbF2_6LV.d.ts +1567 -0
  80. package/dist/zero/babel.d.ts +49 -90
  81. package/dist/zero/babel.js +252 -119
  82. package/dist/zero/babel.js.map +1 -1
  83. package/dist/zero/index.d.ts +117 -3
  84. package/dist/zero/index.js +23 -3
  85. package/dist/zero/index.js.map +1 -0
  86. package/dist/zero/next.d.ts +58 -33
  87. package/dist/zero/next.js +89 -59
  88. package/dist/zero/next.js.map +1 -1
  89. package/docs/README.md +42 -0
  90. package/docs/adoption.md +331 -0
  91. package/docs/ai-agents.md +252 -0
  92. package/docs/comparison.md +449 -0
  93. package/docs/configuration.md +943 -0
  94. package/docs/debug.md +333 -0
  95. package/docs/design-system.md +557 -0
  96. package/docs/dsl.md +1093 -0
  97. package/docs/getting-started.md +297 -0
  98. package/docs/injector.md +633 -0
  99. package/docs/methodology.md +673 -0
  100. package/docs/migration-v3.md +285 -0
  101. package/docs/pipeline.md +768 -0
  102. package/docs/plugins.md +333 -0
  103. package/docs/react-api.md +703 -0
  104. package/docs/runtime-benchmarks.md +388 -0
  105. package/docs/ssr.md +630 -0
  106. package/docs/styles.md +725 -0
  107. package/docs/tasty-static.md +659 -0
  108. package/package.json +238 -50
  109. package/tasty.config.ts +6 -0
  110. package/dist/_virtual/_rolldown/runtime.js +0 -8
  111. package/dist/chunks/cacheKey.js +0 -70
  112. package/dist/chunks/cacheKey.js.map +0 -1
  113. package/dist/chunks/definitions.d.ts +0 -37
  114. package/dist/chunks/definitions.js +0 -260
  115. package/dist/chunks/definitions.js.map +0 -1
  116. package/dist/chunks/renderChunk.js +0 -61
  117. package/dist/chunks/renderChunk.js.map +0 -1
  118. package/dist/config.d.ts +0 -280
  119. package/dist/config.js +0 -403
  120. package/dist/config.js.map +0 -1
  121. package/dist/debug.d.ts +0 -204
  122. package/dist/debug.js +0 -733
  123. package/dist/debug.js.map +0 -1
  124. package/dist/hooks/useGlobalStyles.d.ts +0 -27
  125. package/dist/hooks/useGlobalStyles.js +0 -56
  126. package/dist/hooks/useGlobalStyles.js.map +0 -1
  127. package/dist/hooks/useKeyframes.d.ts +0 -56
  128. package/dist/hooks/useKeyframes.js +0 -54
  129. package/dist/hooks/useKeyframes.js.map +0 -1
  130. package/dist/hooks/useProperty.d.ts +0 -79
  131. package/dist/hooks/useProperty.js +0 -91
  132. package/dist/hooks/useProperty.js.map +0 -1
  133. package/dist/hooks/useRawCSS.d.ts +0 -53
  134. package/dist/hooks/useRawCSS.js +0 -28
  135. package/dist/hooks/useRawCSS.js.map +0 -1
  136. package/dist/hooks/useStyles.d.ts +0 -40
  137. package/dist/hooks/useStyles.js +0 -169
  138. package/dist/hooks/useStyles.js.map +0 -1
  139. package/dist/injector/index.d.ts +0 -157
  140. package/dist/injector/index.js +0 -154
  141. package/dist/injector/index.js.map +0 -1
  142. package/dist/injector/injector.d.ts +0 -139
  143. package/dist/injector/injector.js +0 -404
  144. package/dist/injector/injector.js.map +0 -1
  145. package/dist/injector/sheet-manager.d.ts +0 -127
  146. package/dist/injector/sheet-manager.js +0 -714
  147. package/dist/injector/sheet-manager.js.map +0 -1
  148. package/dist/injector/types.d.ts +0 -135
  149. package/dist/keyframes/index.js +0 -206
  150. package/dist/keyframes/index.js.map +0 -1
  151. package/dist/parser/classify.js +0 -319
  152. package/dist/parser/classify.js.map +0 -1
  153. package/dist/parser/const.js +0 -33
  154. package/dist/parser/const.js.map +0 -1
  155. package/dist/parser/lru.js +0 -109
  156. package/dist/parser/lru.js.map +0 -1
  157. package/dist/parser/parser.d.ts +0 -25
  158. package/dist/parser/parser.js +0 -116
  159. package/dist/parser/parser.js.map +0 -1
  160. package/dist/parser/tokenizer.js +0 -69
  161. package/dist/parser/tokenizer.js.map +0 -1
  162. package/dist/parser/types.d.ts +0 -51
  163. package/dist/parser/types.js +0 -46
  164. package/dist/parser/types.js.map +0 -1
  165. package/dist/pipeline/conditions.d.ts +0 -134
  166. package/dist/pipeline/conditions.js +0 -400
  167. package/dist/pipeline/conditions.js.map +0 -1
  168. package/dist/pipeline/exclusive.js +0 -231
  169. package/dist/pipeline/exclusive.js.map +0 -1
  170. package/dist/pipeline/index.d.ts +0 -53
  171. package/dist/pipeline/index.js +0 -641
  172. package/dist/pipeline/index.js.map +0 -1
  173. package/dist/pipeline/materialize.js +0 -908
  174. package/dist/pipeline/materialize.js.map +0 -1
  175. package/dist/pipeline/parseStateKey.d.ts +0 -15
  176. package/dist/pipeline/parseStateKey.js +0 -430
  177. package/dist/pipeline/parseStateKey.js.map +0 -1
  178. package/dist/pipeline/simplify.js +0 -557
  179. package/dist/pipeline/simplify.js.map +0 -1
  180. package/dist/plugins/okhsl-plugin.d.ts +0 -35
  181. package/dist/plugins/okhsl-plugin.js +0 -371
  182. package/dist/plugins/okhsl-plugin.js.map +0 -1
  183. package/dist/plugins/types.d.ts +0 -69
  184. package/dist/properties/index.js +0 -158
  185. package/dist/properties/index.js.map +0 -1
  186. package/dist/states/index.d.ts +0 -49
  187. package/dist/states/index.js +0 -416
  188. package/dist/states/index.js.map +0 -1
  189. package/dist/static/tastyStatic.d.ts +0 -46
  190. package/dist/static/tastyStatic.js +0 -31
  191. package/dist/static/tastyStatic.js.map +0 -1
  192. package/dist/static/types.d.ts +0 -49
  193. package/dist/static/types.js +0 -24
  194. package/dist/static/types.js.map +0 -1
  195. package/dist/styles/align.d.ts +0 -15
  196. package/dist/styles/align.js +0 -14
  197. package/dist/styles/align.js.map +0 -1
  198. package/dist/styles/border.d.ts +0 -25
  199. package/dist/styles/border.js +0 -114
  200. package/dist/styles/border.js.map +0 -1
  201. package/dist/styles/color.d.ts +0 -14
  202. package/dist/styles/color.js +0 -23
  203. package/dist/styles/color.js.map +0 -1
  204. package/dist/styles/createStyle.js +0 -77
  205. package/dist/styles/createStyle.js.map +0 -1
  206. package/dist/styles/dimension.js +0 -97
  207. package/dist/styles/dimension.js.map +0 -1
  208. package/dist/styles/display.d.ts +0 -37
  209. package/dist/styles/display.js +0 -67
  210. package/dist/styles/display.js.map +0 -1
  211. package/dist/styles/fade.d.ts +0 -15
  212. package/dist/styles/fade.js +0 -58
  213. package/dist/styles/fade.js.map +0 -1
  214. package/dist/styles/fill.d.ts +0 -44
  215. package/dist/styles/fill.js +0 -51
  216. package/dist/styles/fill.js.map +0 -1
  217. package/dist/styles/flow.d.ts +0 -16
  218. package/dist/styles/flow.js +0 -12
  219. package/dist/styles/flow.js.map +0 -1
  220. package/dist/styles/gap.d.ts +0 -31
  221. package/dist/styles/gap.js +0 -37
  222. package/dist/styles/gap.js.map +0 -1
  223. package/dist/styles/height.d.ts +0 -17
  224. package/dist/styles/height.js +0 -20
  225. package/dist/styles/height.js.map +0 -1
  226. package/dist/styles/index.d.ts +0 -2
  227. package/dist/styles/index.js +0 -9
  228. package/dist/styles/index.js.map +0 -1
  229. package/dist/styles/inset.d.ts +0 -52
  230. package/dist/styles/inset.js +0 -150
  231. package/dist/styles/inset.js.map +0 -1
  232. package/dist/styles/justify.d.ts +0 -15
  233. package/dist/styles/justify.js +0 -14
  234. package/dist/styles/justify.js.map +0 -1
  235. package/dist/styles/list.d.ts +0 -16
  236. package/dist/styles/list.js +0 -98
  237. package/dist/styles/list.js.map +0 -1
  238. package/dist/styles/margin.d.ts +0 -24
  239. package/dist/styles/margin.js +0 -104
  240. package/dist/styles/margin.js.map +0 -1
  241. package/dist/styles/outline.d.ts +0 -29
  242. package/dist/styles/outline.js +0 -65
  243. package/dist/styles/outline.js.map +0 -1
  244. package/dist/styles/padding.d.ts +0 -24
  245. package/dist/styles/padding.js +0 -104
  246. package/dist/styles/padding.js.map +0 -1
  247. package/dist/styles/predefined.d.ts +0 -73
  248. package/dist/styles/predefined.js +0 -241
  249. package/dist/styles/predefined.js.map +0 -1
  250. package/dist/styles/preset.d.ts +0 -47
  251. package/dist/styles/preset.js +0 -126
  252. package/dist/styles/preset.js.map +0 -1
  253. package/dist/styles/radius.d.ts +0 -14
  254. package/dist/styles/radius.js +0 -51
  255. package/dist/styles/radius.js.map +0 -1
  256. package/dist/styles/scrollbar.d.ts +0 -21
  257. package/dist/styles/scrollbar.js +0 -105
  258. package/dist/styles/scrollbar.js.map +0 -1
  259. package/dist/styles/shadow.d.ts +0 -14
  260. package/dist/styles/shadow.js +0 -24
  261. package/dist/styles/shadow.js.map +0 -1
  262. package/dist/styles/styledScrollbar.d.ts +0 -47
  263. package/dist/styles/styledScrollbar.js +0 -38
  264. package/dist/styles/styledScrollbar.js.map +0 -1
  265. package/dist/styles/transition.d.ts +0 -14
  266. package/dist/styles/transition.js +0 -158
  267. package/dist/styles/transition.js.map +0 -1
  268. package/dist/styles/types.d.ts +0 -498
  269. package/dist/styles/width.d.ts +0 -17
  270. package/dist/styles/width.js +0 -20
  271. package/dist/styles/width.js.map +0 -1
  272. package/dist/tasty.d.ts +0 -982
  273. package/dist/tasty.js +0 -191
  274. package/dist/tasty.js.map +0 -1
  275. package/dist/tokens/typography.d.ts +0 -19
  276. package/dist/tokens/typography.js +0 -237
  277. package/dist/tokens/typography.js.map +0 -1
  278. package/dist/types.d.ts +0 -184
  279. package/dist/utils/cache-wrapper.js +0 -26
  280. package/dist/utils/cache-wrapper.js.map +0 -1
  281. package/dist/utils/case-converter.js +0 -8
  282. package/dist/utils/case-converter.js.map +0 -1
  283. package/dist/utils/colors.d.ts +0 -5
  284. package/dist/utils/colors.js +0 -9
  285. package/dist/utils/colors.js.map +0 -1
  286. package/dist/utils/css-types.d.ts +0 -7
  287. package/dist/utils/dotize.d.ts +0 -26
  288. package/dist/utils/dotize.js +0 -122
  289. package/dist/utils/dotize.js.map +0 -1
  290. package/dist/utils/filter-base-props.d.ts +0 -15
  291. package/dist/utils/filter-base-props.js +0 -45
  292. package/dist/utils/filter-base-props.js.map +0 -1
  293. package/dist/utils/get-display-name.d.ts +0 -7
  294. package/dist/utils/get-display-name.js +0 -10
  295. package/dist/utils/get-display-name.js.map +0 -1
  296. package/dist/utils/hsl-to-rgb.js +0 -38
  297. package/dist/utils/hsl-to-rgb.js.map +0 -1
  298. package/dist/utils/is-dev-env.js +0 -19
  299. package/dist/utils/is-dev-env.js.map +0 -1
  300. package/dist/utils/is-valid-element-type.js +0 -15
  301. package/dist/utils/is-valid-element-type.js.map +0 -1
  302. package/dist/utils/merge-styles.js.map +0 -1
  303. package/dist/utils/mod-attrs.d.ts +0 -8
  304. package/dist/utils/mod-attrs.js +0 -21
  305. package/dist/utils/mod-attrs.js.map +0 -1
  306. package/dist/utils/okhsl-to-rgb.js +0 -296
  307. package/dist/utils/okhsl-to-rgb.js.map +0 -1
  308. package/dist/utils/process-tokens.d.ts +0 -31
  309. package/dist/utils/process-tokens.js +0 -171
  310. package/dist/utils/process-tokens.js.map +0 -1
  311. package/dist/utils/resolve-recipes.d.ts +0 -17
  312. package/dist/utils/resolve-recipes.js +0 -147
  313. package/dist/utils/resolve-recipes.js.map +0 -1
  314. package/dist/utils/string.js +0 -8
  315. package/dist/utils/string.js.map +0 -1
  316. package/dist/utils/styles.d.ts +0 -183
  317. package/dist/utils/styles.js +0 -585
  318. package/dist/utils/styles.js.map +0 -1
  319. package/dist/utils/typography.d.ts +0 -36
  320. package/dist/utils/typography.js +0 -53
  321. package/dist/utils/typography.js.map +0 -1
  322. package/dist/utils/warnings.d.ts +0 -16
  323. package/dist/utils/warnings.js +0 -16
  324. package/dist/utils/warnings.js.map +0 -1
  325. package/dist/zero/css-writer.d.ts +0 -45
  326. package/dist/zero/css-writer.js +0 -74
  327. package/dist/zero/css-writer.js.map +0 -1
  328. package/dist/zero/extractor.d.ts +0 -24
  329. package/dist/zero/extractor.js +0 -150
  330. package/dist/zero/extractor.js.map +0 -1
@@ -0,0 +1,633 @@
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
+ - **Selector assembly** - Prepends the doubled `.tX.tX` class and root prefix to the pipeline's selector fragments (sub-element and `&` nesting is flattened earlier, by the pipeline)
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 shared with `ServerStyleCollector`, and hydration of server-rendered classes
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
+ // Rules flagged needsClassName get the generated class prepended (doubled)
59
+ const result = inject([{
60
+ selector: '',
61
+ declarations: 'color: red; padding: 10px;',
62
+ needsClassName: true,
63
+ }]);
64
+
65
+ console.log(result.className); // 'th8n0uh' — `t` + base36 hash of the rules
66
+ // Injected: .th8n0uh.th8n0uh { color: red; padding: 10px; }
67
+
68
+ // Release the pin; the class becomes collectible once nothing renders it
69
+ result.dispose();
70
+ ```
71
+
72
+ `inject()` **pins** the class it returns, and `gc()` never evicts a pinned class
73
+ — that is what `dispose()` releases. Pass `{ pin: false }` when the caller keeps
74
+ no handle and the DOM is the only record that the class is in use; `dispose()`
75
+ is then a no-op. The render path (`tasty()` / `computeStyles()`) injects this
76
+ way, because a hook-free render has no unmount signal to dispose on.
77
+
78
+ ### `injectGlobal(rules, options?): { dispose: () => void }`
79
+
80
+ Injects global styles that don't reserve tasty class names.
81
+
82
+ ```typescript
83
+ // Global styles - for body, resets, etc.
84
+ const globalResult = injectGlobal([
85
+ {
86
+ selector: 'body',
87
+ declarations: 'margin: 0; font-family: Arial;',
88
+ },
89
+ {
90
+ selector: '.header',
91
+ declarations: 'background: blue; color: white;',
92
+ atRules: ['@media (min-width: 768px)'],
93
+ }
94
+ ]);
95
+
96
+ // Only returns dispose function - no className needed for global styles
97
+ globalResult.dispose();
98
+ ```
99
+
100
+ ### `injectRawCSS(css, options?): { dispose: () => void }`
101
+
102
+ Injects raw CSS text directly without parsing. This is a low-overhead method for injecting CSS that doesn't need tasty processing.
103
+
104
+ ```typescript
105
+ import { injectRawCSS } from '@tenphi/tasty';
106
+
107
+ // Inject raw CSS
108
+ const { dispose } = injectRawCSS(`
109
+ body {
110
+ margin: 0;
111
+ padding: 0;
112
+ font-family: sans-serif;
113
+ }
114
+
115
+ .my-class {
116
+ color: red;
117
+ }
118
+ `);
119
+
120
+ // Later, remove the injected CSS
121
+ dispose();
122
+ ```
123
+
124
+ ### `useRawCSS(css, options?)` or `useRawCSS(factory, deps, options?)`
125
+
126
+ Inject raw CSS without parsing. Hook-free — works in client components, SSR, and React Server Components.
127
+
128
+ Supports two overloads:
129
+ - **Static CSS**: `useRawCSS(cssString, options?)` — content-based deduplication
130
+ - **Factory function**: `useRawCSS(() => cssString, deps, options?)` — factory called on every invocation, dedup handled internally
131
+
132
+ Use the `id` option for update tracking — when the CSS changes for the same id, the previous injection is replaced:
133
+
134
+ ```tsx
135
+ import { useRawCSS } from '@tenphi/tasty';
136
+
137
+ // Static CSS
138
+ function GlobalReset() {
139
+ useRawCSS(`
140
+ body { margin: 0; padding: 0; }
141
+ `);
142
+ return null;
143
+ }
144
+
145
+ // Dynamic CSS with factory function and update tracking
146
+ function ThemeStyles({ theme }: { theme: 'dark' | 'light' }) {
147
+ useRawCSS(() => `
148
+ body {
149
+ margin: 0;
150
+ background: ${theme === 'dark' ? '#000' : '#fff'};
151
+ color: ${theme === 'dark' ? '#fff' : '#000'};
152
+ }
153
+ `, [theme], { id: 'theme-body' });
154
+
155
+ return null;
156
+ }
157
+ ```
158
+
159
+ ### `createInjector(config?): StyleInjector`
160
+
161
+ Creates an isolated injector instance with custom configuration.
162
+
163
+ ```typescript
164
+ import { createInjector } from '@tenphi/tasty';
165
+
166
+ // Create isolated instance for testing
167
+ const testInjector = createInjector({
168
+ devMode: true,
169
+ forceTextInjection: true,
170
+ });
171
+
172
+ const result = testInjector.inject(rules);
173
+ ```
174
+
175
+ ### `keyframes(steps, nameOrOptions?): KeyframesResult`
176
+
177
+ Injects CSS keyframes with automatic deduplication.
178
+
179
+ ```typescript
180
+ // Generated name (tk0, tk1, … — namePrefix + 'k' + counter)
181
+ const fadeIn = keyframes({
182
+ from: { opacity: 0 },
183
+ to: { opacity: 1 },
184
+ });
185
+
186
+ // Custom name
187
+ const slideIn = keyframes({
188
+ '0%': { transform: 'translateX(-100%)' },
189
+ '100%': { transform: 'translateX(0)' },
190
+ }, 'slideInAnimation');
191
+
192
+ // Use in tasty styles (recommended)
193
+ const AnimatedBox = tasty({
194
+ styles: {
195
+ animation: `${fadeIn} 300ms ease-in`,
196
+ },
197
+ });
198
+
199
+ // Or use with injectGlobal for fixed selectors
200
+ injectGlobal([{
201
+ selector: '.my-animated-class',
202
+ declarations: `animation: ${slideIn} 500ms ease-out;`
203
+ }]);
204
+
205
+ // Cleanup keyframes (if needed)
206
+ fadeIn.dispose(); // Immediate keyframes deletion from DOM
207
+ slideIn.dispose(); // Immediate keyframes deletion from DOM
208
+ ```
209
+
210
+ ### `configure(config): void`
211
+
212
+ 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).
213
+
214
+ ```typescript
215
+ import { configure } from '@tenphi/tasty';
216
+
217
+ configure({
218
+ devMode: true, // Enable development features (auto-detected)
219
+ maxRulesPerSheet: 8192, // Cap rules per stylesheet (default: 8192)
220
+ forceTextInjection: false, // Force textContent insertion (auto-detected for tests)
221
+ nonce: 'csp-nonce', // CSP nonce for security
222
+ gc: { // Garbage collection for unused styles
223
+ touchInterval: 1000, // Touch events between GC cycles (default: 1000)
224
+ capacity: 1000, // Max unused styles to retain (default: 1000)
225
+ },
226
+ states: { // Global predefined states for advanced state mapping
227
+ '@mobile': '@media(w < 768px)',
228
+ '@dark': '@root(schema=dark)',
229
+ },
230
+ });
231
+ ```
232
+
233
+ **Auto-Detection Features:**
234
+ - `devMode`: Automatically enabled in development environments (detected via `isDevEnv()`)
235
+ - `forceTextInjection`: Automatically enabled in test environments (Jest, Vitest, Mocha, happy-dom, jsdom)
236
+
237
+ **Injection Modes:**
238
+
239
+ Each sheet picks its write mode once, when it is created, and keeps it for its
240
+ lifetime:
241
+
242
+ | Mode | How rules are written | How rules are removed |
243
+ |---|---|---|
244
+ | CSSOM (default) | `styleSheet.insertRule(rule, index)` | `styleSheet.deleteRule(index)` |
245
+ | 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 |
246
+ | Adopted (ShadowRoot with constructable sheets) | `insertRule` on the constructable sheet | `deleteRule` on the constructable sheet |
247
+
248
+ Text mode cannot edit a single rule in place the way CSSOM can, so the sheet
249
+ keeps the inserted rule texts in index order and rewrites the element on delete.
250
+ Dispose, ref-counted cleanup and GC therefore behave identically in every mode.
251
+
252
+ **Configuration Notes:**
253
+ - Most options have sensible defaults and auto-detection
254
+ - `configure()` is optional - the injector works with defaults
255
+ - **Configuration is locked after styles are generated** - calling `configure()` after first render will emit a warning and be ignored
256
+ - `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.
257
+ - `gc.grace`: How long a class is left alone after collection first notices nothing is carrying it, in milliseconds (default `10000`).
258
+ - Automatic sweeps are opt-in: they run only when `configure({ gc })` is set (`gc: {}` enables them with these defaults). Without it nothing is collected until you call `gc()` or `cleanup()`.
259
+
260
+ **What a sweep does.** Everything the injector holds falls into one of five bands, and only the last is ever deleted:
261
+
262
+ | Band | | Deleted |
263
+ |---|---|---|
264
+ | 1 | **Rendered** — some element carries the class right now | never |
265
+ | 2 | **Not ours** — queued for a batched write, pre-allocated, or server-rendered | never |
266
+ | 3 | **Hot** — nothing carries it, but that was noticed less than `grace` ago | never |
267
+ | 4 | **Cached** — cold, but within `capacity` when ordered by when it went cold | never |
268
+ | 5 | Everything else | on every sweep |
269
+
270
+ `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.
271
+
272
+ > **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.
273
+ >
274
+ > 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.
275
+ >
276
+ > 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.
277
+ - `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.
278
+
279
+ ---
280
+
281
+ ### At-rule injection
282
+
283
+ 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.
284
+
285
+ | Function | Injects | Notes |
286
+ |---|---|---|
287
+ | `keyframes(steps, nameOrOptions?)` | `@keyframes` | The exception: ref-counted and disposed immediately when unused. Returns the injected name, which may differ from the requested one. |
288
+ | `property(name, options?)` | `@property` | `name` accepts `$name`, `#name`, or `--name`. Usually unnecessary — types are inferred automatically unless `configure({ autoPropertyTypes: false })`. |
289
+ | `fontFace(family, descriptors, options?)` | `@font-face` | Deduplicated by family **and** descriptor content, so several faces of one family coexist. |
290
+ | `counterStyle(name, descriptors, options?)` | `@counter-style` | |
291
+ | `func(name, definition, options?)` | `@function` | `name` accepts `$$name`, `$name`, or `--name`. Abbreviated because `function` is a reserved word. |
292
+
293
+ Every one of these takes an optional `root` (a `Document` or `ShadowRoot`).
294
+
295
+ `counterStyle()` and `func()` also accept `weak: true`, which registers the rule **without** overriding an existing one of the same name. `configure()` uses it for global `@counter-style` and `@function` definitions so a component-local definition always wins over the global default, regardless of which is injected first.
296
+
297
+ ```ts
298
+ import { counterStyle, fontFace, func, property } from '@tenphi/tasty';
299
+
300
+ property('$card-elevation', { syntax: '<number>', initialValue: '0' });
301
+ fontFace('Inter', { src: 'url(/inter.woff2)', fontWeight: '400 700' });
302
+ counterStyle('dashes', { system: 'cyclic', symbols: '"—"', suffix: ' ' });
303
+ func('$$negative', { args: ['$value'], result: '(-1 * $value)' });
304
+ ```
305
+
306
+ ---
307
+
308
+ ## Advanced Features
309
+
310
+ ### Style Result Format
311
+
312
+ The injector works with `StyleResult` objects from the pipeline (`renderStyles`):
313
+
314
+ ```typescript
315
+ interface StyleResult {
316
+ selector: string; // full selector, or a fragment when needsClassName
317
+ declarations: string; // CSS declarations
318
+ atRules?: string[]; // @media, @container, @supports, …
319
+ needsClassName?: boolean; // prepend the generated `.tX.tX` (OR'd fragments joined with '|||')
320
+ rootPrefix?: string; // root-state prefix placed before the class
321
+ startingStyle?: boolean; // wrap declarations in @starting-style
322
+ }
323
+
324
+ // Example StyleResult
325
+ const styleRule: StyleResult = {
326
+ selector: ':where([data-hovered])',
327
+ declarations: 'padding: 8px 16px; background: blue; color: white;',
328
+ atRules: ['@media (min-width: 768px)'],
329
+ needsClassName: true,
330
+ };
331
+ ```
332
+
333
+ ### Batched Injection
334
+
335
+ `configure({ batchInjection: true })` queues every sheet write — component
336
+ rules, global rules, raw CSS and at-rules — into one FIFO and applies them
337
+ together, so the document is style-invalidated once per flush instead of once per
338
+ component. `<TastyBatchProvider>` flushes in `useInsertionEffect`, before any
339
+ layout effect, so a queued write can never be observed by a measurement. See
340
+ [Batched injection](configuration.md#batched-injection) for the modes and the
341
+ ordering guarantee. `flushStyles()` applies pending writes on demand; every read
342
+ API here calls it for you.
343
+
344
+ ### Deduplication & Performance
345
+
346
+ ```typescript
347
+ const rule = { selector: '', declarations: 'padding: 8px; color: red;', needsClassName: true };
348
+
349
+ const button1 = inject([rule], { cacheKey: 'button' });
350
+ const button2 = inject([rule], { cacheKey: 'button' });
351
+
352
+ // One class, one copy of the CSS
353
+ console.log(button1.className === button2.className); // true
354
+ ```
355
+
356
+ Without `cacheKey` the class name still matches (it hashes the rules), but the rule is inserted again and the pin count restarts at 1.
357
+
358
+ ### Pinning
359
+
360
+ ```typescript
361
+ // Multiple callers using the same styles
362
+ const comp1 = inject([commonStyle], { cacheKey: 'common' });
363
+ const comp2 = inject([commonStyle], { cacheKey: 'common' });
364
+ const comp3 = inject([commonStyle], { cacheKey: 'common' });
365
+
366
+ // Style is pinned while any caller holds a handle
367
+ comp1.dispose(); // pins: 3 → 2
368
+ comp2.dispose(); // pins: 2 → 1
369
+ comp3.dispose(); // pins: 1 → 0, now up to the DOM and gc()
370
+
371
+ // Unpinned does not mean deleted: the rule stays cached and is reused instantly
372
+ // by the next inject(). gc() decides when it actually goes.
373
+ ```
374
+
375
+ Pinning covers callers that hold a handle. Styles that come from rendering are
376
+ never pinned — see `{ pin: false }` under
377
+ [`inject()`](#injectrules-options-injectresult) — so what keeps them alive is
378
+ being in the DOM, and nothing else.
379
+
380
+ ### Garbage Collection
381
+
382
+ ```typescript
383
+ import { configure, gc } from '@tenphi/tasty';
384
+
385
+ // Keyframes: Disposed immediately when refCount = 0 (safer for global scope)
386
+ // CSS rules: Tracked by touch count and cleaned up via gc()
387
+ //
388
+ // A CSS rule is collectible when no element carries its class AND nobody
389
+ // pinned it with inject().
390
+
391
+ configure({
392
+ gc: {
393
+ touchInterval: 1000, // Schedule GC every 1000 touches
394
+ capacity: 1000, // Max unused styles to retain
395
+ },
396
+ });
397
+
398
+ // Manual GC (synchronous, returns number of swept styles):
399
+ gc();
400
+
401
+ // Force-remove ALL unused styles (e.g. on route change or test teardown):
402
+ gc({ force: true });
403
+
404
+ // cleanup() is the same thing:
405
+ cleanup();
406
+
407
+ // Every `touchInterval` renders, a sweep is scheduled in idle time. It scans
408
+ // the DOM for the classes actually on the page and sorts everything the
409
+ // injector holds into five bands — only the last one is deleted. See below.
410
+
411
+ // Benefits:
412
+ // - Activity-proportional: busy apps trigger GC more often
413
+ // - DOM-safe: styles currently in the DOM are never evicted
414
+ // - Oldest-first: least recently used styles are evicted first
415
+ // - Keyframes: Immediate cleanup prevents global namespace pollution
416
+ // - Unused styles stay cached until evicted, so re-rendering them is a cache hit
417
+ ```
418
+
419
+ ### Shadow DOM Support
420
+
421
+ ```typescript
422
+ // Works with Shadow DOM
423
+ const shadowRoot = document.createElement('div').attachShadow({ mode: 'open' });
424
+
425
+ const shadowStyles = inject([{
426
+ selector: '.shadow-component',
427
+ declarations: 'color: purple;'
428
+ }], { root: shadowRoot });
429
+
430
+ // Keyframes in Shadow DOM
431
+ const shadowAnimation = keyframes({
432
+ from: { opacity: 0 },
433
+ to: { opacity: 1 }
434
+ }, { root: shadowRoot, name: 'shadowFade' });
435
+ ```
436
+
437
+ ---
438
+
439
+ ## SSR & Testing
440
+
441
+ ### Server-Side Rendering
442
+
443
+ `getCSSText()` reads the injector's stylesheets, so it needs a DOM; on a server it throws. Collect server CSS with `ServerStyleCollector` from `@tenphi/tasty/ssr` (`collector.getCSS()`) — see [SSR](./ssr.md).
444
+
445
+ ```typescript
446
+ import { getCSSText, getCSSTextForNode } from '@tenphi/tasty';
447
+ import { render } from '@testing-library/react';
448
+
449
+ const cssText = getCSSText(); // everything the injector holds (browser / test DOM)
450
+
451
+ const { container } = render(<MyComponent />);
452
+ const componentCSS = getCSSTextForNode(container); // only the CSS this subtree uses
453
+ ```
454
+
455
+ ### Test Environment Detection
456
+
457
+ ```typescript
458
+ // Automatically detected test environments:
459
+ // - NODE_ENV === 'test'
460
+ // - Jest globals (jest, describe, it, expect)
461
+ // - jsdom / HappyDOM user agent
462
+ // - Vitest globals (vitest)
463
+ // - Mocha globals (mocha)
464
+
465
+ import { configure, isTestEnvironment, resetConfig } from '@tenphi/tasty';
466
+
467
+ const isTest = isTestEnvironment();
468
+
469
+ // Reset config between tests to allow reconfiguration
470
+ beforeEach(() => {
471
+ resetConfig();
472
+ configure({
473
+ forceTextInjection: isTest, // More reliable in test environments
474
+ devMode: true, // Always enable dev features in tests
475
+ });
476
+ });
477
+ ```
478
+
479
+ ### Memory Management in Tests
480
+
481
+ ```typescript
482
+ // Clean up between tests
483
+ afterEach(() => {
484
+ cleanup(); // Force cleanup of unused styles
485
+ });
486
+
487
+ // Full cleanup after test suite
488
+ afterAll(() => {
489
+ destroy(); // Destroy all stylesheets and reset state
490
+ });
491
+ ```
492
+
493
+ ---
494
+
495
+ ## Development Features
496
+
497
+ ### Performance Metrics
498
+
499
+ When `devMode` is enabled, the injector tracks comprehensive metrics:
500
+
501
+ ```typescript
502
+ import { configure, injector } from '@tenphi/tasty';
503
+
504
+ configure({ devMode: true });
505
+
506
+ // Access metrics through the global injector
507
+ const metrics = injector.instance.getMetrics();
508
+
509
+ console.log({
510
+ cacheHits: metrics.hits, // Successful cache hits
511
+ cacheMisses: metrics.misses, // New styles injected
512
+ unusedHits: metrics.unusedHits, // Styles currently eligible for eviction (scans the DOM)
513
+ bulkCleanups: metrics.bulkCleanups, // Number of bulk cleanup operations
514
+ stylesCleanedUp: metrics.stylesCleanedUp, // Total styles removed in bulk cleanups
515
+ totalInsertions: metrics.totalInsertions, // Lifetime insertions
516
+ totalUnused: metrics.totalUnused, // Times a pinned style lost its last pin
517
+ startTime: metrics.startTime, // Metrics collection start timestamp
518
+ cleanupHistory: metrics.cleanupHistory, // Detailed cleanup operation history
519
+ });
520
+ ```
521
+
522
+ ### Debug Information
523
+
524
+ ```typescript
525
+ import { tastyDebug } from '@tenphi/tasty';
526
+
527
+ const { activeClasses, unusedClasses, hotClasses, totalRuleCount } =
528
+ tastyDebug.summary({ raw: true });
529
+ ```
530
+
531
+ See [Debug Utilities](./debug.md).
532
+
533
+ ### Cleanup History
534
+
535
+ ```typescript
536
+ // Track cleanup operations over time
537
+ const metrics = injector.instance.getMetrics();
538
+
539
+ metrics.cleanupHistory.forEach(cleanup => {
540
+ console.log({
541
+ timestamp: new Date(cleanup.timestamp),
542
+ classesDeleted: cleanup.classesDeleted,
543
+ rulesDeleted: cleanup.rulesDeleted,
544
+ cssSize: cleanup.cssSize, // Total CSS size removed (bytes)
545
+ });
546
+ });
547
+ ```
548
+
549
+ ---
550
+
551
+ ## Performance Optimizations
552
+
553
+ ### Best Practices
554
+
555
+ ```typescript
556
+ // ✅ Reuse styles - identical CSS gets deduplicated
557
+ const buttonBase = 'padding: 8px 16px; border-radius: 4px;';
558
+
559
+ // ✅ Avoid frequent disposal and re-injection
560
+ // Let the injector handle cleanup
561
+
562
+ // ✅ Use bulk operations for global styles
563
+ injectGlobal([
564
+ { selector: 'body', declarations: 'margin: 0;' },
565
+ { selector: '*', declarations: 'box-sizing: border-box;' },
566
+ { selector: '.container', declarations: 'max-width: 1200px;' }
567
+ ]);
568
+
569
+ // ✅ Configure GC for your app (BEFORE first render!)
570
+ import { configure } from '@tenphi/tasty';
571
+
572
+ configure({
573
+ gc: {
574
+ touchInterval: 1000, // Schedule GC every 1000 style touches
575
+ capacity: 1000, // Max unused styles to retain
576
+ },
577
+ });
578
+ ```
579
+
580
+ ### Memory Management
581
+
582
+ ```typescript
583
+ // The injector automatically manages memory through:
584
+
585
+ // 1. Hash-based deduplication - same CSS = same className
586
+ // 2. DOM-driven lifetime - a rendered class is never evicted
587
+ // 3. Pinning - inject() callers hold their classes until they dispose
588
+ // 4. Immediate keyframes cleanup - disposed instantly when refCount = 0
589
+ // 5. Touch-count GC - unused CSS rules are evicted oldest-first when over capacity
590
+
591
+ // Manual cleanup is rarely needed but available:
592
+ cleanup(); // Remove every rule that is neither rendered nor pinned
593
+ destroy(); // Nuclear option: remove all stylesheets and reset
594
+ ```
595
+
596
+ ---
597
+
598
+ ## Integration with Tasty
599
+
600
+ The Style Injector is seamlessly integrated with the higher-level Tasty API:
601
+
602
+ ```jsx
603
+ // High-level tasty() API
604
+ const StyledButton = tasty({
605
+ styles: {
606
+ padding: '2x 4x',
607
+ fill: '#purple',
608
+ color: '#white',
609
+ }
610
+ });
611
+
612
+ // Internally uses the injector:
613
+ // 1. Styles are parsed into StyleResult objects
614
+ // 2. inject() is called with the parsed results, unpinned
615
+ // 3. Component gets the returned className
616
+ // 4. gc() reclaims the class once no element carries it
617
+ ```
618
+
619
+ 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.
620
+
621
+ ---
622
+
623
+ ## When to Use Direct Injection
624
+
625
+ Direct injector usage is recommended for:
626
+
627
+ - **Custom CSS-in-JS libraries** built on top of Tasty
628
+ - **Global styles** that don't fit the component model
629
+ - **Third-party integration** where you need low-level CSS control
630
+ - **Performance-critical scenarios** where you need direct control
631
+ - **Testing utilities** that need to inject or extract CSS
632
+
633
+ For regular component styling, prefer the [`tasty()` API](./react-api.md) which provides a more developer-friendly interface.