@tenphi/tasty 0.0.0-snapshot.2ea241d → 0.0.0-snapshot.2f4e31d
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.
- package/README.md +440 -372
- package/dist/babel-types-Dc5zghyE.d.ts +18 -0
- package/dist/chunks/async-storage-f9j9JRtq.js +37 -0
- package/dist/chunks/async-storage-f9j9JRtq.js.map +1 -0
- package/dist/chunks/build-config-D9Iq8QQm.js +60 -0
- package/dist/chunks/build-config-D9Iq8QQm.js.map +1 -0
- package/dist/{collector-Crs9kGJW.js → chunks/collector-Cb8ah2JF.js} +68 -101
- package/dist/chunks/collector-Cb8ah2JF.js.map +1 -0
- package/dist/chunks/config-engine-CMYFZYQh.js +272 -0
- package/dist/chunks/config-engine-CMYFZYQh.js.map +1 -0
- package/dist/chunks/config-file-DlZXJMj8.js +25 -0
- package/dist/chunks/config-file-DlZXJMj8.js.map +1 -0
- package/dist/chunks/css-definitions-B4aWBkH3.js +910 -0
- package/dist/chunks/css-definitions-B4aWBkH3.js.map +1 -0
- package/dist/chunks/css-resources-P7IBUUZs.js +142 -0
- package/dist/chunks/css-resources-P7IBUUZs.js.map +1 -0
- package/dist/chunks/debug-D2Pu7Xhy.js +502 -0
- package/dist/chunks/debug-D2Pu7Xhy.js.map +1 -0
- package/dist/chunks/dsl-CsFl9LGn.js +1458 -0
- package/dist/chunks/dsl-CsFl9LGn.js.map +1 -0
- package/dist/chunks/hydration-TRcz5vnk.js +41 -0
- package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
- package/dist/chunks/react-runtime-DHiopXCu.js +691 -0
- package/dist/chunks/react-runtime-DHiopXCu.js.map +1 -0
- package/dist/chunks/runtime-engine-NGCofNXy.js +2435 -0
- package/dist/chunks/runtime-engine-NGCofNXy.js.map +1 -0
- package/dist/chunks/runtime-state-lZjMbvwV.js +152 -0
- package/dist/chunks/runtime-state-lZjMbvwV.js.map +1 -0
- package/dist/{merge-styles-BzQutdAK.js → chunks/shared-utils-y-HjvPN4.js} +60 -55
- package/dist/chunks/shared-utils-y-HjvPN4.js.map +1 -0
- package/dist/chunks/style-engine-DnkV_4Jg.js +5602 -0
- package/dist/chunks/style-engine-DnkV_4Jg.js.map +1 -0
- package/dist/{css-writer-CPy_cbFJ.js → chunks/zero-engine-DcwaCvFs.js} +95 -136
- package/dist/chunks/zero-engine-DcwaCvFs.js.map +1 -0
- package/dist/{collector-osfWTeRd.d.ts → collector-D2OT6I2G.d.ts} +64 -8
- package/dist/{config-BoZDUHW5.d.ts → config-C4ftFxgI.d.ts} +514 -92
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +9 -6
- package/dist/hydrate-CRyjjAyl.d.ts +22 -0
- package/dist/{index-B_k47mc_.d.ts → index-DxQNRj50.d.ts} +717 -408
- package/dist/index.d.ts +5 -5
- package/dist/index.js +11 -732
- package/dist/{merge-styles-BMWcH6MF.d.ts → merge-styles-D39qBtox.d.ts} +2 -3
- package/dist/ssr/astro-client.d.ts +1 -1
- package/dist/ssr/astro-client.js +1 -14
- package/dist/ssr/astro-client.js.map +1 -1
- package/dist/ssr/astro-middleware-extract-static.d.ts +10 -0
- package/dist/ssr/astro-middleware-extract-static.js +9 -0
- package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
- package/dist/ssr/astro-middleware-extract.d.ts +10 -0
- package/dist/ssr/astro-middleware-extract.js +9 -0
- package/dist/ssr/astro-middleware-extract.js.map +1 -0
- package/dist/ssr/astro-middleware-static.d.ts +17 -0
- package/dist/ssr/astro-middleware-static.js +7 -0
- package/dist/ssr/astro-middleware-static.js.map +1 -0
- package/dist/ssr/astro-middleware.d.ts +11 -8
- package/dist/ssr/astro-middleware.js +2 -14
- package/dist/ssr/astro-middleware.js.map +1 -1
- package/dist/ssr/astro.d.ts +40 -10
- package/dist/ssr/astro.js +163 -91
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/client.d.ts +2 -0
- package/dist/ssr/client.js +2 -0
- package/dist/ssr/index.d.ts +5 -32
- package/dist/ssr/index.js +6 -6
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next-config.d.ts +64 -0
- package/dist/ssr/next-config.js +123 -0
- package/dist/ssr/next-config.js.map +1 -0
- package/dist/ssr/next.d.ts +9 -9
- package/dist/ssr/next.js +29 -44
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +8 -9
- package/dist/static/index.js +4 -22
- package/dist/static/index.js.map +1 -1
- package/dist/static/inject.d.ts +1 -2
- package/dist/static/inject.js.map +1 -1
- package/dist/{index-tcHuMPFt.d.ts → types-CYQIhUg1.d.ts} +883 -600
- package/dist/zero/babel.d.ts +12 -20
- package/dist/zero/babel.js +97 -156
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +76 -7
- package/dist/zero/index.js +25 -2
- package/dist/zero/index.js.map +1 -0
- package/dist/zero/next.d.ts +4 -5
- package/dist/zero/next.js +3 -38
- package/dist/zero/next.js.map +1 -1
- package/docs/README.md +20 -9
- package/docs/adoption.md +69 -36
- package/docs/ai-agents.md +259 -0
- package/docs/comparison.md +77 -47
- package/docs/configuration.md +617 -98
- package/docs/debug.md +28 -15
- package/docs/design-system.md +154 -33
- package/docs/dsl.md +715 -194
- package/docs/getting-started.md +130 -50
- package/docs/injector.md +160 -69
- package/docs/methodology.md +82 -51
- package/docs/migration-v3.md +285 -0
- package/docs/pipeline.md +102 -33
- package/docs/plugins.md +333 -0
- package/docs/react-api.md +215 -50
- package/docs/runtime-benchmarks.md +388 -0
- package/docs/ssr.md +310 -118
- package/docs/styles.md +225 -42
- package/docs/tasty-static.md +289 -136
- package/package.json +146 -41
- package/tasty.config.ts +6 -0
- package/dist/async-storage-B7_o6FKt.js +0 -44
- package/dist/async-storage-B7_o6FKt.js.map +0 -1
- package/dist/collector-Crs9kGJW.js.map +0 -1
- package/dist/config-BaxtQMS3.js +0 -10464
- package/dist/config-BaxtQMS3.js.map +0 -1
- package/dist/context-CkSg-kDT.js +0 -24
- package/dist/context-CkSg-kDT.js.map +0 -1
- package/dist/core-CmxaoZ-N.js +0 -1598
- package/dist/core-CmxaoZ-N.js.map +0 -1
- package/dist/css-writer-CPy_cbFJ.js.map +0 -1
- package/dist/format-global-rules-Dbc_1tc3.js +0 -22
- package/dist/format-global-rules-Dbc_1tc3.js.map +0 -1
- package/dist/format-rules-CPirO_Mj.js +0 -143
- package/dist/format-rules-CPirO_Mj.js.map +0 -1
- package/dist/hydrate-CVn-A_3y.js +0 -45
- package/dist/hydrate-CVn-A_3y.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/keyframes-vpzoVdUR.js +0 -588
- package/dist/keyframes-vpzoVdUR.js.map +0 -1
- package/dist/merge-styles-BzQutdAK.js.map +0 -1
- package/dist/resolve-recipes-DgH8A3Nn.js +0 -144
- package/dist/resolve-recipes-DgH8A3Nn.js.map +0 -1
package/docs/pipeline.md
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
This document describes the style rendering pipeline that transforms style objects into CSS rules. The pipeline ensures that each style value is applied to exactly one condition through exclusive condition building, boolean simplification, and intelligent CSS generation.
|
|
4
4
|
|
|
5
|
-
**Implementation:** [`src/pipeline/`](
|
|
5
|
+
**Implementation:** [`src/pipeline/`](https://github.com/tenphi/tasty/tree/main/src/pipeline) — TypeScript file names below are relative to that directory.
|
|
6
6
|
|
|
7
7
|
## Overview
|
|
8
8
|
|
|
9
|
-
The pipeline takes a `Styles` object and produces an array of `CSSRule` objects ready for injection into the DOM.
|
|
9
|
+
The pipeline takes a `Styles` object and produces an array of `CSSRule` objects ready for injection into the DOM. The entry point is `renderStyles`, which has two overloads: called with a selector or class (`renderStyles(styles, '.t1')`) it returns the rules directly; called without one (`renderStyles(styles)`) it returns `{ rules }` for a caller that will allocate the class name itself. The per-handler flow is:
|
|
10
10
|
|
|
11
11
|
```
|
|
12
12
|
Input: Styles Object
|
|
@@ -76,7 +76,7 @@ Output: CSSRule[]
|
|
|
76
76
|
|
|
77
77
|
**Simplification** (`simplifyCondition` in `simplify.ts`) is not a separate numbered stage. It runs inside OR expansion, exclusive building, `expandExclusiveOrs` branch cleanup, combination ANDs, merge-by-value ORs, and materialization. Every call is cached by condition unique-id, so the repetition is cheap.
|
|
78
78
|
|
|
79
|
-
**Post-pass:** After `processStyles` collects rules from every handler, `runPipeline` (`index.ts
|
|
79
|
+
**Post-pass:** After `processStyles` collects rules from every handler, `runPipeline` (`index.ts`) filters duplicates using a key of `selector|declarations|atRules|rootPrefix|startingStyle`, then **stable-sorts rules by their cascade `order` hint (ascending source priority)** so lower-priority rules come first and higher-priority rules win, and finally emits every `@starting-style` rule **after** all normal rules. Each Stage 4 snapshot takes the highest source priority among its entries as its `order` hint; when Stage 6 merges same-output rules, the merged rule keeps the lowest `order` of its group, so a rule carrying the `_` floor's value keeps the floor's early position (threaded `ComputedRule → CSSRule`). This ordering is cascade-critical because Stage 7 equalizes specificity with `:where()`: once every state selector carries zero specificity, source order alone decides which of two overlapping rules wins — most importantly the `_` fallback floor (low order, emitted first) versus the states layered over it, and `@starting-style` versus its normal counterpart. Mutually-exclusive rules are unaffected by ordering (they never both match), so reordering them is safe.
|
|
80
80
|
|
|
81
81
|
---
|
|
82
82
|
|
|
@@ -86,18 +86,22 @@ Output: CSSRule[]
|
|
|
86
86
|
|
|
87
87
|
### What It Does
|
|
88
88
|
|
|
89
|
-
Runs on each style's value map **before** any parsing
|
|
89
|
+
Runs on each style's value map **before** any parsing, when the map has at least three keys and one of them uses `&`. An atom is a **don't-care** when flipping it never changes which value the map resolves to; every key that mentions a don't-care atom is dropped.
|
|
90
90
|
|
|
91
91
|
### How It Works
|
|
92
92
|
|
|
93
|
-
1.
|
|
94
|
-
2.
|
|
95
|
-
3.
|
|
96
|
-
4. Drop
|
|
93
|
+
1. Split each key into its top-level `&` atoms. Keys containing `|`, `^`, or `,` at top level are a single opaque atom. The `_` floor (and a misused `_` key) is kept verbatim and left out of the analysis.
|
|
94
|
+
2. Treat the map as the cascade it is: the last authored key whose atoms all hold wins, and `''` is always the lowest priority.
|
|
95
|
+
3. An atom is a don't-care when, in every state, the cascade resolves to the same value with the atom present as with it absent. Only the states `(K₁ minus the atom) ∪ K₀`, for every key `K₁` that contains the atom and every key `K₀` that does not (or none), can tell the two apart, so the check is quadratic in the number of keys rather than exponential in atoms.
|
|
96
|
+
4. Drop every key that contains a don't-care atom. With the atom forced absent those keys never match, and by definition the result is unchanged.
|
|
97
|
+
|
|
98
|
+
The check is over the cascade, not over pairs of keys. In `{ '': A, checked: B, 'invalid & checked': C, disabled: A }`, `disabled` has the default's value, but it outranks `checked`: a checked, disabled element gets `A`, so `disabled` is not a don't-care. (An earlier pairwise rule — "every key with the atom has a same-value partner without it" — folded `disabled` into `''` here and lost that priority.)
|
|
99
|
+
|
|
100
|
+
Atoms are compared as strings and treated as independent. Real atoms can be related (`theme=dark` vs `theme=light`, nested media ranges); that only rules states out, so a don't-care over independent atoms is one for every real state too. Two guards keep the rewrite safe: a map with more than 32 distinct atoms is left unreduced, and a reduction that would leave the `_` floor alone with `''` (which means "use the floor", see Stage 1) is skipped.
|
|
97
101
|
|
|
98
102
|
### Why
|
|
99
103
|
|
|
100
|
-
Removing don't-care dimensions before parsing prevents combinatorial blowup in later stages. `mergeEntriesByValue`, `buildExclusiveConditions`, and materialization all see fewer entries and fewer spurious conditions.
|
|
104
|
+
Removing don't-care dimensions before parsing prevents combinatorial blowup in later stages. `mergeEntriesByValue`, `buildExclusiveConditions`, and materialization all see fewer entries and fewer spurious conditions.
|
|
101
105
|
|
|
102
106
|
### Example
|
|
103
107
|
|
|
@@ -120,6 +124,8 @@ Removing don't-care dimensions before parsing prevents combinatorial blowup in l
|
|
|
120
124
|
|
|
121
125
|
Converts each state key in a style value map (like `'hovered & !disabled'`, `'@media(w < 768px)'`) into `ConditionNode` trees. `parseStyleEntries` walks the object keys in source order and assigns priorities; `parseStateKey` parses a single key string.
|
|
122
126
|
|
|
127
|
+
`parseStyleEntries` also handles the bare `''` default and the standalone `_` fallback floor before the priority order is finalized. The bare `''` default only behaves correctly as the lowest-priority state, so a misplaced one is moved to the front (`MISPLACED_DEFAULT_STATE` warning). The `_` key is pulled out as a separate floor entry (`floor: true`, `TrueCondition`) and always assigned the lowest priority. If a map defines only `_` and a bare `''` (no other states), the `''` default is redundant — it is dropped in favor of the `_` value (`REDUNDANT_DEFAULT_STATE` warning). A `_` combined with state logic (`_ & hovered`, `_ | x`) is ignored (`INVALID_FALLBACK_KEY` warning).
|
|
128
|
+
|
|
123
129
|
### How It Works
|
|
124
130
|
|
|
125
131
|
1. **Tokenization**: The state key is split into tokens using a regex pattern that recognizes:
|
|
@@ -191,10 +197,14 @@ Merging two same-value entries with conditions `C_h` (higher priority) and `C_l`
|
|
|
191
197
|
|
|
192
198
|
The merge is safe iff for every entry `e_m` strictly between them in priority with a different value,
|
|
193
199
|
|
|
194
|
-
|
|
200
|
+
```
|
|
201
|
+
simplify(C_m & C_l & !C_h) = FALSE
|
|
202
|
+
```
|
|
195
203
|
|
|
196
204
|
i.e. there is no scenario where the intermediate state could have matched, the lower same-value entry would also have matched, and the higher one would not. This is the only way the merge could leak through and shadow the intermediate state.
|
|
197
205
|
|
|
206
|
+
An intermediate whose condition always holds (a tautological key, or same-value keys that already merged into one, like `beta | !beta`) is checked like any other. Only the `''` default and the `_` floor are exempt from the check, and they are always the lowest priorities, so they are never intermediates.
|
|
207
|
+
|
|
198
208
|
### Why
|
|
199
209
|
|
|
200
210
|
Without this pass a value map like `{ '@dark': 'red', '@dark & @hc': 'red' }` would create two separate entries that later produce two CSS rules with identical output. Merging before exclusive building keeps the exclusive condition algebra small and avoids duplicate CSS. The safety check ensures we never break the cascade in service of this optimization.
|
|
@@ -291,7 +301,35 @@ B: B & !A (applies only when A doesn't)
|
|
|
291
301
|
C: C & !A & !B (applies only when neither A nor B)
|
|
292
302
|
```
|
|
293
303
|
|
|
294
|
-
Each exclusive condition is passed through `simplifyCondition`. Entries that simplify to `FALSE` (impossible) are filtered out.
|
|
304
|
+
Each exclusive condition is passed through `simplifyCondition`. Entries that simplify to `FALSE` (impossible) are filtered out.
|
|
305
|
+
|
|
306
|
+
Every entry is added to the "prior" list, including one whose condition is `TRUE`. That can be a tautological key, or same-value keys that merged into one in Stage 1b (`alpha: X, '!alpha': X` → `TRUE`). Such an entry always applies at its priority, so negating it correctly makes every lower entry `FALSE`. The bare `''` default is `TRUE` too, but it is always the lowest priority, so no entry comes after it.
|
|
307
|
+
|
|
308
|
+
### `_` fallback floor
|
|
309
|
+
|
|
310
|
+
An entry flagged `floor: true` (from the standalone `_` key) is the one
|
|
311
|
+
exception to the negation cascade above. `buildExclusiveConditions` **pulls the
|
|
312
|
+
floor entries out** before the negation pass, builds the remaining entries with a
|
|
313
|
+
plain unconditional negation loop, then re-appends each floor with its own
|
|
314
|
+
(`TRUE`) condition as the exclusive condition. So the floor **always applies**,
|
|
315
|
+
never receives `!prior`, and never negates lower-priority entries. Because its
|
|
316
|
+
condition is `TRUE`, Stage 1 `mergeEntriesByValue` already leaves it untouched
|
|
317
|
+
(same guard as the bare `''` default), so no floor-specific merge handling is
|
|
318
|
+
needed.
|
|
319
|
+
|
|
320
|
+
This exists to fix the *unknown-query hole*: CSS three-valued logic makes
|
|
321
|
+
`not(unknown) = unknown`, so a negated `@supports(...)` / container-query default
|
|
322
|
+
branch silently never applies. A `_` floor sidesteps negation entirely and lets
|
|
323
|
+
the positive override layer on top via the cascade (see Stage 7's `:where()`
|
|
324
|
+
equalization and the ascending-priority post-pass).
|
|
325
|
+
|
|
326
|
+
Because the floor is **additive** (always emitted, never negated) rather than
|
|
327
|
+
mutually exclusive, it differs observably from the `''` default in two ways
|
|
328
|
+
beyond the unknown-query fix: an "empty" higher-priority state (one that emits no
|
|
329
|
+
declarations) cannot unset the property — the floor still applies — and when
|
|
330
|
+
states emit different declaration sets, the floor's declarations bleed through
|
|
331
|
+
wherever a winning state does not override the same property. The `''` default,
|
|
332
|
+
being negated, swaps out cleanly. See the DSL guide's "`_` vs the `''` default".
|
|
295
333
|
|
|
296
334
|
### Why
|
|
297
335
|
|
|
@@ -326,29 +364,36 @@ This is the companion to **Stage 2a** (user-OR expansion). The split exists beca
|
|
|
326
364
|
|
|
327
365
|
| Stage | Runs on | Sees ORs from | Sorts branches? |
|
|
328
366
|
|---|---|---|---|
|
|
329
|
-
| 2a `expandOrConditions` | `ParsedStyleEntry.condition` | User-authored
|
|
367
|
+
| 2a `expandOrConditions` | `ParsedStyleEntry.condition` | User-authored `\|` in state keys | No — user order is stable |
|
|
330
368
|
| 3 `expandExclusiveOrs` | `ExclusiveStyleEntry.exclusiveCondition` | De Morgan negation inside `buildExclusiveConditions` | Yes — at-rule branches first |
|
|
331
369
|
|
|
332
370
|
### How It Works
|
|
333
371
|
|
|
334
372
|
1. Collect top-level OR branches of `exclusiveCondition`.
|
|
335
373
|
2. If there is no OR (single branch), the entry is unchanged. Pure selector ORs with no at-rule context are also left alone (materialization handles them via `:is()` / variant merging).
|
|
336
|
-
3. Otherwise `sortOrBranchesForExpansion` reorders branches
|
|
374
|
+
3. Otherwise `sortOrBranchesForExpansion` reorders branches by a three-tier rank — `@supports` branches first, then other at-rule branches (media / container / starting), then pure-selector branches. This is load-bearing for correctness (see below).
|
|
337
375
|
4. Each branch is made exclusive against prior branches: `branch & !prior[0] & !prior[1] & ...`, then simplified.
|
|
338
376
|
5. Impossible branches are dropped; expanded entries get a synthetic `stateKey` suffix like `[or:0]`.
|
|
339
377
|
|
|
340
378
|
### Why the sort matters
|
|
341
379
|
|
|
342
|
-
Consider `!A | !B` where A is an at-rule (e.g. `@supports(grid)`) and B is a modifier (e.g. `:has(foo)`):
|
|
380
|
+
**At-rules before selectors.** Consider `!A | !B` where A is an at-rule (e.g. `@supports(grid)`) and B is a modifier (e.g. `:has(foo)`):
|
|
343
381
|
|
|
344
382
|
- **With at-rule-first sort** (`!A`, then `!B & A`): the first branch emits "outside `@supports`", the second emits "inside `@supports` with `:not(:has(foo))`". Full coverage.
|
|
345
383
|
- **Without the sort** (`!B`, then `!A & B`): the first branch emits `:not(:has(foo))` as a bare selector with no at-rule context — leaking the rule outside `@supports`. The second is incomplete.
|
|
346
384
|
|
|
385
|
+
**`@supports` before other at-rules (Kleene logic).** A `@supports` feature query is special: anything ANDed with it can become *unknown* — not simply false — when the feature is unsupported. The canonical case is a feature guard over a dependent query, e.g. `@supports(container-type: scroll-state) & @(scroll-state(scrolled: block-end))` (`S & C`). The default's exclusive is `!(S & C) = !S | !C`, which `simplify` sorts alphabetically into `[!C, !S]`.
|
|
386
|
+
|
|
387
|
+
- **Expanding `!C` first** emits a bare `@container (not scroll-state(...))` rule. In a browser without `scroll-state` support that query is unknown (not false), so it matches nothing and the default `inset` is never applied — a coverage hole.
|
|
388
|
+
- **Expanding `!S` first** yields `!S | (S & !C)`: a bare `@supports (not (container-type: scroll-state))` fallback carrying the default, plus the dependent negation nested inside the supported scope. Full coverage, and the unsupported path never references the guarded query.
|
|
389
|
+
|
|
390
|
+
Because `!S | (S & !R) ≡ !S | !R` in two-valued logic, this reordering is a no-op for cases without an `@supports` guard. The same supports-first ordering is also applied in `makeOrBranchesExclusive` (`materialize.ts`) for ORs that survive nested inside an AND (e.g. `compact & (!S | !C)`).
|
|
391
|
+
|
|
347
392
|
The pre-build Stage 2a pass doesn't need this because user-authored ORs aren't produced by negation and their branches are expected to apply in each branch's own scope.
|
|
348
393
|
|
|
349
394
|
### Example (conceptual)
|
|
350
395
|
|
|
351
|
-
See the comment block in `exclusive.ts
|
|
396
|
+
See the comment block on `expandExclusiveOrs` in `exclusive.ts`: a default value whose higher-priority sibling is `@supports(...) & :has(...)` gets an exclusive of `!@supports | !:has`. Expansion yields one branch under `@supports (not ...)` and another under `@supports (...) { :not(:has()) }` instead of a bare `:not(:has())` rule.
|
|
352
397
|
|
|
353
398
|
---
|
|
354
399
|
|
|
@@ -360,6 +405,8 @@ See the comment block in `exclusive.ts:500-523`: a default value whose higher-pr
|
|
|
360
405
|
|
|
361
406
|
Computes the Cartesian product of all style entries for a handler, creating snapshots of which value each style has for each possible state combination.
|
|
362
407
|
|
|
408
|
+
When every input is a direct value rather than a state map, the pipeline skips stages 0–4 and passes one unconditional snapshot directly to the handler. This avoids building exclusive entries and a Cartesian product for ordinary state-free styles.
|
|
409
|
+
|
|
363
410
|
### How It Works
|
|
364
411
|
|
|
365
412
|
1. Collect exclusive entries for each style the handler uses
|
|
@@ -419,6 +466,7 @@ Style handlers encapsulate the logic for translating design tokens (like `'2x'`)
|
|
|
419
466
|
### What It Does
|
|
420
467
|
|
|
421
468
|
Combines rules that have identical CSS output into a single rule with an OR condition.
|
|
469
|
+
Zero- and one-rule inputs return unchanged because no merge is possible.
|
|
422
470
|
|
|
423
471
|
### How It Works
|
|
424
472
|
|
|
@@ -470,7 +518,15 @@ Converts condition trees into actual CSS selectors and at-rules.
|
|
|
470
518
|
|
|
471
519
|
3. **Contradiction detection**: During variant merging, impossible combinations are dropped (e.g. conflicting media, root, or modifier negations).
|
|
472
520
|
|
|
473
|
-
4. **`materializeComputedRule`**: Groups variants by sorted at-rules plus root-prefix key; within each group, `mergeVariantsIntoSelectorGroups` merges variants that differ only in flat modifier/pseudo parts; builds selector strings and emits one or more `CSSRule` objects.
|
|
521
|
+
4. **`materializeComputedRule`**: Groups variants by sorted at-rules plus root-prefix key; within each group, `mergeVariantsIntoSelectorGroups` merges variants that differ only in flat modifier/pseudo parts; builds selector strings and emits one or more `CSSRule` objects. The rule's `order` hint (cascade priority) is propagated here for the post-pass sort.
|
|
522
|
+
|
|
523
|
+
5. **`:where()` specificity equalization**: Every stateful part of the selector is wrapped in `:where(...)` so it contributes **zero specificity**:
|
|
524
|
+
- the flat root modifiers + pseudos and the root element's `:is()`/`:not()` groups are combined into one `:where(...)` (`buildSelectorFromVariant`);
|
|
525
|
+
- the sub-element (`@own`) groups are wrapped in a **separate** `:where(...)` so the sub-element's structural `[data-element="X"]` specificity is preserved while its states are zeroed. When the suffix ends in a pseudo-element, these are the pseudo-element's own states and stay after it (`a::before:where(:hover)`). States a pseudo-element can't have (attributes, modifiers, classes, tree-structural pseudo-classes) are dropped with a `PSEUDO_ELEMENT_STATE_IGNORED` warning before Stage 0, using the CSS language alone, never per-browser support (`pseudo-element-states.ts`). A direct selector that ends in a pseudo-element (`.card::before`) is rendered separately: its root states are checked the same way and go after the pseudo-element, its `@parent` segments before it, at the `pseudoElementAt` each `CSSRule` records;
|
|
526
|
+
- `@parent` ancestors (`parentGroupsToCSS`) become `:where(... *)` / `:where(:not(... *))`;
|
|
527
|
+
- the `@root` context prefix (`rootStateToPrefix`) becomes `:where(:root...)` (zeroing the `:root` pseudo too). When a direct selector can only match the root itself (`:root`, `html`, `:where(:root)`), the state segment joins it instead — `:root:where([data-schema="dark"])` — since an ancestor prefix would ask for a `:root` inside the root.
|
|
528
|
+
|
|
529
|
+
The only specificity anchors that remain are the doubled component class (`.tXX.tXX`, added by the injector) and sub-element `[data-element]` attributes. Because Stage 2b already makes ordinary rules mutually exclusive, zeroing specificity never changes *which* rule matches — it only makes additive layering (`_` fallback floor, `@starting-style`) resolve deterministically by source order (see the post-pass). Canonical sorting/dedup/subsumption still run first; `:where()` is only the final wrapper, and both output paths (injector and direct-selector / SSR) consume the same wrapped fragments.
|
|
474
530
|
|
|
475
531
|
### Why
|
|
476
532
|
|
|
@@ -491,10 +547,13 @@ interface CSSRule {
|
|
|
491
547
|
declarations: string; // CSS declarations (e.g. 'color: red;')
|
|
492
548
|
atRules?: string[]; // Wrapping at-rules
|
|
493
549
|
rootPrefix?: string; // Root state prefix
|
|
550
|
+
rootState?: string; // Root-state segment without its :root anchor; lets a root selector take states directly
|
|
551
|
+
startingStyle?: boolean; // Wrap declarations in @starting-style
|
|
552
|
+
order?: number; // Internal cascade order hint (ascending source priority); stripped before injection
|
|
494
553
|
}
|
|
495
554
|
```
|
|
496
555
|
|
|
497
|
-
When `
|
|
556
|
+
When `renderStyles` runs **without** a selector, returned rules include `needsClassName: true` (compatibility field for the injector); that flag is not part of `CSSRule` (defined in `materialize-types.ts`).
|
|
498
557
|
|
|
499
558
|
---
|
|
500
559
|
|
|
@@ -562,7 +621,7 @@ Applies boolean algebra rules to reduce condition complexity and detect impossib
|
|
|
562
621
|
- `A & (A | B) = A`
|
|
563
622
|
- `A | (A & B) = A`
|
|
564
623
|
|
|
565
|
-
7. **Range intersection**: For **media and container** dimension queries, impossible ranges simplify to `FALSE` (e.g. `@media(w > 400px) & @media(w < 300px)`). Ranges with compatible bounds are also merged in place (`w >= 400 & w <= 800` → a single bounded range).
|
|
624
|
+
7. **Range intersection**: For **media and container** dimension queries, impossible ranges simplify to `FALSE` (e.g. `@media(w > 400px) & @media(w < 300px)`). Ranges with compatible bounds are also merged in place (`w >= 400 & w <= 800` → a single bounded range). Only bounds in the same unit are compared: `600px` and `40em` are never merged or found contradictory, because a query `em` follows the user's default font size. A bound with no numeric value (`calc(…)`) and a range whose two bounds use different units are left as they are.
|
|
566
625
|
|
|
567
626
|
8. **Container style queries**: Conflicting or redundant `@container` style conditions on the same property can be reduced (see `simplify.ts` around the container-style conflict pass).
|
|
568
627
|
|
|
@@ -586,7 +645,7 @@ LRU and small auxiliary caches:
|
|
|
586
645
|
| Cache | Size | Key | Purpose |
|
|
587
646
|
|-------|------|-----|---------|
|
|
588
647
|
| `pipelineCache` | 5000 | `pipelineCacheKey \|\| stringifyStyles(styles)` | Skip full pipeline for identical styles |
|
|
589
|
-
| `parseCache` | 5000 | `trimmedStateKey + '
|
|
648
|
+
| `parseCache` | 5000 | `trimmedStateKey + '\0' + (isSubElement ? '1' : '0') + '\0' + (localPredefinedStates non-empty ? JSON.stringify(localPredefinedStates) : '')` | Skip re-parsing identical state keys in context |
|
|
590
649
|
| `simplifyCache` | 5000 | `getConditionUniqueId(node)` | Skip re-simplifying identical conditions |
|
|
591
650
|
| `conditionCache` | 3000 | `getConditionUniqueId(node)` in `conditionToCSS` | Skip re-materializing identical conditions |
|
|
592
651
|
| `variantKeyCache` | — | `WeakMap<SelectorVariant, string>` | Stable string keys for variants during materialization |
|
|
@@ -638,7 +697,7 @@ The default entry's exclusive is `!hovered & !@media(dark)` — no top-level OR,
|
|
|
638
697
|
|
|
639
698
|
### Stages 4–5: Compute combinations and call handler
|
|
640
699
|
|
|
641
|
-
Single style, three snapshots; the `color` handler emits `color` plus `--current-color
|
|
700
|
+
Single style, three snapshots; the `color` handler emits `color` plus a `--current-color` variable.
|
|
642
701
|
|
|
643
702
|
### Stage 6: Merge by value
|
|
644
703
|
|
|
@@ -646,27 +705,24 @@ Each snapshot yields distinct declarations; no merge.
|
|
|
646
705
|
|
|
647
706
|
### Stage 7: Materialize CSS
|
|
648
707
|
|
|
649
|
-
Using `renderStyles(styles, '.t1'
|
|
708
|
+
Using `renderStyles(styles, '.t1', { doubleSelector: true })`. The injector doubles the class the same way (`.t1.t1`) so Tasty owns specificity without `!important`, and every state is wrapped in `:where()` so it adds none. Rules come out in ascending priority:
|
|
650
709
|
|
|
651
710
|
```css
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
711
|
+
@media (not (prefers-color-scheme: dark)) {
|
|
712
|
+
.t1.t1:where(:not([data-hovered])) {
|
|
713
|
+
color: var(--white-color);
|
|
714
|
+
--current-color: var(--white-color);
|
|
715
|
+
}
|
|
656
716
|
}
|
|
657
717
|
@media (prefers-color-scheme: dark) {
|
|
658
|
-
.t1:not([data-hovered]) {
|
|
718
|
+
.t1.t1:where(:not([data-hovered])) {
|
|
659
719
|
color: var(--dark-color);
|
|
660
720
|
--current-color: var(--dark-color);
|
|
661
|
-
--current-color-oklch: var(--dark-color-oklch);
|
|
662
721
|
}
|
|
663
722
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
--current-color: var(--white-color);
|
|
668
|
-
--current-color-oklch: var(--white-color-oklch);
|
|
669
|
-
}
|
|
723
|
+
.t1.t1:where([data-hovered]) {
|
|
724
|
+
color: var(--highlight-color);
|
|
725
|
+
--current-color: var(--highlight-color);
|
|
670
726
|
}
|
|
671
727
|
```
|
|
672
728
|
|
|
@@ -697,3 +753,16 @@ Impossible combinations are detected at multiple levels (simplification, variant
|
|
|
697
753
|
### 4. Aggressive Caching
|
|
698
754
|
|
|
699
755
|
Parse, simplify, condition-to-CSS, and full-pipeline results are cached independently, enabling fast re-rendering when only parts of the style object change.
|
|
756
|
+
|
|
757
|
+
Cache keys must respect key order where it carries meaning. A state map resolves by key order, so `{ '': A, checked: B, disabled: C }` and `{ '': A, disabled: C, checked: B }` are different styles and must get different keys (and classes). Only the style keys of a styles object, including a sub-element's, are order-insensitive, so they may be sorted. `stringifyStyles` (pipeline cache) and `generateChunkCacheKey` (class allocation) both follow this rule.
|
|
758
|
+
|
|
759
|
+
---
|
|
760
|
+
|
|
761
|
+
## Testing Priority
|
|
762
|
+
|
|
763
|
+
Every stage above is an optimization that must leave one thing unchanged: in any state, the value that applies is the value of the last authored key whose condition holds. `src/test/state-oracle.ts` states that rule directly, with none of the pipeline's machinery, and two suites compare the pipeline against it:
|
|
764
|
+
|
|
765
|
+
- `src/pipeline/exclusive.test.ts` (Node) evaluates the conditions after each of Stages 0–3 on thousands of generated maps, and names the stage that disagrees.
|
|
766
|
+
- `src/pipeline/state-priority.test.ts` (browser) renders hand-written, permuted, and generated maps to CSS, applies every combination of states (modifiers, value modifiers, `:has()`, `@root`, `@parent`, `@own`, media, supports), and compares what the browser computes against the oracle. It also checks that rules stay mutually exclusive, which a correct computed value alone can hide. It runs through the pipeline, the runtime injector, and the SSR collector, with all maps mounted at once so a cache-key collision shows up.
|
|
767
|
+
|
|
768
|
+
A change to any stage should keep both green. When a generated map fails, the message includes the map, the failing states, and the CSS; the map is usually worth adding to the hand-written cases once it is reduced.
|
package/docs/plugins.md
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# Plugins & Extension Points
|
|
2
|
+
|
|
3
|
+
How to extend Tasty: new value syntax, new units, new states, new style properties, new component props, and how to package any of it as a plugin.
|
|
4
|
+
|
|
5
|
+
- [What a plugin is](#what-a-plugin-is)
|
|
6
|
+
- [Choosing an extension point](#choosing-an-extension-point)
|
|
7
|
+
- [Custom style handlers](#custom-style-handlers)
|
|
8
|
+
- [Props middleware](#props-middleware)
|
|
9
|
+
- [Base style props](#base-style-props)
|
|
10
|
+
- [Typing your extension](#typing-your-extension)
|
|
11
|
+
- [Worked example: a `glaze` plugin](#worked-example-a-glaze-plugin)
|
|
12
|
+
- [Rendering modes and caveats](#rendering-modes-and-caveats)
|
|
13
|
+
- [Testing a plugin](#testing-a-plugin)
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## What a plugin is
|
|
18
|
+
|
|
19
|
+
A plugin is a plain object with a `name` and any subset of the `configure()` options it is allowed to supply. There is no lifecycle and no init hook — a plugin is just pre-packaged configuration.
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { configure } from '@tenphi/tasty';
|
|
23
|
+
import type { TastyPluginFactory } from '@tenphi/tasty';
|
|
24
|
+
|
|
25
|
+
const spacingPlugin: TastyPluginFactory = () => ({
|
|
26
|
+
name: 'spacing',
|
|
27
|
+
units: { gu: (n) => `calc(${n} * var(--grid-unit))` },
|
|
28
|
+
tokens: { '$grid-unit': '4px' },
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
configure({ plugins: [spacingPlugin()] });
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`TastyPluginFactory<TOptions>` types a factory that takes options; with no type argument it types a zero-argument factory.
|
|
35
|
+
|
|
36
|
+
**Ordering.** Plugins are applied in array order and merged key by key, so a later plugin overrides an earlier one for the same key. Options passed directly to `configure()` are applied last and win over every plugin.
|
|
37
|
+
|
|
38
|
+
**Configuration is locked after the first render.** `configure()` warns and does nothing once any style has been generated, so it must run before your first component renders — at module scope in your entry file, or in a design-system module every component imports. `resetConfig()` reopens it, but it exists for tests.
|
|
39
|
+
|
|
40
|
+
**Repeated `configure()` calls merge.** Each call adds to what earlier calls registered, key by key, in every registry (`states`, `units`, `functions`, `handlers`, `propHandlers`, `baseStyleProps`, `tokens`, `replaceTokens`, `recipes`, `keyframes`, `properties`, `fontFaces`, `counterStyles`); `globalStyles` merges per selector. A later value for the same key wins.
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## Choosing an extension point
|
|
45
|
+
|
|
46
|
+
| You want to add | Use | Runs | Build-time extraction |
|
|
47
|
+
| ------------------------------------------- | -------------------------- | ---------------------------- | ----------------------- |
|
|
48
|
+
| New value syntax — `okhsl(…)`, `double(2x)` | `functions` (bare key) | parse time, per value | ✅ |
|
|
49
|
+
| A reusable CSS `@function` | `functions` (`$$name` key) | injected once, globally | ✅ |
|
|
50
|
+
| A new unit — `2gu` | `units` | parse time, per value | ✅ |
|
|
51
|
+
| A new state alias — `@mobile` | `states` | state-key parse | ✅ |
|
|
52
|
+
| A style property → **CSS declarations** | `handlers` | pipeline, per state snapshot | ✅ |
|
|
53
|
+
| A style property on every component | `baseStyleProps` | prop harvest | ✅ (styles only) |
|
|
54
|
+
| A **component prop** → anything | `propHandlers` | render, per component | ❌ (no props to run on) |
|
|
55
|
+
| A named bundle of styles | `recipes` | before chunking | ✅ |
|
|
56
|
+
| Typography scale tokens | `presets` | inject time | ✅ |
|
|
57
|
+
| `:root` variables | `tokens`, `replaceTokens` | inject time | ✅ |
|
|
58
|
+
| Global selector styles | `globalStyles` | inject time | ✅ |
|
|
59
|
+
|
|
60
|
+
Two distinctions do most of the work:
|
|
61
|
+
|
|
62
|
+
- **`handlers` vs `propHandlers`.** A handler turns a _style property_ into CSS declarations and knows nothing about components. A prop handler turns a _component prop_ into other props — including `styles`, which then flow through the normal handlers. Reach for `propHandlers` when the input isn't a style value (an options object, a domain concept) or when it should affect more than styles.
|
|
63
|
+
- **`recipes` vs `propHandlers`.** A recipe is a static named bundle. A prop handler computes its styles from a value.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Custom style handlers
|
|
68
|
+
|
|
69
|
+
A handler receives a map of the style properties it declared and returns CSS declarations. See [Configuration → Custom Style Handlers](configuration.md#custom-style-handlers) for the definition forms, return shape, the shared-handler groups you must be careful of, and chunk membership. The essentials:
|
|
70
|
+
|
|
71
|
+
- Values arrive **state-resolved but unparsed** — the raw authored DSL string (`'2x'`, `'#purple.5'`, `true`, `4`). Call the exported `parseStyle()` / `parseColor()` yourself.
|
|
72
|
+
- Return a `CSSMap` with **kebab-case** keys, an array of them, or nothing. `$` is a selector suffix, not a property. A property whose value is an array gets one declaration per entry, for fallback chains.
|
|
73
|
+
- Handlers must be pure and synchronous. They are called once per state combination and the results are cached.
|
|
74
|
+
- Use `defineHandler(deps, fn)` for multi-dependency handlers so the dependency types are inferred.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { configure, defineHandler, parseStyle } from '@tenphi/tasty';
|
|
78
|
+
|
|
79
|
+
configure({
|
|
80
|
+
handlers: {
|
|
81
|
+
// Every declaration set the handler returns can target its own selector.
|
|
82
|
+
stripe: defineHandler(['stripe'], ({ stripe }) => {
|
|
83
|
+
if (!stripe) return;
|
|
84
|
+
|
|
85
|
+
const { values } = parseStyle(String(stripe)).groups[0];
|
|
86
|
+
|
|
87
|
+
return [
|
|
88
|
+
{ position: 'relative' },
|
|
89
|
+
{
|
|
90
|
+
$: '&::before',
|
|
91
|
+
content: '""',
|
|
92
|
+
position: 'absolute',
|
|
93
|
+
inset: '0 auto 0 0',
|
|
94
|
+
width: values[0],
|
|
95
|
+
background: 'var(--purple-color)',
|
|
96
|
+
},
|
|
97
|
+
];
|
|
98
|
+
}),
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## Props middleware
|
|
106
|
+
|
|
107
|
+
`propHandlers` are middleware over a component's props: props in, props out. They run at the very top of every tasty component's render, before any prop is destructured, so a handler can read and rewrite `styles`, `mods`, `tokens`, `variant`, `as`, `element`, and `qa`, and can strip its own props so they never reach the DOM.
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { configure, mergeStyles } from '@tenphi/tasty';
|
|
111
|
+
import type { Styles } from '@tenphi/tasty';
|
|
112
|
+
|
|
113
|
+
configure({
|
|
114
|
+
propHandlers: {
|
|
115
|
+
glaze: (props) => {
|
|
116
|
+
const { glaze, ...rest } = props;
|
|
117
|
+
if (!glaze) return rest;
|
|
118
|
+
|
|
119
|
+
// glazeStyles: see the worked example below
|
|
120
|
+
return {
|
|
121
|
+
...rest,
|
|
122
|
+
styles: mergeStyles(glazeStyles(glaze), rest.styles as Styles),
|
|
123
|
+
};
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**The key is the trigger.** By default a handler runs only when a prop matching its key is present, so an absent prop costs one property check rather than a call. Override that with a tuple:
|
|
130
|
+
|
|
131
|
+
| Definition | Runs when |
|
|
132
|
+
| ------------------------- | ------------------------------------- |
|
|
133
|
+
| `fn` | a prop named after the key is present |
|
|
134
|
+
| `['glaze', fn]` | `glaze` is present |
|
|
135
|
+
| `[['glaze', 'tint'], fn]` | either is present |
|
|
136
|
+
| `['*', fn]` | always |
|
|
137
|
+
|
|
138
|
+
**Chaining.** Handlers run in registration order — plugins first, then direct `configure()` — and each receives the previous one's output. Registering the same key twice replaces the handler in place, keeping its position.
|
|
139
|
+
|
|
140
|
+
**Returning nothing means unchanged**, with a development-mode warning, because that is almost always a forgotten `return props`. A non-object return is ignored with a warning.
|
|
141
|
+
|
|
142
|
+
### Rules
|
|
143
|
+
|
|
144
|
+
- **Be pure. Never mutate the input.** Style values are cached by object identity, so mutating a value object in place yields a stale class name _and_ stale CSS. Return fresh objects.
|
|
145
|
+
- **Memoize the styles you build, per input value.** A reference-stable (ideally frozen) styles object lets the cache key reuse its serialization instead of recomputing it on every render. This is the single highest-leverage thing you can do for performance.
|
|
146
|
+
- **Precedence is fixed** and not adjustable from a handler. Styles are merged as `factory defaults → styles → harvested style props`, and injected styles occupy the `styles` slot: they beat a component's own default styles and lose to a style prop passed at the call site. This matches how `recipe` already behaves.
|
|
147
|
+
- **Prefer returning `styles` over bare style props.** Returning `{ fill: '#red' }` only works if `fill` is harvestable on _that_ component (in its `styleProps`, or promoted via `baseStyleProps`); otherwise it leaks to the DOM.
|
|
148
|
+
|
|
149
|
+
### What it cannot do
|
|
150
|
+
|
|
151
|
+
- **`ref`** — `forwardRef` separates it from props, so it is out of reach.
|
|
152
|
+
- **Sub-elements** (`Card.Title`) — they have no `styles` prop and no style-prop harvest, so middleware does not run on them.
|
|
153
|
+
- **Build-time extraction** — see [Rendering modes](#rendering-modes-and-caveats).
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Base style props
|
|
158
|
+
|
|
159
|
+
A small set of style properties — `display`, `font`, `preset`, `hide`, `whiteSpace`, `opacity`, `transition` — are harvested as props on every `tasty()` component. `baseStyleProps` adds to that set globally:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
configure({ baseStyleProps: ['radius', 'shadow'] });
|
|
163
|
+
|
|
164
|
+
<Card radius="1r" shadow />
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Names must start with a lowercase letter and contain only letters and digits, and must not collide with a prop `tasty()` consumes itself (`as`, `styles`, `variant`, `mods`, `tokens`, …); invalid entries are dropped with a development warning. Names are not checked against the style registry, so a misspelled name is still harvested as a style prop.
|
|
168
|
+
|
|
169
|
+
`configure()` may run _after_ your components are defined — each factory resolves its prop list lazily and refreshes when the registry changes.
|
|
170
|
+
|
|
171
|
+
**Costs and caveats.** Each name adds one property check per render of every component, forever, so keep the list short. The effect is app-global and cannot be scoped to a subtree — use a factory's own `styleProps` for that. Be wary of names that collide with real DOM or component props (`width`, `size`, `color`): promoting one means every component swallows it as a style, including when rendering `as={SomeThirdPartyComponent}`.
|
|
172
|
+
|
|
173
|
+
---
|
|
174
|
+
|
|
175
|
+
## Typing your extension
|
|
176
|
+
|
|
177
|
+
Every extension point has a matching augmentation interface: `StylesInterface` for `handlers`, `TastyCustomProps` for `propHandlers`, `TastyBaseStylePropNames` for `baseStyleProps`, and `TastyNamedColors`, `TastyPresetNames`, and `TastyThemeNames` for the names your `tokens` and `presets` define. [Configuration → TypeScript](configuration.md#typescript) covers all six and the rules that go with them.
|
|
178
|
+
|
|
179
|
+
**Also update `tasty.config.ts`.** The ESLint plugin and VS Code extension validate style and token names against it, and neither reads the runtime registries or your augmentations:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
// tasty.config.ts
|
|
183
|
+
export default {
|
|
184
|
+
styles: ['stripe'],
|
|
185
|
+
tokens: ['#glaze-bg'],
|
|
186
|
+
};
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`propHandlers` keys are JSX props rather than style keys, so they need no entry — but any _style_ name or token a handler expands into does.
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Worked example: a `glaze` plugin
|
|
194
|
+
|
|
195
|
+
A `glaze` prop on every component that takes a configuration object and expands into color token declarations. This is the case `propHandlers` exists for: the value is an options object, not a style value, so it cannot be a style property.
|
|
196
|
+
|
|
197
|
+
```ts
|
|
198
|
+
// glaze-plugin.ts
|
|
199
|
+
import { mergeStyles } from '@tenphi/tasty';
|
|
200
|
+
import type { Styles, TastyPluginFactory } from '@tenphi/tasty';
|
|
201
|
+
|
|
202
|
+
export interface GlazeConfig {
|
|
203
|
+
tone: string;
|
|
204
|
+
/** 0–100. Default 10. */
|
|
205
|
+
intensity?: number;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
type GlazeValue = string | GlazeConfig;
|
|
209
|
+
|
|
210
|
+
// Memoized per value so the styles object is reference-stable across renders.
|
|
211
|
+
const cache = new Map<string, Styles>();
|
|
212
|
+
|
|
213
|
+
function glazeStyles(value: GlazeValue): Styles {
|
|
214
|
+
const { tone, intensity = 10 } =
|
|
215
|
+
typeof value === 'string' ? { tone: value } : value;
|
|
216
|
+
const key = `${tone}:${intensity}`;
|
|
217
|
+
|
|
218
|
+
let styles = cache.get(key);
|
|
219
|
+
|
|
220
|
+
if (!styles) {
|
|
221
|
+
styles = Object.freeze({
|
|
222
|
+
'#glaze-bg': `#${tone}.${intensity}`,
|
|
223
|
+
fill: '#glaze-bg',
|
|
224
|
+
transition: 'fill',
|
|
225
|
+
}) as Styles;
|
|
226
|
+
cache.set(key, styles);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return styles;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export const glazePlugin: TastyPluginFactory = () => ({
|
|
233
|
+
name: 'glaze',
|
|
234
|
+
|
|
235
|
+
propHandlers: {
|
|
236
|
+
glaze: (props) => {
|
|
237
|
+
const { glaze, ...rest } = props;
|
|
238
|
+
if (!glaze) return rest;
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
...rest,
|
|
242
|
+
styles: mergeStyles(
|
|
243
|
+
glazeStyles(glaze as GlazeValue),
|
|
244
|
+
rest.styles as Styles,
|
|
245
|
+
),
|
|
246
|
+
};
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
|
|
250
|
+
// Typed so `#glaze-bg` animates smoothly instead of snapping.
|
|
251
|
+
properties: {
|
|
252
|
+
'#glaze-bg': {
|
|
253
|
+
syntax: '<color>',
|
|
254
|
+
inherits: false,
|
|
255
|
+
initialValue: 'transparent',
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
// app entry, before the first render
|
|
263
|
+
import { configure } from '@tenphi/tasty';
|
|
264
|
+
|
|
265
|
+
import { glazePlugin } from './glaze-plugin';
|
|
266
|
+
|
|
267
|
+
configure({ plugins: [glazePlugin()] });
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
```tsx
|
|
271
|
+
<Element glaze="purple" />
|
|
272
|
+
<Element glaze={{ tone: 'success', intensity: 30 }} />
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
// tasty.d.ts
|
|
277
|
+
import '@tenphi/tasty';
|
|
278
|
+
|
|
279
|
+
declare module '@tenphi/tasty' {
|
|
280
|
+
interface TastyCustomProps {
|
|
281
|
+
glaze: import('./glaze-plugin').GlazeConfig | string;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
The object value is unambiguous here precisely because `glaze` is a **prop**. A style _value_ of the same shape would be indistinguishable from a state map (`{ tone: … }` looks exactly like `{ hovered: … }`), which is why this belongs in `propHandlers` rather than `handlers`.
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
## Rendering modes and caveats
|
|
291
|
+
|
|
292
|
+
| Mode | `functions` / `units` / `states` / `handlers` / `recipes` / `tokens` | `propHandlers` |
|
|
293
|
+
| -------------------------- | -------------------------------------------------------------------- | -------------- |
|
|
294
|
+
| Client | ✅ | ✅ |
|
|
295
|
+
| SSR / RSC | ✅ | ✅ |
|
|
296
|
+
| Build-time (`tastyStatic`) | ✅ at build time | not applicable |
|
|
297
|
+
|
|
298
|
+
**Build-time extraction.** The Babel plugin transforms `tastyStatic()` calls, which take styles objects — there are no props in that pipeline, so there is nothing for props middleware to run on. Components rendered through `tasty()` are untouched by the plugin; `propHandlers` work whether those components render on the server or in the browser. Everything in the `tastyStatic()` path runs at build time, which is why handlers, functions, and units must be pure functions of their input.
|
|
299
|
+
|
|
300
|
+
**Server and client must configure identically.** Class names are derived from resolved styles, so a handler or promoted prop registered on one side and not the other produces a hydration mismatch. This is the same requirement as `namePrefix` — see [SSR → Hydration mismatch warnings](ssr.md#hydration-mismatch-warnings).
|
|
301
|
+
|
|
302
|
+
---
|
|
303
|
+
|
|
304
|
+
## Testing a plugin
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
import { resetConfig, renderStyles } from '@tenphi/tasty';
|
|
308
|
+
import type { PropHandler, Styles } from '@tenphi/tasty';
|
|
309
|
+
|
|
310
|
+
describe('glaze plugin', () => {
|
|
311
|
+
beforeEach(() => resetConfig());
|
|
312
|
+
afterEach(() => resetConfig());
|
|
313
|
+
|
|
314
|
+
it('turns the glaze prop into styles', () => {
|
|
315
|
+
const glaze = glazePlugin().propHandlers!.glaze as PropHandler;
|
|
316
|
+
const out = glaze({ glaze: 'purple' })!;
|
|
317
|
+
|
|
318
|
+
expect(out).not.toHaveProperty('glaze');
|
|
319
|
+
|
|
320
|
+
const rules = renderStyles(out.styles as Styles, '.test');
|
|
321
|
+
expect(rules[0].declarations).toContain('--glaze-bg-color');
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
Two things to know:
|
|
327
|
+
|
|
328
|
+
- **Create components inside each test.** `resetConfig()` does not clear a component's own class-name cache, which `tasty()` keeps in DOM environments, so a module-scope component can keep returning a class whose CSS the reset removed.
|
|
329
|
+
- **Dev-mode warnings may not fire.** `isDevEnv()` reports `false` for `NODE_ENV=test`. Warnings that check it lazily can be enabled with `vi.stubEnv('NODE_ENV', 'development')`; some older ones capture it at module load and cannot be triggered from a test at all.
|
|
330
|
+
|
|
331
|
+
---
|
|
332
|
+
|
|
333
|
+
See [Configuration](configuration.md) for every option in detail, [Style DSL](dsl.md) for the value syntax your extensions produce, and [React API](react-api.md) for `tasty()`, `styleProps`, `modProps`, and `tokenProps`.
|