@tenphi/tasty 0.0.0-snapshot.27b6708 → 0.0.0-snapshot.28eb83c
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 +38 -54
- package/dist/{babel-BUQGeOXA.d.ts → babel-D6lOuSwk.d.ts} +2 -2
- package/dist/chunks/async-storage-DKK-wTD4.js.map +1 -0
- package/dist/chunks/build-config-BBThSdlo.js +45 -0
- package/dist/chunks/build-config-BBThSdlo.js.map +1 -0
- package/dist/{collector-DTahQUiV.js → chunks/collector-DcViW2ZQ.js} +28 -14
- package/dist/chunks/collector-DcViW2ZQ.js.map +1 -0
- package/dist/chunks/config-engine-DQVQK4NU.js +403 -0
- package/dist/chunks/config-engine-DQVQK4NU.js.map +1 -0
- package/dist/chunks/css-definitions-BZ9vm0ci.js +1284 -0
- package/dist/chunks/css-definitions-BZ9vm0ci.js.map +1 -0
- package/dist/chunks/css-resources-Cyl_axbI.js +149 -0
- package/dist/chunks/css-resources-Cyl_axbI.js.map +1 -0
- package/dist/chunks/debug-Vyauml7U.js +583 -0
- package/dist/chunks/debug-Vyauml7U.js.map +1 -0
- package/dist/chunks/dsl-CXvoaLnj.js +2097 -0
- package/dist/chunks/dsl-CXvoaLnj.js.map +1 -0
- package/dist/chunks/hydration-CLdVKcH2.js +59 -0
- package/dist/chunks/hydration-CLdVKcH2.js.map +1 -0
- package/dist/chunks/react-runtime-so_X_yMo.js +1526 -0
- package/dist/chunks/react-runtime-so_X_yMo.js.map +1 -0
- package/dist/chunks/runtime-engine-DQ5laRou.js +3056 -0
- package/dist/chunks/runtime-engine-DQ5laRou.js.map +1 -0
- package/dist/{merge-styles-oklji0KB.js → chunks/shared-utils-OIg0N_dp.js} +42 -3
- package/dist/chunks/shared-utils-OIg0N_dp.js.map +1 -0
- package/dist/{config-B5kHzuNz.js → chunks/style-engine-CBuOt1e4.js} +2387 -7442
- package/dist/chunks/style-engine-CBuOt1e4.js.map +1 -0
- package/dist/{css-writer-B-J87ncv.js → chunks/zero-engine-BFh7gKbK.js} +3 -3
- package/dist/chunks/zero-engine-BFh7gKbK.js.map +1 -0
- package/dist/{collector-DUaHCcTS.d.ts → collector-CAmndLXe.d.ts} +23 -3
- package/dist/{config-YsxGv4tq.d.ts → config-BWYrv_Aa.d.ts} +141 -37
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +9 -6
- package/dist/{index-Cd45t5NM.d.ts → index-BzAC3p06.d.ts} +118 -23
- package/dist/{index-PqN-DIpn.d.ts → index-D4kRLj2o.d.ts} +128 -68
- package/dist/index.d.ts +5 -5
- package/dist/index.js +10 -922
- package/dist/{merge-styles-CU7JbEwg.d.ts → merge-styles-BFktNP8J.d.ts} +2 -2
- package/dist/ssr/astro-client.js +1 -1
- package/dist/ssr/astro-middleware-extract-static.d.ts +11 -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 +11 -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 +3 -1
- package/dist/ssr/astro-middleware.d.ts +3 -1
- package/dist/ssr/astro.d.ts +45 -3
- package/dist/ssr/astro.js +157 -14
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/index.d.ts +7 -7
- package/dist/ssr/index.js +4 -4
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next-config.d.ts +66 -0
- package/dist/ssr/next-config.js +135 -0
- package/dist/ssr/next-config.js.map +1 -0
- package/dist/ssr/next.d.ts +9 -2
- package/dist/ssr/next.js +26 -10
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +2 -2
- package/dist/static/index.js +1 -1
- package/dist/zero/babel.d.ts +1 -1
- package/dist/zero/babel.js +25 -24
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +1 -1
- package/dist/zero/index.js +1 -1
- package/dist/zero/next.d.ts +1 -1
- package/docs/README.md +5 -3
- package/docs/adoption.md +3 -3
- package/docs/ai-agents.md +83 -78
- package/docs/comparison.md +12 -12
- package/docs/configuration.md +47 -47
- package/docs/debug.md +19 -7
- package/docs/dsl.md +3 -3
- package/docs/getting-started.md +10 -10
- package/docs/injector.md +62 -25
- package/docs/methodology.md +3 -3
- package/docs/migration-v3.md +49 -49
- package/docs/plugins.md +37 -33
- package/docs/react-api.md +2 -2
- package/docs/runtime-benchmarks.md +351 -0
- package/docs/ssr.md +219 -61
- package/docs/styles.md +43 -11
- package/docs/tasty-static.md +136 -103
- package/package.json +80 -11
- package/dist/async-storage-DKK-wTD4.js.map +0 -1
- package/dist/collector-DTahQUiV.js.map +0 -1
- package/dist/config-B5kHzuNz.js.map +0 -1
- package/dist/context-CA8YKeMn.js +0 -24
- package/dist/context-CA8YKeMn.js.map +0 -1
- package/dist/core-Dr4u1NVD.js +0 -1566
- package/dist/core-Dr4u1NVD.js.map +0 -1
- package/dist/css-writer-B-J87ncv.js.map +0 -1
- package/dist/format-global-rules-DklyaXv-.js +0 -22
- package/dist/format-global-rules-DklyaXv-.js.map +0 -1
- package/dist/format-rules-DKOA-6qu.js +0 -130
- package/dist/format-rules-DKOA-6qu.js.map +0 -1
- package/dist/hydrate-OeMX99We.js +0 -37
- package/dist/hydrate-OeMX99We.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/keyframes-CV8azJf3.js +0 -493
- package/dist/keyframes-CV8azJf3.js.map +0 -1
- package/dist/merge-styles-oklji0KB.js.map +0 -1
- package/dist/resolve-recipes-DTG81rzl.js +0 -144
- package/dist/resolve-recipes-DTG81rzl.js.map +0 -1
- /package/dist/{async-storage-DKK-wTD4.js → chunks/async-storage-DKK-wTD4.js} +0 -0
|
@@ -0,0 +1,3056 @@
|
|
|
1
|
+
import { T as Lru, h as resetGlobalPredefinedTokens, m as resetGlobalParseFunctions, p as parseStyle } from "./dsl-CXvoaLnj.js";
|
|
2
|
+
import { i as warn, n as isSelector, o as isDevEnv, r as resetStyleWarnings } from "./shared-utils-OIg0N_dp.js";
|
|
3
|
+
import { A as rscClassRegexGlobal, B as formatFunctionDeclarations, D as makeClassName, F as getEffectiveDefinition, L as normalizePropertyDefinition, M as validateNamePrefix, N as hashString, V as formatFunctionPrelude, W as parseFunctionName, b as fontFaceContentHash, g as formatCounterStyleDeclarations, j as tastyClassRegex, k as makeKeyframeName, m as DEFAULT_PROPERTIES, q as resetFunctionPolyfills, w as PropertyTypeResolver, x as formatFontFaceDeclarations } from "./css-definitions-BZ9vm0ci.js";
|
|
4
|
+
import { C as STYLE_HANDLER_MAP, D as resetHandlers, G as resetGlobalPolyfillsState, H as hasStylesGenerated, K as resetStylesGeneratedState, R as resetStyleChunks, U as isFunctionsPolyfillEnabled, W as markStylesGeneratedState, a as registerBaseStyleProps, b as renderStyles, k as createStyle, o as resetBaseStyleProps, y as clearPipelineCache } from "./style-engine-CBuOt1e4.js";
|
|
5
|
+
import { n as applyStyleConfig, r as normalizeConfig, t as resolveRecipesWith } from "./config-engine-DQVQK4NU.js";
|
|
6
|
+
//#region src/prop-handlers.ts
|
|
7
|
+
/**
|
|
8
|
+
* Props middleware for tasty components.
|
|
9
|
+
*
|
|
10
|
+
* A prop handler receives a component's props and returns them, changed or not.
|
|
11
|
+
* That makes it the extension point for props that are *not* style properties:
|
|
12
|
+
* it can read a custom prop, strip it so it never reaches the DOM, and fold its
|
|
13
|
+
* meaning into `styles`, `mods`, `tokens`, `variant`, or `as`.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* configure({
|
|
17
|
+
* propHandlers: {
|
|
18
|
+
* glaze: (props) => {
|
|
19
|
+
* const { glaze, ...rest } = props;
|
|
20
|
+
* if (!glaze) return rest;
|
|
21
|
+
* return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };
|
|
22
|
+
* },
|
|
23
|
+
* },
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* Handlers run on every render of every tasty component, so the registry is a
|
|
28
|
+
* pre-composed chain that is `null` while nothing is registered — the cost when
|
|
29
|
+
* unused is one property load and one branch.
|
|
30
|
+
*/
|
|
31
|
+
const GTKEY = "__tasty_prop_handlers__";
|
|
32
|
+
const globalStore = globalThis;
|
|
33
|
+
const propHandlerRegistry = globalStore[GTKEY] ?? (globalStore[GTKEY] = {
|
|
34
|
+
apply: null,
|
|
35
|
+
list: []
|
|
36
|
+
});
|
|
37
|
+
function normalize(key, definition, options) {
|
|
38
|
+
const source = options?.source ?? "configure()";
|
|
39
|
+
if (typeof definition === "function") return {
|
|
40
|
+
key,
|
|
41
|
+
triggers: [key],
|
|
42
|
+
fn: definition,
|
|
43
|
+
source
|
|
44
|
+
};
|
|
45
|
+
if (Array.isArray(definition)) {
|
|
46
|
+
const [first, fn] = definition;
|
|
47
|
+
if (typeof fn !== "function") throw new Error(`[Tasty] Invalid prop handler definition for "${key}". Tuple must have a function as the second element: [string, function] or [string[], function].`);
|
|
48
|
+
if (first === "*") return {
|
|
49
|
+
key,
|
|
50
|
+
triggers: null,
|
|
51
|
+
fn,
|
|
52
|
+
source
|
|
53
|
+
};
|
|
54
|
+
if (typeof first === "string") return {
|
|
55
|
+
key,
|
|
56
|
+
triggers: [first],
|
|
57
|
+
fn,
|
|
58
|
+
source
|
|
59
|
+
};
|
|
60
|
+
if (Array.isArray(first)) return {
|
|
61
|
+
key,
|
|
62
|
+
triggers: first.includes("*") ? null : first,
|
|
63
|
+
fn,
|
|
64
|
+
source
|
|
65
|
+
};
|
|
66
|
+
throw new Error(`[Tasty] Invalid prop handler definition for "${key}". First element must be a string or string array.`);
|
|
67
|
+
}
|
|
68
|
+
throw new Error(`[Tasty] Invalid prop handler definition for "${key}". Expected function, [string, function], or [string[], function].`);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Run one handler, treating a nothing/non-object return as "unchanged".
|
|
72
|
+
*
|
|
73
|
+
* `isDevEnv()` is called lazily rather than captured at module load so the
|
|
74
|
+
* warnings are assertable in tests; it is only reached on the misuse path.
|
|
75
|
+
*/
|
|
76
|
+
function runOne(handler, props) {
|
|
77
|
+
const next = handler.fn(props);
|
|
78
|
+
if (next != null && typeof next === "object" && !Array.isArray(next)) return next;
|
|
79
|
+
if (isDevEnv()) console.warn(next == null ? `[Tasty] propHandlers["${handler.key}"] (from ${handler.source}) returned ${String(next)}. Props are treated as unchanged — did you forget to \`return props\`?` : `[Tasty] propHandlers["${handler.key}"] (from ${handler.source}) returned ${Array.isArray(next) ? "an array" : typeof next}. A prop handler must return a props object. The result was ignored.`);
|
|
80
|
+
return props;
|
|
81
|
+
}
|
|
82
|
+
function compose(list) {
|
|
83
|
+
if (list.length === 0) return null;
|
|
84
|
+
if (list.length === 1) {
|
|
85
|
+
const only = list[0];
|
|
86
|
+
if (only.triggers === null) return (props) => runOne(only, props);
|
|
87
|
+
if (only.triggers.length === 1) {
|
|
88
|
+
const trigger = only.triggers[0];
|
|
89
|
+
return (props) => trigger in props ? runOne(only, props) : props;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return (props) => {
|
|
93
|
+
for (const handler of list) {
|
|
94
|
+
const triggers = handler.triggers;
|
|
95
|
+
if (triggers !== null) {
|
|
96
|
+
let triggered = false;
|
|
97
|
+
for (const trigger of triggers) if (trigger in props) {
|
|
98
|
+
triggered = true;
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
if (!triggered) continue;
|
|
102
|
+
}
|
|
103
|
+
props = runOne(handler, props);
|
|
104
|
+
}
|
|
105
|
+
return props;
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Register a props middleware under `key`, replacing any handler already
|
|
110
|
+
* registered under the same key while keeping its position in the chain.
|
|
111
|
+
*/
|
|
112
|
+
function registerPropHandler(key, definition, options) {
|
|
113
|
+
const normalized = normalize(key, definition, options);
|
|
114
|
+
const { list } = propHandlerRegistry;
|
|
115
|
+
const existing = list.findIndex((handler) => handler.key === key);
|
|
116
|
+
if (existing === -1) list.push(normalized);
|
|
117
|
+
else list[existing] = normalized;
|
|
118
|
+
propHandlerRegistry.apply = compose(list);
|
|
119
|
+
}
|
|
120
|
+
/** Drop every registered props middleware. Called by `resetConfig()`. */
|
|
121
|
+
function resetPropHandlers() {
|
|
122
|
+
if (propHandlerRegistry.list.length === 0) return;
|
|
123
|
+
propHandlerRegistry.list.length = 0;
|
|
124
|
+
propHandlerRegistry.apply = null;
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region src/injector/batch.ts
|
|
128
|
+
/**
|
|
129
|
+
* Deferred CSSOM writes ("batched injection").
|
|
130
|
+
*
|
|
131
|
+
* Every `insertRule()` on a live stylesheet invalidates style for the sheet's
|
|
132
|
+
* scope, so Blink recalculates style the next time anything reads layout or
|
|
133
|
+
* computed style. When components inject during React's render phase and other
|
|
134
|
+
* components read layout in the same pass, the two interleave:
|
|
135
|
+
*
|
|
136
|
+
* inject -> read (forced recalc) -> inject -> read (forced recalc) -> ...
|
|
137
|
+
*
|
|
138
|
+
* Batching moves every sheet write out from between those reads. Writes are
|
|
139
|
+
* queued in FIFO order and drained in one go, so the tree is invalidated once
|
|
140
|
+
* per flush instead of once per component.
|
|
141
|
+
*
|
|
142
|
+
* ## Ordering
|
|
143
|
+
*
|
|
144
|
+
* A single queue holds *all* writes — component rules, global rules, keyframes,
|
|
145
|
+
* `@property`, `@font-face`, `@counter-style`, `@function` and raw CSS. Draining
|
|
146
|
+
* it in insertion order keeps the sheet byte-identical to unbatched output,
|
|
147
|
+
* which matters because equal-specificity rules resolve by document order.
|
|
148
|
+
*
|
|
149
|
+
* ## Batch windows — why queuing is safe
|
|
150
|
+
*
|
|
151
|
+
* Deferring a write past React's layout phase would let a `useLayoutEffect`
|
|
152
|
+
* measure an element whose rules are not in the sheet yet, reading the unstyled
|
|
153
|
+
* box. `<TastyBatchProvider>` closes that hole by opening a *window* during its
|
|
154
|
+
* render and closing it — flushing — in its `useInsertionEffect`, which React
|
|
155
|
+
* runs in the mutation phase, before any layout effect:
|
|
156
|
+
*
|
|
157
|
+
* provider renders -> window OPEN
|
|
158
|
+
* children render -> injections queued
|
|
159
|
+
* provider insertionEffect -> FLUSH, window CLOSED
|
|
160
|
+
* layout effects run -> rules are in the sheet
|
|
161
|
+
*
|
|
162
|
+
* So in the default (`batchInjection: true`) mode a write is only ever queued
|
|
163
|
+
* inside a commit whose flush is already guaranteed by that same commit. Every
|
|
164
|
+
* injection outside a window — a deep update the provider did not re-render
|
|
165
|
+
* for, a `useLayoutEffect` that injects, an event handler, an async callback —
|
|
166
|
+
* is written straight through, exactly as with batching off.
|
|
167
|
+
*
|
|
168
|
+
* `batchInjection: 'always'` opts out of the gate and queues unconditionally.
|
|
169
|
+
* That wins on more commits, at the cost of the measurement hazard above.
|
|
170
|
+
*
|
|
171
|
+
* ## Flush points (earliest wins)
|
|
172
|
+
*
|
|
173
|
+
* 1. `<TastyBatchProvider>`'s `useInsertionEffect` — closes the window.
|
|
174
|
+
* 2. A microtask — a backstop for a render that was aborted or suspended and
|
|
175
|
+
* therefore never reached its insertion effect. An aborted render mounts
|
|
176
|
+
* nothing, so nothing can measure what it queued. Microtasks also always
|
|
177
|
+
* drain before paint, so styles are never visually missing.
|
|
178
|
+
* 3. `flushStyles()` — explicit, and called internally by every injector read
|
|
179
|
+
* API (`getCSSText`, `cleanup`, `gc`, `destroy`, ...).
|
|
180
|
+
*/
|
|
181
|
+
/**
|
|
182
|
+
* FIFO of pending writes. Drained with a moving `head` index rather than
|
|
183
|
+
* `shift()` so a large batch stays O(n) instead of O(n²).
|
|
184
|
+
*/
|
|
185
|
+
let queue = [];
|
|
186
|
+
let head = 0;
|
|
187
|
+
let microtaskScheduled = false;
|
|
188
|
+
let flushing = false;
|
|
189
|
+
/**
|
|
190
|
+
* Whether a `<TastyBatchProvider>` has rendered in the current commit and will
|
|
191
|
+
* therefore flush in its insertion effect, making it safe to queue a write.
|
|
192
|
+
*
|
|
193
|
+
* A flag rather than a depth count, because renders and insertion effects do
|
|
194
|
+
* not pair up one-to-one. StrictMode double-invokes render but runs the
|
|
195
|
+
* insertion effect once, so a counter ends the commit stuck above zero — and a
|
|
196
|
+
* window that stays open past its commit turns the next provider-less commit
|
|
197
|
+
* into `'always'` mode behind the user's back, which is exactly the measurement
|
|
198
|
+
* hazard `true` exists to avoid.
|
|
199
|
+
*
|
|
200
|
+
* Clearing on the first close is safe with nested or sibling providers: React
|
|
201
|
+
* finishes every render in a commit before running any insertion effect, so once
|
|
202
|
+
* one closes, no further render-phase injection can arrive in that commit.
|
|
203
|
+
*/
|
|
204
|
+
let windowOpen = false;
|
|
205
|
+
/** Whether any window has ever been opened, i.e. a provider is in the tree. */
|
|
206
|
+
let everOpened = false;
|
|
207
|
+
/** Dev-only: warn at most once that batching is on with no provider mounted. */
|
|
208
|
+
let warnedNoProvider = false;
|
|
209
|
+
/**
|
|
210
|
+
* Queue a sheet write.
|
|
211
|
+
*
|
|
212
|
+
* Returns a handle whose `cancel()` drops the write if the caller disposes
|
|
213
|
+
* before the flush. The handle is intentionally tiny — one is allocated per
|
|
214
|
+
* injected class, on the cache-miss path only.
|
|
215
|
+
*/
|
|
216
|
+
function enqueueStyleWrite(run) {
|
|
217
|
+
if (flushing) {
|
|
218
|
+
run();
|
|
219
|
+
return {
|
|
220
|
+
run,
|
|
221
|
+
cancelled: false,
|
|
222
|
+
done: true
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const entry = {
|
|
226
|
+
run,
|
|
227
|
+
cancelled: false,
|
|
228
|
+
done: false
|
|
229
|
+
};
|
|
230
|
+
queue.push(entry);
|
|
231
|
+
scheduleMicrotaskFlush();
|
|
232
|
+
return entry;
|
|
233
|
+
}
|
|
234
|
+
/** Whether any write is still waiting to hit a stylesheet. */
|
|
235
|
+
function hasPendingStyleWrites() {
|
|
236
|
+
return head < queue.length;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Open a batch window. Called from `<TastyBatchProvider>`'s render, so every
|
|
240
|
+
* descendant injection in this commit is covered by the provider's insertion
|
|
241
|
+
* effect.
|
|
242
|
+
*
|
|
243
|
+
* Called during render on purpose: the window must be open before children
|
|
244
|
+
* render. It is idempotent — so StrictMode's double render costs nothing — and
|
|
245
|
+
* carries no other side effect. A render that is thrown away is recovered by the
|
|
246
|
+
* microtask backstop.
|
|
247
|
+
*
|
|
248
|
+
* A no-op without a `document`. On the server there is no sheet to batch
|
|
249
|
+
* against, and `useInsertionEffect` never runs, so nothing would ever close a
|
|
250
|
+
* window this opened. Skipping it keeps the provider inert during SSR and RSC
|
|
251
|
+
* instead of merely harmless.
|
|
252
|
+
*/
|
|
253
|
+
function openBatchWindow() {
|
|
254
|
+
if (typeof document === "undefined") return;
|
|
255
|
+
windowOpen = true;
|
|
256
|
+
everOpened = true;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Close a batch window and flush. Called from the provider's
|
|
260
|
+
* `useInsertionEffect`, i.e. after every render in the commit and before any
|
|
261
|
+
* layout effect.
|
|
262
|
+
*/
|
|
263
|
+
function closeBatchWindow() {
|
|
264
|
+
windowOpen = false;
|
|
265
|
+
flushStyles();
|
|
266
|
+
}
|
|
267
|
+
/** Whether a batch window is currently open. */
|
|
268
|
+
function isBatchWindowOpen() {
|
|
269
|
+
return windowOpen;
|
|
270
|
+
}
|
|
271
|
+
function scheduleMicrotaskFlush() {
|
|
272
|
+
if (microtaskScheduled || flushing) return;
|
|
273
|
+
microtaskScheduled = true;
|
|
274
|
+
queueMicrotask(() => {
|
|
275
|
+
microtaskScheduled = false;
|
|
276
|
+
windowOpen = false;
|
|
277
|
+
flushStyles();
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Drain every pending sheet write, in insertion order.
|
|
282
|
+
*
|
|
283
|
+
* Safe to call when the queue is empty (the common case, so the guard comes
|
|
284
|
+
* first) and safe to call re-entrantly: a nested `flushStyles()` is a no-op,
|
|
285
|
+
* and work a draining write triggers is written in place by
|
|
286
|
+
* `enqueueStyleWrite` rather than queued behind the rest of the batch.
|
|
287
|
+
*/
|
|
288
|
+
function flushStyles() {
|
|
289
|
+
if (head >= queue.length) return;
|
|
290
|
+
if (flushing) return;
|
|
291
|
+
flushing = true;
|
|
292
|
+
try {
|
|
293
|
+
while (head < queue.length) {
|
|
294
|
+
const entry = queue[head++];
|
|
295
|
+
if (entry.cancelled) {
|
|
296
|
+
entry.done = true;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
entry.run();
|
|
300
|
+
entry.done = true;
|
|
301
|
+
}
|
|
302
|
+
} finally {
|
|
303
|
+
queue = [];
|
|
304
|
+
head = 0;
|
|
305
|
+
flushing = false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Dev-only: `batchInjection: true` batches nothing unless a window opens, and no
|
|
310
|
+
* window has ever opened, so no provider is in the tree. Called by the injector
|
|
311
|
+
* the first time it declines to batch.
|
|
312
|
+
*/
|
|
313
|
+
function warnBatchProviderMissing() {
|
|
314
|
+
if (everOpened || warnedNoProvider || !isDevEnv()) return;
|
|
315
|
+
warnedNoProvider = true;
|
|
316
|
+
warn("[Tasty] batchInjection needs <TastyBatchProvider> mounted to batch.");
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Drop every pending write without applying it. Test helper — production code
|
|
320
|
+
* should call `flushStyles()` instead.
|
|
321
|
+
*/
|
|
322
|
+
function resetStyleBatch() {
|
|
323
|
+
queue = [];
|
|
324
|
+
head = 0;
|
|
325
|
+
microtaskScheduled = false;
|
|
326
|
+
flushing = false;
|
|
327
|
+
windowOpen = false;
|
|
328
|
+
everOpened = false;
|
|
329
|
+
warnedNoProvider = false;
|
|
330
|
+
}
|
|
331
|
+
//#endregion
|
|
332
|
+
//#region src/injector/sheet-manager.ts
|
|
333
|
+
const supportsConstructableSheets = typeof CSSStyleSheet !== "undefined" && (() => {
|
|
334
|
+
try {
|
|
335
|
+
new CSSStyleSheet();
|
|
336
|
+
return true;
|
|
337
|
+
} catch {
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
})();
|
|
341
|
+
var SheetManager = class {
|
|
342
|
+
rootRegistries = /* @__PURE__ */ new WeakMap();
|
|
343
|
+
/** Strong set of active roots so background GC can iterate them all */
|
|
344
|
+
activeRoots = /* @__PURE__ */ new Set();
|
|
345
|
+
config;
|
|
346
|
+
/** Dedicated style elements for raw CSS per root */
|
|
347
|
+
rawStyleElements = /* @__PURE__ */ new WeakMap();
|
|
348
|
+
/** Constructable sheets for raw CSS in adopted mode */
|
|
349
|
+
rawConstructableSheets = /* @__PURE__ */ new WeakMap();
|
|
350
|
+
/** Tracking for raw CSS blocks per root */
|
|
351
|
+
rawCSSBlocks = /* @__PURE__ */ new WeakMap();
|
|
352
|
+
/** Counter for generating unique raw CSS IDs */
|
|
353
|
+
rawCSSCounter = 0;
|
|
354
|
+
constructor(config) {
|
|
355
|
+
this.config = config;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Resolve the underlying CSSStyleSheet from a SheetInfo,
|
|
359
|
+
* abstracting away adopted vs style-element modes.
|
|
360
|
+
*/
|
|
361
|
+
getCSSSheet(sheetInfo) {
|
|
362
|
+
if (sheetInfo.constructableSheet) return sheetInfo.constructableSheet;
|
|
363
|
+
return sheetInfo.sheet?.sheet ?? null;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Record an inserted rule text at its rule index (text mode only).
|
|
367
|
+
*
|
|
368
|
+
* `textRules` mirrors the sheet's rule order. `textContent` cannot be edited
|
|
369
|
+
* rule-by-rule the way CSSOM can, so keeping the texts is what makes
|
|
370
|
+
* deletion possible at all in this mode.
|
|
371
|
+
*/
|
|
372
|
+
trackTextRule(sheet, ruleIndex, ruleText) {
|
|
373
|
+
if (!sheet.textMode) return;
|
|
374
|
+
const rules = sheet.textRules ??= [];
|
|
375
|
+
while (rules.length < ruleIndex) rules.push("");
|
|
376
|
+
rules[ruleIndex] = ruleText;
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Remove rule indices from a text-mode sheet and rewrite the element's text.
|
|
380
|
+
* Returns the indices that were actually removed.
|
|
381
|
+
*/
|
|
382
|
+
deleteTextRules(sheet, indices) {
|
|
383
|
+
const rules = sheet.textRules;
|
|
384
|
+
if (!rules) return [];
|
|
385
|
+
const removed = [...new Set(indices)].filter((idx) => idx >= 0 && idx < rules.length).sort((a, b) => b - a);
|
|
386
|
+
for (const idx of removed) rules.splice(idx, 1);
|
|
387
|
+
if (removed.length > 0 && sheet.sheet) sheet.sheet.textContent = rules.length ? "\n" + rules.join("\n") : "";
|
|
388
|
+
return removed;
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Determine the injection mode for a root.
|
|
392
|
+
* ShadowRoot uses adopted stylesheets when supported; Document uses <style> elements.
|
|
393
|
+
*/
|
|
394
|
+
detectInjectionMode(root) {
|
|
395
|
+
if (root instanceof ShadowRoot && supportsConstructableSheets && !this.config.forceTextInjection) return "adopted";
|
|
396
|
+
return "style-element";
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Get or create registry for a root (Document or ShadowRoot)
|
|
400
|
+
*/
|
|
401
|
+
getRegistry(root) {
|
|
402
|
+
let registry = this.rootRegistries.get(root);
|
|
403
|
+
if (!registry) {
|
|
404
|
+
const metrics = this.config.devMode ? {
|
|
405
|
+
hits: 0,
|
|
406
|
+
misses: 0,
|
|
407
|
+
bulkCleanups: 0,
|
|
408
|
+
totalInsertions: 0,
|
|
409
|
+
totalUnused: 0,
|
|
410
|
+
stylesCleanedUp: 0,
|
|
411
|
+
cleanupHistory: [],
|
|
412
|
+
startTime: Date.now()
|
|
413
|
+
} : void 0;
|
|
414
|
+
registry = {
|
|
415
|
+
sheets: [],
|
|
416
|
+
pinCounts: /* @__PURE__ */ new Map(),
|
|
417
|
+
rules: /* @__PURE__ */ new Map(),
|
|
418
|
+
cacheKeyToClassName: /* @__PURE__ */ new Map(),
|
|
419
|
+
ruleTextSet: /* @__PURE__ */ new Set(),
|
|
420
|
+
metrics,
|
|
421
|
+
keyframesCache: /* @__PURE__ */ new Map(),
|
|
422
|
+
keyframesNameToContent: /* @__PURE__ */ new Map(),
|
|
423
|
+
keyframesCounter: 0,
|
|
424
|
+
injectedProperties: /* @__PURE__ */ new Map(),
|
|
425
|
+
injectedFontFaces: /* @__PURE__ */ new Set(),
|
|
426
|
+
injectedCounterStyles: /* @__PURE__ */ new Map(),
|
|
427
|
+
injectedFunctions: /* @__PURE__ */ new Map(),
|
|
428
|
+
globalRules: /* @__PURE__ */ new Map(),
|
|
429
|
+
propertyTypeResolver: new PropertyTypeResolver(),
|
|
430
|
+
unusedSince: /* @__PURE__ */ new Map(),
|
|
431
|
+
localKeyframes: /* @__PURE__ */ new Map(),
|
|
432
|
+
touchCount: 0,
|
|
433
|
+
serverClassSyncIndex: 0,
|
|
434
|
+
rscStylesScanned: false,
|
|
435
|
+
injectionMode: this.detectInjectionMode(root)
|
|
436
|
+
};
|
|
437
|
+
this.rootRegistries.set(root, registry);
|
|
438
|
+
this.activeRoots.add(root);
|
|
439
|
+
}
|
|
440
|
+
return registry;
|
|
441
|
+
}
|
|
442
|
+
/** Return all roots with active registries (for background GC sweep). */
|
|
443
|
+
getActiveRoots() {
|
|
444
|
+
return this.activeRoots;
|
|
445
|
+
}
|
|
446
|
+
/** Check whether any roots have active registries. */
|
|
447
|
+
hasActiveRoots() {
|
|
448
|
+
return this.activeRoots.size > 0;
|
|
449
|
+
}
|
|
450
|
+
/** Remove registries for ShadowRoots whose host has been detached from the DOM. */
|
|
451
|
+
pruneDisconnectedRoots() {
|
|
452
|
+
const toPrune = [];
|
|
453
|
+
for (const root of this.activeRoots) if (root !== document && !root.host?.isConnected) toPrune.push(root);
|
|
454
|
+
for (const root of toPrune) this.cleanup(root);
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Create a new stylesheet for the registry.
|
|
458
|
+
* In adopted mode (ShadowRoot), creates a constructable CSSStyleSheet and
|
|
459
|
+
* pushes it to adoptedStyleSheets. Otherwise creates a <style> element.
|
|
460
|
+
*/
|
|
461
|
+
createSheet(registry, root) {
|
|
462
|
+
if (registry.injectionMode === "adopted") {
|
|
463
|
+
const constructableSheet = new CSSStyleSheet();
|
|
464
|
+
root.adoptedStyleSheets = [...root.adoptedStyleSheets, constructableSheet];
|
|
465
|
+
const sheetInfo = {
|
|
466
|
+
sheet: null,
|
|
467
|
+
constructableSheet,
|
|
468
|
+
ruleCount: 0,
|
|
469
|
+
holes: []
|
|
470
|
+
};
|
|
471
|
+
registry.sheets.push(sheetInfo);
|
|
472
|
+
return sheetInfo;
|
|
473
|
+
}
|
|
474
|
+
const sheet = this.createStyleElement(root);
|
|
475
|
+
const textMode = this.config.forceTextInjection === true || sheet.sheet == null;
|
|
476
|
+
const sheetInfo = {
|
|
477
|
+
sheet,
|
|
478
|
+
ruleCount: 0,
|
|
479
|
+
holes: [],
|
|
480
|
+
textMode,
|
|
481
|
+
...textMode ? { textRules: [] } : {}
|
|
482
|
+
};
|
|
483
|
+
registry.sheets.push(sheetInfo);
|
|
484
|
+
return sheetInfo;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Create a style element and append to document
|
|
488
|
+
*/
|
|
489
|
+
createStyleElement(root) {
|
|
490
|
+
const style = root.createElement?.("style") || document.createElement("style");
|
|
491
|
+
if (this.config.nonce) style.nonce = this.config.nonce;
|
|
492
|
+
style.setAttribute("data-tasty", "");
|
|
493
|
+
if ("head" in root && root.head) root.head.appendChild(style);
|
|
494
|
+
else if ("appendChild" in root) root.appendChild(style);
|
|
495
|
+
else document.head.appendChild(style);
|
|
496
|
+
if (!style.isConnected && !this.config.forceTextInjection) console.error("[Tasty] SheetManager: style element failed to connect to the DOM.", {
|
|
497
|
+
parentNode: style.parentNode?.nodeName,
|
|
498
|
+
isConnected: style.isConnected
|
|
499
|
+
});
|
|
500
|
+
return style;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Insert CSS rules as a single block
|
|
504
|
+
*/
|
|
505
|
+
insertRule(registry, flattenedRules, className, root) {
|
|
506
|
+
let targetSheet = this.findAvailableSheet(registry, root);
|
|
507
|
+
if (!targetSheet) targetSheet = this.createSheet(registry, root);
|
|
508
|
+
const sheetIndex = registry.sheets.indexOf(targetSheet);
|
|
509
|
+
try {
|
|
510
|
+
const groupedRules = [];
|
|
511
|
+
const groupMap = /* @__PURE__ */ new Map();
|
|
512
|
+
const atKey = (at) => at && at.length ? at.join("|") : "";
|
|
513
|
+
flattenedRules.forEach((r) => {
|
|
514
|
+
const key = `${atKey(r.atRules)}||${r.selector}||${r.startingStyle ? "1" : "0"}`;
|
|
515
|
+
const existing = groupMap.get(key);
|
|
516
|
+
if (existing) existing.declarations = existing.declarations ? `${existing.declarations} ${r.declarations}` : r.declarations;
|
|
517
|
+
else {
|
|
518
|
+
groupMap.set(key, {
|
|
519
|
+
idx: groupedRules.length,
|
|
520
|
+
selector: r.selector,
|
|
521
|
+
atRules: r.atRules,
|
|
522
|
+
startingStyle: r.startingStyle,
|
|
523
|
+
declarations: r.declarations
|
|
524
|
+
});
|
|
525
|
+
groupedRules.push({ ...r });
|
|
526
|
+
}
|
|
527
|
+
});
|
|
528
|
+
groupMap.forEach((val) => {
|
|
529
|
+
groupedRules[val.idx] = {
|
|
530
|
+
selector: val.selector,
|
|
531
|
+
atRules: val.atRules,
|
|
532
|
+
startingStyle: val.startingStyle,
|
|
533
|
+
declarations: val.declarations
|
|
534
|
+
};
|
|
535
|
+
});
|
|
536
|
+
const insertedRuleTexts = [];
|
|
537
|
+
const insertedIndices = [];
|
|
538
|
+
let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);
|
|
539
|
+
let firstInsertedIndex = null;
|
|
540
|
+
let lastInsertedIndex = null;
|
|
541
|
+
for (const rule of groupedRules) {
|
|
542
|
+
const declarations = rule.declarations;
|
|
543
|
+
const innerContent = rule.startingStyle ? `@starting-style { ${declarations} }` : declarations;
|
|
544
|
+
const baseRule = `${rule.selector} { ${innerContent} }`;
|
|
545
|
+
let fullRule = baseRule;
|
|
546
|
+
if (rule.atRules && rule.atRules.length > 0) fullRule = rule.atRules.reduce((css, atRule) => `${atRule} { ${css} }`, baseRule);
|
|
547
|
+
const styleElement = targetSheet.sheet;
|
|
548
|
+
const styleSheet = this.getCSSSheet(targetSheet);
|
|
549
|
+
if (!targetSheet.textMode && styleSheet) {
|
|
550
|
+
const maxIndex = styleSheet.cssRules.length;
|
|
551
|
+
const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);
|
|
552
|
+
const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);
|
|
553
|
+
const splitSelectorsSafely = (selectorList) => {
|
|
554
|
+
const parts = [];
|
|
555
|
+
let buf = "";
|
|
556
|
+
let depthSq = 0;
|
|
557
|
+
let depthPar = 0;
|
|
558
|
+
let inStr = "";
|
|
559
|
+
for (let i = 0; i < selectorList.length; i++) {
|
|
560
|
+
const ch = selectorList[i];
|
|
561
|
+
if (inStr) {
|
|
562
|
+
if (ch === inStr && selectorList[i - 1] !== "\\") inStr = "";
|
|
563
|
+
buf += ch;
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
if (ch === "\"" || ch === "'") {
|
|
567
|
+
inStr = ch;
|
|
568
|
+
buf += ch;
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
if (ch === "[") depthSq++;
|
|
572
|
+
else if (ch === "]") depthSq = Math.max(0, depthSq - 1);
|
|
573
|
+
else if (ch === "(") depthPar++;
|
|
574
|
+
else if (ch === ")") depthPar = Math.max(0, depthPar - 1);
|
|
575
|
+
if (ch === "," && depthSq === 0 && depthPar === 0) {
|
|
576
|
+
const part = buf.trim();
|
|
577
|
+
if (part) parts.push(part);
|
|
578
|
+
buf = "";
|
|
579
|
+
} else buf += ch;
|
|
580
|
+
}
|
|
581
|
+
const tail = buf.trim();
|
|
582
|
+
if (tail) parts.push(tail);
|
|
583
|
+
return parts;
|
|
584
|
+
};
|
|
585
|
+
try {
|
|
586
|
+
styleSheet.insertRule(fullRule, safeIndex);
|
|
587
|
+
targetSheet.ruleCount++;
|
|
588
|
+
insertedIndices.push(safeIndex);
|
|
589
|
+
if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;
|
|
590
|
+
lastInsertedIndex = safeIndex;
|
|
591
|
+
currentRuleIndex = safeIndex + 1;
|
|
592
|
+
} catch (e) {
|
|
593
|
+
const selectors = splitSelectorsSafely(rule.selector);
|
|
594
|
+
if (selectors.length > 1) {
|
|
595
|
+
let anyInserted = false;
|
|
596
|
+
for (const sel of selectors) {
|
|
597
|
+
const singleBase = `${sel} { ${declarations} }`;
|
|
598
|
+
let singleRule = singleBase;
|
|
599
|
+
if (rule.atRules && rule.atRules.length > 0) singleRule = rule.atRules.reduce((css, atRule) => `${atRule} { ${css} }`, singleBase);
|
|
600
|
+
try {
|
|
601
|
+
const maxIdx = styleSheet.cssRules.length;
|
|
602
|
+
const atomicIdx = this.findAvailableRuleIndex(targetSheet);
|
|
603
|
+
const idx = Math.min(Math.max(0, atomicIdx), maxIdx);
|
|
604
|
+
styleSheet.insertRule(singleRule, idx);
|
|
605
|
+
targetSheet.ruleCount++;
|
|
606
|
+
insertedIndices.push(idx);
|
|
607
|
+
if (firstInsertedIndex == null) firstInsertedIndex = idx;
|
|
608
|
+
lastInsertedIndex = idx;
|
|
609
|
+
currentRuleIndex = idx + 1;
|
|
610
|
+
anyInserted = true;
|
|
611
|
+
} catch (singleErr) {
|
|
612
|
+
console.warn("[Tasty] Browser rejected CSS rule:", singleRule, singleErr);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
if (!anyInserted) {}
|
|
616
|
+
} else if (!(fullRule.startsWith("@property ") && !this.engineSupportsAtProperty(registry, styleSheet))) console.warn("[Tasty] Browser rejected CSS rule:", fullRule, e);
|
|
617
|
+
}
|
|
618
|
+
} else if (styleElement) {
|
|
619
|
+
const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);
|
|
620
|
+
this.trackTextRule(targetSheet, atomicRuleIndex, fullRule);
|
|
621
|
+
styleElement.textContent = (styleElement.textContent || "") + "\n" + fullRule;
|
|
622
|
+
targetSheet.ruleCount++;
|
|
623
|
+
insertedIndices.push(atomicRuleIndex);
|
|
624
|
+
if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;
|
|
625
|
+
lastInsertedIndex = atomicRuleIndex;
|
|
626
|
+
currentRuleIndex = atomicRuleIndex + 1;
|
|
627
|
+
}
|
|
628
|
+
if (styleElement && !styleElement.parentNode && !this.config.forceTextInjection) console.error("[Tasty] SheetManager: style element is not attached to the DOM; rules will not apply.", {
|
|
629
|
+
className,
|
|
630
|
+
ruleIndex: currentRuleIndex
|
|
631
|
+
});
|
|
632
|
+
if (this.config.devMode) {
|
|
633
|
+
insertedRuleTexts.push(fullRule);
|
|
634
|
+
try {
|
|
635
|
+
registry.ruleTextSet.add(fullRule);
|
|
636
|
+
} catch {}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
if (insertedIndices.length === 0) return null;
|
|
640
|
+
return {
|
|
641
|
+
className,
|
|
642
|
+
ruleIndex: firstInsertedIndex ?? 0,
|
|
643
|
+
sheetIndex,
|
|
644
|
+
cssText: this.config.devMode ? insertedRuleTexts : void 0,
|
|
645
|
+
endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,
|
|
646
|
+
indices: insertedIndices
|
|
647
|
+
};
|
|
648
|
+
} catch (error) {
|
|
649
|
+
console.warn("[Tasty] Failed to insert CSS rules:", error, {
|
|
650
|
+
flattenedRules,
|
|
651
|
+
className
|
|
652
|
+
});
|
|
653
|
+
return null;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Insert global CSS rules
|
|
658
|
+
*/
|
|
659
|
+
insertGlobalRule(registry, flattenedRules, globalKey, root) {
|
|
660
|
+
const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);
|
|
661
|
+
if (ruleInfo) registry.globalRules.set(globalKey, ruleInfo);
|
|
662
|
+
return ruleInfo;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Delete a global CSS rule by key
|
|
666
|
+
*/
|
|
667
|
+
deleteGlobalRule(registry, globalKey) {
|
|
668
|
+
const ruleInfo = registry.globalRules.get(globalKey);
|
|
669
|
+
if (!ruleInfo) return;
|
|
670
|
+
this.deleteRule(registry, ruleInfo);
|
|
671
|
+
registry.globalRules.delete(globalKey);
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Adjust rule indices after deletion to account for shifting
|
|
675
|
+
*/
|
|
676
|
+
adjustIndicesAfterDeletion(registry, sheetIndex, startIdx, endIdx, deleteCount, deletedRuleInfo, deletedIndices) {
|
|
677
|
+
try {
|
|
678
|
+
const sortedDeleted = deletedIndices && deletedIndices.length > 0 ? [...deletedIndices].sort((a, b) => a - b) : null;
|
|
679
|
+
const countDeletedBefore = (sorted, idx) => {
|
|
680
|
+
let shift = 0;
|
|
681
|
+
for (const delIdx of sorted) if (delIdx < idx) shift++;
|
|
682
|
+
else break;
|
|
683
|
+
return shift;
|
|
684
|
+
};
|
|
685
|
+
const adjustRuleInfo = (info) => {
|
|
686
|
+
if (info === deletedRuleInfo) return;
|
|
687
|
+
if (info.sheetIndex !== sheetIndex) return;
|
|
688
|
+
if (!info.indices || info.indices.length === 0) return;
|
|
689
|
+
if (sortedDeleted) info.indices = info.indices.map((idx) => {
|
|
690
|
+
return idx - countDeletedBefore(sortedDeleted, idx);
|
|
691
|
+
});
|
|
692
|
+
else info.indices = info.indices.map((idx) => idx > endIdx ? Math.max(0, idx - deleteCount) : idx);
|
|
693
|
+
if (info.indices.length > 0) {
|
|
694
|
+
info.ruleIndex = Math.min(...info.indices);
|
|
695
|
+
info.endRuleIndex = Math.max(...info.indices);
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
for (const info of registry.rules.values()) adjustRuleInfo(info);
|
|
699
|
+
for (const info of registry.globalRules.values()) adjustRuleInfo(info);
|
|
700
|
+
for (const entry of registry.keyframesCache.values()) {
|
|
701
|
+
const ki = entry.info;
|
|
702
|
+
if (ki.sheetIndex !== sheetIndex) continue;
|
|
703
|
+
if (sortedDeleted) {
|
|
704
|
+
const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);
|
|
705
|
+
if (shift > 0) ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);
|
|
706
|
+
} else if (ki.ruleIndex > endIdx) ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);
|
|
707
|
+
}
|
|
708
|
+
} catch {}
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Delete a CSS rule from the sheet
|
|
712
|
+
*/
|
|
713
|
+
deleteRule(registry, ruleInfo) {
|
|
714
|
+
const sheet = registry.sheets[ruleInfo.sheetIndex];
|
|
715
|
+
if (!sheet) return;
|
|
716
|
+
try {
|
|
717
|
+
const texts = this.config.devMode && Array.isArray(ruleInfo.cssText) ? ruleInfo.cssText.slice() : [];
|
|
718
|
+
const styleSheet = this.getCSSSheet(sheet);
|
|
719
|
+
if (sheet.textMode) {
|
|
720
|
+
let targetIndices;
|
|
721
|
+
if (ruleInfo.indices && ruleInfo.indices.length > 0) targetIndices = ruleInfo.indices;
|
|
722
|
+
else {
|
|
723
|
+
const startIdx = Math.max(0, ruleInfo.ruleIndex);
|
|
724
|
+
const endIdx = Math.min((sheet.textRules?.length ?? 0) - 1, Number.isFinite(ruleInfo.endRuleIndex) ? ruleInfo.endRuleIndex : startIdx);
|
|
725
|
+
targetIndices = [];
|
|
726
|
+
for (let idx = startIdx; idx <= endIdx; idx++) targetIndices.push(idx);
|
|
727
|
+
}
|
|
728
|
+
const deletedIndices = this.deleteTextRules(sheet, targetIndices);
|
|
729
|
+
if (deletedIndices.length > 0) {
|
|
730
|
+
sheet.ruleCount = Math.max(0, sheet.ruleCount - deletedIndices.length);
|
|
731
|
+
this.adjustIndicesAfterDeletion(registry, ruleInfo.sheetIndex, Math.min(...deletedIndices), Math.max(...deletedIndices), deletedIndices.length, ruleInfo, deletedIndices);
|
|
732
|
+
}
|
|
733
|
+
} else if (styleSheet) {
|
|
734
|
+
const rules = styleSheet.cssRules;
|
|
735
|
+
if (ruleInfo.indices && ruleInfo.indices.length > 0) {
|
|
736
|
+
const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a);
|
|
737
|
+
const deletedIndices = [];
|
|
738
|
+
for (const idx of sortedIndices) if (idx >= 0 && idx < styleSheet.cssRules.length) try {
|
|
739
|
+
styleSheet.deleteRule(idx);
|
|
740
|
+
deletedIndices.push(idx);
|
|
741
|
+
} catch (e) {
|
|
742
|
+
console.warn(`[Tasty] Failed to delete rule at index ${idx}:`, e);
|
|
743
|
+
}
|
|
744
|
+
sheet.ruleCount = Math.max(0, sheet.ruleCount - deletedIndices.length);
|
|
745
|
+
if (deletedIndices.length > 0) this.adjustIndicesAfterDeletion(registry, ruleInfo.sheetIndex, Math.min(...deletedIndices), Math.max(...deletedIndices), deletedIndices.length, ruleInfo, deletedIndices);
|
|
746
|
+
} else {
|
|
747
|
+
const startIdx = Math.max(0, ruleInfo.ruleIndex);
|
|
748
|
+
const endIdx = Math.min(rules.length - 1, Number.isFinite(ruleInfo.endRuleIndex) ? ruleInfo.endRuleIndex : startIdx);
|
|
749
|
+
if (Number.isFinite(startIdx) && endIdx >= startIdx) {
|
|
750
|
+
const deleteCount = endIdx - startIdx + 1;
|
|
751
|
+
for (let idx = endIdx; idx >= startIdx; idx--) {
|
|
752
|
+
if (idx < 0 || idx >= styleSheet.cssRules.length) continue;
|
|
753
|
+
styleSheet.deleteRule(idx);
|
|
754
|
+
}
|
|
755
|
+
sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);
|
|
756
|
+
this.adjustIndicesAfterDeletion(registry, ruleInfo.sheetIndex, startIdx, endIdx, deleteCount, ruleInfo);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (this.config.devMode && texts.length) try {
|
|
761
|
+
for (const text of texts) registry.ruleTextSet.delete(text);
|
|
762
|
+
} catch {}
|
|
763
|
+
} catch (error) {
|
|
764
|
+
console.warn("[Tasty] Failed to delete CSS rule:", error);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Find a sheet with available space or return null
|
|
769
|
+
*/
|
|
770
|
+
findAvailableSheet(registry, _root) {
|
|
771
|
+
const maxRules = this.config.maxRulesPerSheet;
|
|
772
|
+
if (!maxRules) return registry.sheets[registry.sheets.length - 1] || null;
|
|
773
|
+
for (const sheet of registry.sheets) if (sheet.ruleCount < maxRules) return sheet;
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Find an available rule index in the sheet
|
|
778
|
+
*/
|
|
779
|
+
findAvailableRuleIndex(sheet) {
|
|
780
|
+
return sheet.ruleCount;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Probe whether the underlying CSS engine supports `@property` at-rules.
|
|
784
|
+
* Result is cached per registry on `registry.atPropertySupported`.
|
|
785
|
+
*
|
|
786
|
+
* The probe inserts and immediately deletes a minimal known-valid rule
|
|
787
|
+
* (`@property --__tasty_probe__ { syntax: "*"; inherits: true; }`).
|
|
788
|
+
* Engines that lack `@property` support (jsdom, happy-dom) reject any
|
|
789
|
+
* `@property` rule including this one, so a probe failure is a reliable
|
|
790
|
+
* signal that further `@property` rejections are environmental noise and
|
|
791
|
+
* not user-authored bugs.
|
|
792
|
+
*
|
|
793
|
+
* The probe is intentionally a separate operation from the user's failing
|
|
794
|
+
* insertion: we don't want to leak `--__tasty_probe__` into the sheet, so
|
|
795
|
+
* on success we delete the probe rule immediately, leaving `ruleCount`
|
|
796
|
+
* and `cssRules.length` unchanged.
|
|
797
|
+
*/
|
|
798
|
+
engineSupportsAtProperty(registry, styleSheet) {
|
|
799
|
+
if (registry.atPropertySupported !== void 0) return registry.atPropertySupported;
|
|
800
|
+
const probeRule = "@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }";
|
|
801
|
+
try {
|
|
802
|
+
const probeIdx = styleSheet.cssRules.length;
|
|
803
|
+
styleSheet.insertRule(probeRule, probeIdx);
|
|
804
|
+
try {
|
|
805
|
+
styleSheet.deleteRule(probeIdx);
|
|
806
|
+
} catch {}
|
|
807
|
+
registry.atPropertySupported = true;
|
|
808
|
+
} catch {
|
|
809
|
+
registry.atPropertySupported = false;
|
|
810
|
+
}
|
|
811
|
+
return registry.atPropertySupported;
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* Delete the given classes: their rules leave the sheets and every registry
|
|
815
|
+
* entry pointing at them is dropped.
|
|
816
|
+
*
|
|
817
|
+
* Deciding *what* is unused belongs to `StyleInjector.gc()`, which owns the
|
|
818
|
+
* DOM scan and the capacity policy. This only re-checks that each class is
|
|
819
|
+
* still safe to delete, and reports how many were.
|
|
820
|
+
*
|
|
821
|
+
* @returns Number of classes actually deleted.
|
|
822
|
+
*/
|
|
823
|
+
deleteClasses(registry, classNames) {
|
|
824
|
+
const cleanupStartTime = Date.now();
|
|
825
|
+
const selected = Array.from(classNames).map((className) => {
|
|
826
|
+
const ruleInfo = registry.rules.get(className);
|
|
827
|
+
return ruleInfo ? {
|
|
828
|
+
className,
|
|
829
|
+
ruleInfo
|
|
830
|
+
} : null;
|
|
831
|
+
}).filter((entry) => entry != null);
|
|
832
|
+
if (selected.length === 0) return 0;
|
|
833
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
834
|
+
let cleanedUpCount = 0;
|
|
835
|
+
let totalCssSize = 0;
|
|
836
|
+
let totalRulesDeleted = 0;
|
|
837
|
+
const rulesBySheet = /* @__PURE__ */ new Map();
|
|
838
|
+
for (const { className, ruleInfo } of selected) {
|
|
839
|
+
const sheetIndex = ruleInfo.sheetIndex;
|
|
840
|
+
if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {
|
|
841
|
+
const cssSize = ruleInfo.cssText.reduce((total, css) => total + css.length, 0);
|
|
842
|
+
totalCssSize += cssSize;
|
|
843
|
+
totalRulesDeleted += ruleInfo.cssText.length;
|
|
844
|
+
}
|
|
845
|
+
if (!rulesBySheet.has(sheetIndex)) rulesBySheet.set(sheetIndex, []);
|
|
846
|
+
rulesBySheet.get(sheetIndex).push({
|
|
847
|
+
className,
|
|
848
|
+
ruleInfo
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
for (const [_sheetIndex, rulesInSheet] of rulesBySheet) {
|
|
852
|
+
rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);
|
|
853
|
+
for (const { className, ruleInfo } of rulesInSheet) {
|
|
854
|
+
if ((registry.pinCounts.get(className) ?? 0) > 0) continue;
|
|
855
|
+
if (registry.rules.get(className) !== ruleInfo) continue;
|
|
856
|
+
const sheetInfo = registry.sheets[ruleInfo.sheetIndex];
|
|
857
|
+
if (!sheetInfo || !sheetInfo.sheet && !sheetInfo.constructableSheet) continue;
|
|
858
|
+
const styleSheet = this.getCSSSheet(sheetInfo);
|
|
859
|
+
if (!sheetInfo.textMode && !styleSheet) continue;
|
|
860
|
+
const maxRuleIndex = (sheetInfo.textMode ? sheetInfo.textRules?.length ?? 0 : styleSheet?.cssRules.length ?? 0) - 1;
|
|
861
|
+
const startIdx = ruleInfo.ruleIndex;
|
|
862
|
+
const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;
|
|
863
|
+
if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) continue;
|
|
864
|
+
this.deleteRule(registry, ruleInfo);
|
|
865
|
+
registry.rules.delete(className);
|
|
866
|
+
registry.pinCounts.delete(className);
|
|
867
|
+
registry.unusedSince.delete(className);
|
|
868
|
+
for (const [key, entry] of registry.localKeyframes) {
|
|
869
|
+
if (!entry.owners.delete(className)) continue;
|
|
870
|
+
if (entry.owners.size === 0) {
|
|
871
|
+
entry.dispose();
|
|
872
|
+
registry.localKeyframes.delete(key);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
deleted.add(className);
|
|
876
|
+
cleanedUpCount++;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
if (deleted.size > 0) {
|
|
880
|
+
for (const [key, mappedClassName] of registry.cacheKeyToClassName) if (deleted.has(mappedClassName)) registry.cacheKeyToClassName.delete(key);
|
|
881
|
+
}
|
|
882
|
+
if (registry.metrics) {
|
|
883
|
+
registry.metrics.bulkCleanups++;
|
|
884
|
+
registry.metrics.stylesCleanedUp += cleanedUpCount;
|
|
885
|
+
registry.metrics.cleanupHistory.push({
|
|
886
|
+
timestamp: cleanupStartTime,
|
|
887
|
+
classesDeleted: cleanedUpCount,
|
|
888
|
+
cssSize: totalCssSize,
|
|
889
|
+
rulesDeleted: totalRulesDeleted
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
return cleanedUpCount;
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Get total number of rules across all sheets
|
|
896
|
+
*/
|
|
897
|
+
getTotalRuleCount(registry) {
|
|
898
|
+
return registry.sheets.reduce((total, sheet) => total + sheet.ruleCount - sheet.holes.length, 0);
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* The CSS of one managed sheet, or `null` when it holds none this can read —
|
|
902
|
+
* an empty style element, or a sheet the engine refuses to hand over.
|
|
903
|
+
*/
|
|
904
|
+
readSheetCSS(sheetInfo) {
|
|
905
|
+
try {
|
|
906
|
+
if (sheetInfo.constructableSheet) return Array.from(sheetInfo.constructableSheet.cssRules).map((rule) => rule.cssText).join("\n");
|
|
907
|
+
if (sheetInfo.sheet) {
|
|
908
|
+
const styleElement = sheetInfo.sheet;
|
|
909
|
+
if (styleElement.textContent) return styleElement.textContent;
|
|
910
|
+
if (styleElement.sheet) return Array.from(styleElement.sheet.cssRules).map((rule) => rule.cssText).join("\n");
|
|
911
|
+
}
|
|
912
|
+
} catch (error) {
|
|
913
|
+
console.warn("[Tasty] Failed to read CSS from sheet:", error);
|
|
914
|
+
}
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Get CSS text from all sheets (for SSR)
|
|
919
|
+
*/
|
|
920
|
+
getCSSText(registry) {
|
|
921
|
+
const cssChunks = [];
|
|
922
|
+
for (const sheetInfo of registry.sheets) {
|
|
923
|
+
const css = this.readSheetCSS(sheetInfo);
|
|
924
|
+
if (css !== null) cssChunks.push(css);
|
|
925
|
+
}
|
|
926
|
+
return cssChunks.join("\n");
|
|
927
|
+
}
|
|
928
|
+
/**
|
|
929
|
+
* Get cache performance metrics
|
|
930
|
+
*/
|
|
931
|
+
getMetrics(registry) {
|
|
932
|
+
if (!registry.metrics) return null;
|
|
933
|
+
return {
|
|
934
|
+
...registry.metrics,
|
|
935
|
+
unusedHits: 0
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Reset cache performance metrics
|
|
940
|
+
*/
|
|
941
|
+
resetMetrics(registry) {
|
|
942
|
+
if (registry.metrics) registry.metrics = {
|
|
943
|
+
hits: 0,
|
|
944
|
+
misses: 0,
|
|
945
|
+
bulkCleanups: 0,
|
|
946
|
+
totalInsertions: 0,
|
|
947
|
+
totalUnused: 0,
|
|
948
|
+
stylesCleanedUp: 0,
|
|
949
|
+
cleanupHistory: [],
|
|
950
|
+
startTime: Date.now()
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* Convert keyframes steps to CSS string.
|
|
955
|
+
* Public so the SSR collector can format keyframes without DOM access.
|
|
956
|
+
* Returns both the CSS text and a combined declarations string for property type scanning.
|
|
957
|
+
*/
|
|
958
|
+
stepsToCSS(steps) {
|
|
959
|
+
const rules = [];
|
|
960
|
+
const allDeclarations = [];
|
|
961
|
+
for (const [key, value] of Object.entries(steps)) {
|
|
962
|
+
if (typeof value === "string") {
|
|
963
|
+
rules.push(`${key} { ${value.trim()} }`);
|
|
964
|
+
allDeclarations.push(value.trim());
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
const styleMap = value || {};
|
|
968
|
+
const styleNames = Object.keys(styleMap).sort();
|
|
969
|
+
const handlerQueue = [];
|
|
970
|
+
const seenHandlers = /* @__PURE__ */ new Set();
|
|
971
|
+
styleNames.forEach((styleName) => {
|
|
972
|
+
let handlers = STYLE_HANDLER_MAP[styleName];
|
|
973
|
+
if (!handlers) handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];
|
|
974
|
+
handlers.forEach((handler) => {
|
|
975
|
+
if (!seenHandlers.has(handler)) {
|
|
976
|
+
seenHandlers.add(handler);
|
|
977
|
+
handlerQueue.push(handler);
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
});
|
|
981
|
+
const declarationPairs = [];
|
|
982
|
+
handlerQueue.forEach((handler) => {
|
|
983
|
+
const result = handler(handler.__lookupStyles.reduce((acc, name) => {
|
|
984
|
+
const v = styleMap[name];
|
|
985
|
+
if (v !== void 0) acc[name] = v;
|
|
986
|
+
return acc;
|
|
987
|
+
}, {}));
|
|
988
|
+
if (!result) return;
|
|
989
|
+
(Array.isArray(result) ? result : [result]).forEach((cssMap) => {
|
|
990
|
+
if (!cssMap || typeof cssMap !== "object") return;
|
|
991
|
+
const { $: _$, ...props } = cssMap;
|
|
992
|
+
Object.entries(props).forEach(([prop, val]) => {
|
|
993
|
+
if (val == null || val === "") return;
|
|
994
|
+
if (Array.isArray(val)) val.forEach((v) => {
|
|
995
|
+
if (v != null && v !== "") declarationPairs.push({
|
|
996
|
+
prop,
|
|
997
|
+
value: String(v)
|
|
998
|
+
});
|
|
999
|
+
});
|
|
1000
|
+
else declarationPairs.push({
|
|
1001
|
+
prop,
|
|
1002
|
+
value: String(val)
|
|
1003
|
+
});
|
|
1004
|
+
});
|
|
1005
|
+
});
|
|
1006
|
+
});
|
|
1007
|
+
const declarations = declarationPairs.map((d) => `${d.prop}: ${d.value}`).join("; ");
|
|
1008
|
+
rules.push(`${key} { ${declarations.trim()} }`);
|
|
1009
|
+
allDeclarations.push(declarations);
|
|
1010
|
+
}
|
|
1011
|
+
return {
|
|
1012
|
+
css: rules.join(" "),
|
|
1013
|
+
declarations: allDeclarations.join("; ")
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Insert keyframes rule.
|
|
1018
|
+
* Returns the KeyframesInfo and the raw declarations string for property type scanning.
|
|
1019
|
+
*/
|
|
1020
|
+
insertKeyframes(registry, steps, name, root) {
|
|
1021
|
+
let targetSheet = this.findAvailableSheet(registry, root);
|
|
1022
|
+
if (!targetSheet) targetSheet = this.createSheet(registry, root);
|
|
1023
|
+
const ruleIndex = this.findAvailableRuleIndex(targetSheet);
|
|
1024
|
+
const sheetIndex = registry.sheets.indexOf(targetSheet);
|
|
1025
|
+
try {
|
|
1026
|
+
const { css: cssSteps, declarations } = this.stepsToCSS(steps);
|
|
1027
|
+
const fullRule = `@keyframes ${name} { ${cssSteps} }`;
|
|
1028
|
+
const styleSheet = this.getCSSSheet(targetSheet);
|
|
1029
|
+
if (!targetSheet.textMode && styleSheet) {
|
|
1030
|
+
const safeIndex = Math.min(Math.max(0, ruleIndex), styleSheet.cssRules.length);
|
|
1031
|
+
styleSheet.insertRule(fullRule, safeIndex);
|
|
1032
|
+
} else if (targetSheet.sheet) {
|
|
1033
|
+
this.trackTextRule(targetSheet, ruleIndex, fullRule);
|
|
1034
|
+
targetSheet.sheet.textContent = (targetSheet.sheet.textContent || "") + "\n" + fullRule;
|
|
1035
|
+
}
|
|
1036
|
+
targetSheet.ruleCount++;
|
|
1037
|
+
return {
|
|
1038
|
+
info: {
|
|
1039
|
+
name,
|
|
1040
|
+
ruleIndex,
|
|
1041
|
+
sheetIndex,
|
|
1042
|
+
cssText: this.config.devMode ? fullRule : void 0
|
|
1043
|
+
},
|
|
1044
|
+
declarations
|
|
1045
|
+
};
|
|
1046
|
+
} catch (error) {
|
|
1047
|
+
console.warn("[Tasty] Failed to insert keyframes:", error);
|
|
1048
|
+
return null;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Delete keyframes rule
|
|
1053
|
+
*/
|
|
1054
|
+
deleteKeyframes(registry, info) {
|
|
1055
|
+
const sheet = registry.sheets[info.sheetIndex];
|
|
1056
|
+
if (!sheet) return;
|
|
1057
|
+
try {
|
|
1058
|
+
const styleSheet = this.getCSSSheet(sheet);
|
|
1059
|
+
const adjustIndices = () => this.adjustIndicesAfterDeletion(registry, info.sheetIndex, info.ruleIndex, info.ruleIndex, 1, {
|
|
1060
|
+
className: "",
|
|
1061
|
+
ruleIndex: info.ruleIndex,
|
|
1062
|
+
sheetIndex: info.sheetIndex
|
|
1063
|
+
}, [info.ruleIndex]);
|
|
1064
|
+
if (sheet.textMode) {
|
|
1065
|
+
if (this.deleteTextRules(sheet, [info.ruleIndex]).length > 0) {
|
|
1066
|
+
sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);
|
|
1067
|
+
adjustIndices();
|
|
1068
|
+
}
|
|
1069
|
+
} else if (styleSheet) {
|
|
1070
|
+
if (info.ruleIndex >= 0 && info.ruleIndex < styleSheet.cssRules.length) {
|
|
1071
|
+
styleSheet.deleteRule(info.ruleIndex);
|
|
1072
|
+
sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);
|
|
1073
|
+
adjustIndices();
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
} catch (error) {
|
|
1077
|
+
console.warn("[Tasty] Failed to delete keyframes:", error);
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
/**
|
|
1081
|
+
* Clean up resources for a root
|
|
1082
|
+
*/
|
|
1083
|
+
cleanup(root) {
|
|
1084
|
+
const registry = this.rootRegistries.get(root);
|
|
1085
|
+
if (!registry) return;
|
|
1086
|
+
if (registry.injectionMode === "adopted") {
|
|
1087
|
+
const shadowRoot = root;
|
|
1088
|
+
const ownedSheets = /* @__PURE__ */ new Set();
|
|
1089
|
+
for (const sheetInfo of registry.sheets) if (sheetInfo.constructableSheet) ownedSheets.add(sheetInfo.constructableSheet);
|
|
1090
|
+
const rawSheet = this.rawConstructableSheets.get(shadowRoot);
|
|
1091
|
+
if (rawSheet) {
|
|
1092
|
+
ownedSheets.add(rawSheet);
|
|
1093
|
+
this.rawConstructableSheets.delete(shadowRoot);
|
|
1094
|
+
}
|
|
1095
|
+
if (ownedSheets.size > 0) shadowRoot.adoptedStyleSheets = shadowRoot.adoptedStyleSheets.filter((s) => !ownedSheets.has(s));
|
|
1096
|
+
} else {
|
|
1097
|
+
for (const sheet of registry.sheets) try {
|
|
1098
|
+
const styleElement = sheet.sheet;
|
|
1099
|
+
if (styleElement?.parentNode) styleElement.parentNode.removeChild(styleElement);
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
console.warn("[Tasty] Failed to cleanup sheet:", error);
|
|
1102
|
+
}
|
|
1103
|
+
const rawStyleElement = this.rawStyleElements.get(root);
|
|
1104
|
+
if (rawStyleElement?.parentNode) rawStyleElement.parentNode.removeChild(rawStyleElement);
|
|
1105
|
+
this.rawStyleElements.delete(root);
|
|
1106
|
+
}
|
|
1107
|
+
this.rootRegistries.delete(root);
|
|
1108
|
+
this.activeRoots.delete(root);
|
|
1109
|
+
this.rawCSSBlocks.delete(root);
|
|
1110
|
+
}
|
|
1111
|
+
/**
|
|
1112
|
+
* Check if a root uses adopted injection mode.
|
|
1113
|
+
*/
|
|
1114
|
+
isAdoptedMode(root) {
|
|
1115
|
+
const registry = this.rootRegistries.get(root);
|
|
1116
|
+
if (registry) return registry.injectionMode === "adopted";
|
|
1117
|
+
return this.detectInjectionMode(root) === "adopted";
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Get or create a constructable CSSStyleSheet for raw CSS in adopted mode.
|
|
1121
|
+
* The raw sheet is prepended to adoptedStyleSheets so it precedes tasty rules.
|
|
1122
|
+
*/
|
|
1123
|
+
getOrCreateRawAdoptedSheet(root) {
|
|
1124
|
+
let sheet = this.rawConstructableSheets.get(root);
|
|
1125
|
+
if (!sheet) {
|
|
1126
|
+
sheet = new CSSStyleSheet();
|
|
1127
|
+
root.adoptedStyleSheets = [sheet, ...root.adoptedStyleSheets];
|
|
1128
|
+
this.rawConstructableSheets.set(root, sheet);
|
|
1129
|
+
if (!this.rawCSSBlocks.has(root)) this.rawCSSBlocks.set(root, /* @__PURE__ */ new Map());
|
|
1130
|
+
}
|
|
1131
|
+
return sheet;
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Get or create a dedicated style element for raw CSS
|
|
1135
|
+
* Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts
|
|
1136
|
+
*/
|
|
1137
|
+
getOrCreateRawStyleElement(root) {
|
|
1138
|
+
let styleElement = this.rawStyleElements.get(root);
|
|
1139
|
+
if (!styleElement) {
|
|
1140
|
+
styleElement = root.createElement?.("style") || document.createElement("style");
|
|
1141
|
+
if (this.config.nonce) styleElement.nonce = this.config.nonce;
|
|
1142
|
+
styleElement.setAttribute("data-tasty-raw", "");
|
|
1143
|
+
if ("head" in root && root.head) root.head.appendChild(styleElement);
|
|
1144
|
+
else if ("appendChild" in root) root.appendChild(styleElement);
|
|
1145
|
+
else document.head.appendChild(styleElement);
|
|
1146
|
+
this.rawStyleElements.set(root, styleElement);
|
|
1147
|
+
this.rawCSSBlocks.set(root, /* @__PURE__ */ new Map());
|
|
1148
|
+
}
|
|
1149
|
+
return styleElement;
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Inject raw CSS text directly without parsing
|
|
1153
|
+
* Returns a dispose function to remove the injected CSS
|
|
1154
|
+
*/
|
|
1155
|
+
injectRawCSS(css, root) {
|
|
1156
|
+
if (!css.trim()) return { dispose: () => {} };
|
|
1157
|
+
const id = `raw_${this.rawCSSCounter++}`;
|
|
1158
|
+
if (this.isAdoptedMode(root)) {
|
|
1159
|
+
this.getOrCreateRawAdoptedSheet(root);
|
|
1160
|
+
const blocksMap = this.rawCSSBlocks.get(root);
|
|
1161
|
+
const info = {
|
|
1162
|
+
id,
|
|
1163
|
+
css,
|
|
1164
|
+
startOffset: 0,
|
|
1165
|
+
endOffset: css.length
|
|
1166
|
+
};
|
|
1167
|
+
blocksMap.set(id, info);
|
|
1168
|
+
this.rebuildRawAdoptedSheet(root);
|
|
1169
|
+
return { dispose: () => {
|
|
1170
|
+
this.disposeRawCSS(id, root);
|
|
1171
|
+
} };
|
|
1172
|
+
}
|
|
1173
|
+
const styleElement = this.getOrCreateRawStyleElement(root);
|
|
1174
|
+
const blocksMap = this.rawCSSBlocks.get(root);
|
|
1175
|
+
const currentContent = styleElement.textContent || "";
|
|
1176
|
+
const startOffset = currentContent.length;
|
|
1177
|
+
const cssWithNewline = (currentContent ? "\n" : "") + css;
|
|
1178
|
+
const endOffset = startOffset + cssWithNewline.length;
|
|
1179
|
+
styleElement.textContent = currentContent + cssWithNewline;
|
|
1180
|
+
const info = {
|
|
1181
|
+
id,
|
|
1182
|
+
css,
|
|
1183
|
+
startOffset,
|
|
1184
|
+
endOffset
|
|
1185
|
+
};
|
|
1186
|
+
blocksMap.set(id, info);
|
|
1187
|
+
return { dispose: () => {
|
|
1188
|
+
this.disposeRawCSS(id, root);
|
|
1189
|
+
} };
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Rebuild the raw CSS constructable sheet from all tracked blocks.
|
|
1193
|
+
*/
|
|
1194
|
+
rebuildRawAdoptedSheet(root) {
|
|
1195
|
+
const sheet = this.rawConstructableSheets.get(root);
|
|
1196
|
+
const blocksMap = this.rawCSSBlocks.get(root);
|
|
1197
|
+
if (!sheet || !blocksMap) return;
|
|
1198
|
+
if (blocksMap.size === 0) {
|
|
1199
|
+
sheet.replaceSync("");
|
|
1200
|
+
return;
|
|
1201
|
+
}
|
|
1202
|
+
const blocks = Array.from(blocksMap.values());
|
|
1203
|
+
blocks.sort((a, b) => a.startOffset - b.startOffset);
|
|
1204
|
+
const allCSS = blocks.map((b) => b.css).join("\n");
|
|
1205
|
+
sheet.replaceSync(allCSS);
|
|
1206
|
+
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Remove a raw CSS block by ID
|
|
1209
|
+
*/
|
|
1210
|
+
disposeRawCSS(id, root) {
|
|
1211
|
+
const blocksMap = this.rawCSSBlocks.get(root);
|
|
1212
|
+
if (!blocksMap) return;
|
|
1213
|
+
if (!blocksMap.get(id)) return;
|
|
1214
|
+
blocksMap.delete(id);
|
|
1215
|
+
if (this.isAdoptedMode(root)) {
|
|
1216
|
+
this.rebuildRawAdoptedSheet(root);
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
const styleElement = this.rawStyleElements.get(root);
|
|
1220
|
+
if (!styleElement) return;
|
|
1221
|
+
const remainingBlocks = Array.from(blocksMap.values());
|
|
1222
|
+
if (remainingBlocks.length === 0) styleElement.textContent = "";
|
|
1223
|
+
else {
|
|
1224
|
+
remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);
|
|
1225
|
+
styleElement.textContent = remainingBlocks.map((block) => block.css).join("\n");
|
|
1226
|
+
let offset = 0;
|
|
1227
|
+
for (const block of remainingBlocks) {
|
|
1228
|
+
block.startOffset = offset;
|
|
1229
|
+
block.endOffset = offset + block.css.length;
|
|
1230
|
+
offset = block.endOffset + 1;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Get the raw CSS content
|
|
1236
|
+
*/
|
|
1237
|
+
/**
|
|
1238
|
+
* The CSS this injector owns in `root`, one entry per sheet, in the order the
|
|
1239
|
+
* engine applies them.
|
|
1240
|
+
*
|
|
1241
|
+
* `getCSSText()` walks the managed sheets only, and raw CSS has its own —
|
|
1242
|
+
* which sits before, after, or *between* them depending on how it got there:
|
|
1243
|
+
* prepended to `adoptedStyleSheets`, or wherever in `<head>` the first raw
|
|
1244
|
+
* injection happened to land, with every managed sheet opened afterwards
|
|
1245
|
+
* following it. Reporting a fixed order would describe the opposite winner
|
|
1246
|
+
* from the live page whenever two rules of equal specificity meet, so the raw
|
|
1247
|
+
* sheet is spliced in at the position the DOM actually gives it.
|
|
1248
|
+
*/
|
|
1249
|
+
getOwnedCSSInOrder(registry, root) {
|
|
1250
|
+
const raw = this.getRawCSSText(root);
|
|
1251
|
+
const rawElement = this.isAdoptedMode(root) ? null : this.rawStyleElements.get(root);
|
|
1252
|
+
let rawIndex = raw && !rawElement ? 0 : -1;
|
|
1253
|
+
const chunks = [];
|
|
1254
|
+
for (const sheetInfo of registry.sheets) {
|
|
1255
|
+
const css = this.readSheetCSS(sheetInfo);
|
|
1256
|
+
if (css === null) continue;
|
|
1257
|
+
if (rawIndex < 0 && rawElement && sheetInfo.sheet && rawElement.compareDocumentPosition(sheetInfo.sheet) & Node.DOCUMENT_POSITION_FOLLOWING) rawIndex = chunks.length;
|
|
1258
|
+
chunks.push(css);
|
|
1259
|
+
}
|
|
1260
|
+
if (!raw) return chunks;
|
|
1261
|
+
chunks.splice(rawIndex < 0 ? chunks.length : rawIndex, 0, raw);
|
|
1262
|
+
return chunks;
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Top-level rules in the raw sheet.
|
|
1266
|
+
*
|
|
1267
|
+
* Read from the sheet the engine parsed, not from the text: a raw block is
|
|
1268
|
+
* one string but any number of rules, and one rule — `@keyframes`, `@media` —
|
|
1269
|
+
* can contain any number of blocks, so counting braces answers neither
|
|
1270
|
+
* question.
|
|
1271
|
+
*/
|
|
1272
|
+
getRawRuleCount(root) {
|
|
1273
|
+
const sheet = this.isAdoptedMode(root) ? this.rawConstructableSheets.get(root) : this.rawStyleElements.get(root)?.sheet;
|
|
1274
|
+
try {
|
|
1275
|
+
return sheet?.cssRules.length ?? 0;
|
|
1276
|
+
} catch {
|
|
1277
|
+
return 0;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
getRawCSSText(root) {
|
|
1281
|
+
if (this.isAdoptedMode(root)) {
|
|
1282
|
+
const blocksMap = this.rawCSSBlocks.get(root);
|
|
1283
|
+
if (!blocksMap || blocksMap.size === 0) return "";
|
|
1284
|
+
const blocks = Array.from(blocksMap.values());
|
|
1285
|
+
blocks.sort((a, b) => a.startOffset - b.startOffset);
|
|
1286
|
+
return blocks.map((b) => b.css).join("\n");
|
|
1287
|
+
}
|
|
1288
|
+
return this.rawStyleElements.get(root)?.textContent || "";
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
//#endregion
|
|
1292
|
+
//#region src/injector/injector.ts
|
|
1293
|
+
/**
|
|
1294
|
+
* How long a class is left alone after it was last known to be wanted.
|
|
1295
|
+
* Long enough that a render cannot plausibly still be waiting to commit one.
|
|
1296
|
+
*/
|
|
1297
|
+
const DEFAULT_GC_GRACE = 1e4;
|
|
1298
|
+
/** Dispose handle handed back for injections that took no pin. */
|
|
1299
|
+
const noop = () => {};
|
|
1300
|
+
/**
|
|
1301
|
+
* Placeholder `KeyframesInfo` for a cache entry reserved by a batched write and
|
|
1302
|
+
* not yet backed by a real rule. Only ever read through `entry.pending`, which
|
|
1303
|
+
* is checked before the info is used.
|
|
1304
|
+
*/
|
|
1305
|
+
const EMPTY_KEYFRAMES_INFO = {
|
|
1306
|
+
name: "",
|
|
1307
|
+
ruleIndex: -3,
|
|
1308
|
+
sheetIndex: -3
|
|
1309
|
+
};
|
|
1310
|
+
/**
|
|
1311
|
+
* Extract class names from `<style data-tasty-rsc>` tags.
|
|
1312
|
+
* The doubled-specificity pattern `.tXXX.tXXX` makes extraction reliable.
|
|
1313
|
+
*/
|
|
1314
|
+
function extractRSCClassNames(rscClassRegex) {
|
|
1315
|
+
if (typeof document === "undefined") return [];
|
|
1316
|
+
const styles = document.querySelectorAll("style[data-tasty-rsc]");
|
|
1317
|
+
if (styles.length === 0) return [];
|
|
1318
|
+
const classSet = /* @__PURE__ */ new Set();
|
|
1319
|
+
for (const style of styles) {
|
|
1320
|
+
const text = style.textContent;
|
|
1321
|
+
if (!text) continue;
|
|
1322
|
+
let match;
|
|
1323
|
+
rscClassRegex.lastIndex = 0;
|
|
1324
|
+
while ((match = rscClassRegex.exec(text)) !== null) classSet.add(match[1]);
|
|
1325
|
+
}
|
|
1326
|
+
return Array.from(classSet);
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Lazily sync server-rendered class names into the client registry.
|
|
1330
|
+
*
|
|
1331
|
+
* Sources:
|
|
1332
|
+
* 1. `window.__TASTY__` — pushed by SSR/RSC streaming scripts
|
|
1333
|
+
* 2. `<style data-tasty-rsc>` tags — inline CSS emitted by RSC components
|
|
1334
|
+
*
|
|
1335
|
+
* Called inside `inject()` / `allocateClassName()` to pick up
|
|
1336
|
+
* class names rendered on the server (including during SPA navigation).
|
|
1337
|
+
*/
|
|
1338
|
+
function syncServerClasses(registry, rscClassRegex) {
|
|
1339
|
+
if (typeof window === "undefined") return;
|
|
1340
|
+
const classes = window.__TASTY__;
|
|
1341
|
+
if (classes && classes.length > registry.serverClassSyncIndex) {
|
|
1342
|
+
for (let i = registry.serverClassSyncIndex; i < classes.length; i++) registerHydratedClass(registry, classes[i]);
|
|
1343
|
+
registry.serverClassSyncIndex = classes.length;
|
|
1344
|
+
}
|
|
1345
|
+
if (!registry.rscStylesScanned) {
|
|
1346
|
+
registry.rscStylesScanned = true;
|
|
1347
|
+
for (const cls of extractRSCClassNames(rscClassRegex)) registerHydratedClass(registry, cls);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
function registerHydratedClass(registry, className) {
|
|
1351
|
+
if (registry.rules.has(className)) return;
|
|
1352
|
+
registry.rules.set(className, {
|
|
1353
|
+
className,
|
|
1354
|
+
ruleIndex: -2,
|
|
1355
|
+
sheetIndex: -2
|
|
1356
|
+
});
|
|
1357
|
+
registry.pinCounts.set(className, 0);
|
|
1358
|
+
}
|
|
1359
|
+
var StyleInjector = class {
|
|
1360
|
+
sheetManager;
|
|
1361
|
+
config;
|
|
1362
|
+
globalRuleCounter = 0;
|
|
1363
|
+
/** Cancels the scheduled sweep, whichever timer scheduled it. */
|
|
1364
|
+
cancelPendingGC = null;
|
|
1365
|
+
namePrefix;
|
|
1366
|
+
classRegex;
|
|
1367
|
+
rscClassRegex;
|
|
1368
|
+
/** @internal — exposed for debug utilities only */
|
|
1369
|
+
get _sheetManager() {
|
|
1370
|
+
return this.sheetManager;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* Whether sheet writes should be queued instead of applied immediately.
|
|
1374
|
+
*
|
|
1375
|
+
* Only ever true on the client: SSR collects CSS as text and the RSC path
|
|
1376
|
+
* returns it as strings, so neither has a live sheet to batch writes against.
|
|
1377
|
+
*
|
|
1378
|
+
* In the default `true` mode a write is only queued inside an open batch
|
|
1379
|
+
* window — a commit in which `<TastyBatchProvider>` rendered and will
|
|
1380
|
+
* therefore flush in its insertion effect, before any layout effect can
|
|
1381
|
+
* measure. Everything else falls through to a synchronous write, so enabling
|
|
1382
|
+
* the flag cannot make a `useLayoutEffect` read an unstyled element.
|
|
1383
|
+
* `'always'` drops the gate and accepts that trade for wider coverage.
|
|
1384
|
+
*/
|
|
1385
|
+
get batching() {
|
|
1386
|
+
const mode = this.config.batchInjection;
|
|
1387
|
+
if (!mode || typeof document === "undefined") return false;
|
|
1388
|
+
if (mode === "always") return true;
|
|
1389
|
+
if (isBatchWindowOpen()) return true;
|
|
1390
|
+
warnBatchProviderMissing();
|
|
1391
|
+
return false;
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* Apply a sheet write now, or queue it when batching is on.
|
|
1395
|
+
* Returns the queue handle when deferred, so the caller can cancel it if it
|
|
1396
|
+
* disposes before the flush.
|
|
1397
|
+
*/
|
|
1398
|
+
writeSheet(task) {
|
|
1399
|
+
if (this.batching) return enqueueStyleWrite(task);
|
|
1400
|
+
task();
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Insert a global (non-class) rule, honouring batching.
|
|
1405
|
+
*
|
|
1406
|
+
* `onApplied` records the caller's dedupe bookkeeping. When the write is
|
|
1407
|
+
* queued it runs eagerly, so a repeat call before the flush bails out instead
|
|
1408
|
+
* of queueing the same rule twice — the same reasoning as
|
|
1409
|
+
* `insertPropertyRule`'s eager marking. When written synchronously it runs
|
|
1410
|
+
* only on success, preserving the existing retry-on-failure behaviour.
|
|
1411
|
+
*/
|
|
1412
|
+
writeGlobalRule(registry, rules, key, root, onApplied) {
|
|
1413
|
+
if (this.batching) {
|
|
1414
|
+
onApplied?.();
|
|
1415
|
+
enqueueStyleWrite(() => {
|
|
1416
|
+
this.sheetManager.insertGlobalRule(registry, rules, key, root);
|
|
1417
|
+
});
|
|
1418
|
+
return;
|
|
1419
|
+
}
|
|
1420
|
+
if (this.sheetManager.insertGlobalRule(registry, rules, key, root)) onApplied?.();
|
|
1421
|
+
}
|
|
1422
|
+
constructor(config = {}) {
|
|
1423
|
+
if (config.namePrefix !== void 0) validateNamePrefix(config.namePrefix);
|
|
1424
|
+
this.config = config;
|
|
1425
|
+
this.sheetManager = new SheetManager(config);
|
|
1426
|
+
this.namePrefix = config.namePrefix ?? "t";
|
|
1427
|
+
this.classRegex = tastyClassRegex(this.namePrefix);
|
|
1428
|
+
this.rscClassRegex = rscClassRegexGlobal(this.namePrefix);
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Generate a deterministic class name from a cache key using content hash.
|
|
1432
|
+
* The same cache key always produces the same class name across environments
|
|
1433
|
+
* with the same `namePrefix`.
|
|
1434
|
+
*/
|
|
1435
|
+
generateClassName(cacheKey) {
|
|
1436
|
+
return makeClassName(this.namePrefix, hashString(cacheKey));
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Check if `className` was hydrated from server-rendered styles and,
|
|
1440
|
+
* if so, wire the cacheKey mapping. Returns true on hit.
|
|
1441
|
+
*/
|
|
1442
|
+
tryHydratedHit(registry, cacheKey, className) {
|
|
1443
|
+
syncServerClasses(registry, this.rscClassRegex);
|
|
1444
|
+
const rule = registry.rules.get(className);
|
|
1445
|
+
if (rule && rule.ruleIndex === -2 && rule.sheetIndex === -2) {
|
|
1446
|
+
registry.cacheKeyToClassName.set(cacheKey, className);
|
|
1447
|
+
return true;
|
|
1448
|
+
}
|
|
1449
|
+
return false;
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Allocate a className for a cacheKey without injecting styles yet.
|
|
1453
|
+
* This allows separating className allocation (render phase) from style injection (insertion phase).
|
|
1454
|
+
*/
|
|
1455
|
+
allocateClassName(cacheKey, options) {
|
|
1456
|
+
const root = options?.root || document;
|
|
1457
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1458
|
+
if (registry.cacheKeyToClassName.has(cacheKey)) return {
|
|
1459
|
+
className: registry.cacheKeyToClassName.get(cacheKey),
|
|
1460
|
+
isNewAllocation: false
|
|
1461
|
+
};
|
|
1462
|
+
const className = this.generateClassName(cacheKey);
|
|
1463
|
+
if (this.tryHydratedHit(registry, cacheKey, className)) return {
|
|
1464
|
+
className,
|
|
1465
|
+
isNewAllocation: false
|
|
1466
|
+
};
|
|
1467
|
+
if (registry.rules.get(className)) {
|
|
1468
|
+
if (isDevEnv()) console.warn(`[Tasty] Hash collision: cache keys produce the same class "${className}". Styles may be incorrect.`);
|
|
1469
|
+
registry.cacheKeyToClassName.set(cacheKey, className);
|
|
1470
|
+
return {
|
|
1471
|
+
className,
|
|
1472
|
+
isNewAllocation: false
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
const placeholderRuleInfo = {
|
|
1476
|
+
className,
|
|
1477
|
+
ruleIndex: -1,
|
|
1478
|
+
sheetIndex: -1
|
|
1479
|
+
};
|
|
1480
|
+
registry.rules.set(className, placeholderRuleInfo);
|
|
1481
|
+
registry.cacheKeyToClassName.set(cacheKey, className);
|
|
1482
|
+
return {
|
|
1483
|
+
className,
|
|
1484
|
+
isNewAllocation: true
|
|
1485
|
+
};
|
|
1486
|
+
}
|
|
1487
|
+
/**
|
|
1488
|
+
* Inject styles from StyleResult objects
|
|
1489
|
+
*/
|
|
1490
|
+
inject(rules, options) {
|
|
1491
|
+
const root = options?.root || document;
|
|
1492
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1493
|
+
const pin = options?.pin ?? true;
|
|
1494
|
+
if (rules.length === 0) return {
|
|
1495
|
+
className: "",
|
|
1496
|
+
dispose: () => {}
|
|
1497
|
+
};
|
|
1498
|
+
const cacheKey = options?.cacheKey;
|
|
1499
|
+
let className;
|
|
1500
|
+
if (cacheKey && registry.cacheKeyToClassName.has(cacheKey)) {
|
|
1501
|
+
className = registry.cacheKeyToClassName.get(cacheKey);
|
|
1502
|
+
const existingRuleInfo = registry.rules.get(className);
|
|
1503
|
+
if (existingRuleInfo.ruleIndex === -3) {
|
|
1504
|
+
registry.unusedSince.delete(className);
|
|
1505
|
+
if (pin) registry.pinCounts.set(className, (registry.pinCounts.get(className) || 0) + 1);
|
|
1506
|
+
if (registry.metrics) registry.metrics.hits++;
|
|
1507
|
+
return {
|
|
1508
|
+
className,
|
|
1509
|
+
dispose: pin ? () => this.unpin(className, registry) : noop
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
if (!(existingRuleInfo.ruleIndex === -1 && existingRuleInfo.sheetIndex === -1)) {
|
|
1513
|
+
registry.unusedSince.delete(className);
|
|
1514
|
+
if (pin) {
|
|
1515
|
+
const pins = registry.pinCounts.get(className) || 0;
|
|
1516
|
+
registry.pinCounts.set(className, pins + 1);
|
|
1517
|
+
}
|
|
1518
|
+
if (registry.metrics) registry.metrics.hits++;
|
|
1519
|
+
return {
|
|
1520
|
+
className,
|
|
1521
|
+
dispose: pin ? () => this.unpin(className, registry) : noop
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
} else if (cacheKey) {
|
|
1525
|
+
className = this.generateClassName(cacheKey);
|
|
1526
|
+
if (this.tryHydratedHit(registry, cacheKey, className)) {
|
|
1527
|
+
if (pin) registry.pinCounts.set(className, (registry.pinCounts.get(className) || 0) + 1);
|
|
1528
|
+
if (registry.metrics) registry.metrics.hits++;
|
|
1529
|
+
return {
|
|
1530
|
+
className,
|
|
1531
|
+
dispose: pin ? () => this.unpin(className, registry) : noop
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
} else {
|
|
1535
|
+
const parts = rules.map((r) => `${r.selector}\0${r.declarations}`);
|
|
1536
|
+
className = makeClassName(this.namePrefix, hashString(parts.join("\n")));
|
|
1537
|
+
}
|
|
1538
|
+
const rulesToInsert = rules.map((rule) => {
|
|
1539
|
+
let newSelector = rule.selector;
|
|
1540
|
+
if (rule.needsClassName) {
|
|
1541
|
+
const selectorParts = newSelector ? newSelector.split("|||") : [""];
|
|
1542
|
+
const classPrefix = `.${className}.${className}`;
|
|
1543
|
+
newSelector = selectorParts.map((part) => {
|
|
1544
|
+
const classSelector = part ? `${classPrefix}${part}` : classPrefix;
|
|
1545
|
+
if (rule.rootPrefix) return `${rule.rootPrefix} ${classSelector}`;
|
|
1546
|
+
return classSelector;
|
|
1547
|
+
}).join(", ");
|
|
1548
|
+
}
|
|
1549
|
+
return {
|
|
1550
|
+
...rule,
|
|
1551
|
+
selector: newSelector,
|
|
1552
|
+
needsClassName: void 0,
|
|
1553
|
+
rootPrefix: void 0
|
|
1554
|
+
};
|
|
1555
|
+
});
|
|
1556
|
+
const applySheetWrite = () => {
|
|
1557
|
+
if (this.config.autoPropertyTypes !== false) {
|
|
1558
|
+
const resolver = registry.propertyTypeResolver;
|
|
1559
|
+
const defined = registry.injectedProperties;
|
|
1560
|
+
for (const rule of rulesToInsert) {
|
|
1561
|
+
if (!rule.declarations) continue;
|
|
1562
|
+
resolver.scanDeclarations(rule.declarations, (name) => defined.has(name), (name, syntax, initialValue) => {
|
|
1563
|
+
this.property(name, {
|
|
1564
|
+
syntax,
|
|
1565
|
+
inherits: true,
|
|
1566
|
+
initialValue,
|
|
1567
|
+
root
|
|
1568
|
+
});
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
const ruleInfo = this.sheetManager.insertRule(registry, rulesToInsert, className, root);
|
|
1573
|
+
if (!ruleInfo) {
|
|
1574
|
+
if (registry.metrics) registry.metrics.misses++;
|
|
1575
|
+
return null;
|
|
1576
|
+
}
|
|
1577
|
+
registry.rules.set(className, ruleInfo);
|
|
1578
|
+
if (cacheKey) registry.cacheKeyToClassName.set(cacheKey, className);
|
|
1579
|
+
if (registry.metrics) {
|
|
1580
|
+
registry.metrics.totalInsertions++;
|
|
1581
|
+
registry.metrics.misses++;
|
|
1582
|
+
}
|
|
1583
|
+
return ruleInfo;
|
|
1584
|
+
};
|
|
1585
|
+
if (this.batching) {
|
|
1586
|
+
registry.rules.set(className, {
|
|
1587
|
+
className,
|
|
1588
|
+
ruleIndex: -3,
|
|
1589
|
+
sheetIndex: -3
|
|
1590
|
+
});
|
|
1591
|
+
if (cacheKey) registry.cacheKeyToClassName.set(cacheKey, className);
|
|
1592
|
+
if (pin) registry.pinCounts.set(className, 1);
|
|
1593
|
+
registry.unusedSince.set(className, Date.now());
|
|
1594
|
+
const queued = enqueueStyleWrite(() => {
|
|
1595
|
+
if (applySheetWrite()) return;
|
|
1596
|
+
registry.rules.set(className, {
|
|
1597
|
+
className,
|
|
1598
|
+
ruleIndex: -1,
|
|
1599
|
+
sheetIndex: -1
|
|
1600
|
+
});
|
|
1601
|
+
});
|
|
1602
|
+
return {
|
|
1603
|
+
className,
|
|
1604
|
+
dispose: pin ? () => {
|
|
1605
|
+
if (!queued.done && registry.pinCounts.get(className) === 1 && registry.rules.get(className)?.ruleIndex === -3) {
|
|
1606
|
+
queued.cancelled = true;
|
|
1607
|
+
registry.rules.delete(className);
|
|
1608
|
+
if (cacheKey) registry.cacheKeyToClassName.delete(cacheKey);
|
|
1609
|
+
registry.pinCounts.set(className, 0);
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
this.unpin(className, registry);
|
|
1613
|
+
} : noop
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
if (!applySheetWrite()) return {
|
|
1617
|
+
className,
|
|
1618
|
+
dispose: () => {}
|
|
1619
|
+
};
|
|
1620
|
+
if (pin) registry.pinCounts.set(className, 1);
|
|
1621
|
+
registry.unusedSince.set(className, Date.now());
|
|
1622
|
+
return {
|
|
1623
|
+
className,
|
|
1624
|
+
dispose: pin ? () => this.unpin(className, registry) : noop
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
/**
|
|
1628
|
+
* Inject global styles (rules without a generated tasty class selector)
|
|
1629
|
+
* This ensures we don't reserve a tasty class name (t{number}) for global rules,
|
|
1630
|
+
* which could otherwise collide with element-level styles and break lookups.
|
|
1631
|
+
*/
|
|
1632
|
+
injectGlobal(rules, options) {
|
|
1633
|
+
const root = options?.root || document;
|
|
1634
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1635
|
+
if (!rules || rules.length === 0) return { dispose: () => {} };
|
|
1636
|
+
const key = `global:${this.globalRuleCounter++}`;
|
|
1637
|
+
const applyWrite = () => {
|
|
1638
|
+
if (this.config.autoPropertyTypes !== false) {
|
|
1639
|
+
const resolver = registry.propertyTypeResolver;
|
|
1640
|
+
const defined = registry.injectedProperties;
|
|
1641
|
+
for (const rule of rules) {
|
|
1642
|
+
if (!rule.declarations) continue;
|
|
1643
|
+
resolver.scanDeclarations(rule.declarations, (name) => defined.has(name), (name, syntax, initialValue) => {
|
|
1644
|
+
this.property(name, {
|
|
1645
|
+
syntax,
|
|
1646
|
+
inherits: true,
|
|
1647
|
+
initialValue,
|
|
1648
|
+
root
|
|
1649
|
+
});
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
const inserted = this.sheetManager.insertGlobalRule(registry, rules, key, root);
|
|
1654
|
+
if (registry.metrics) registry.metrics.totalInsertions++;
|
|
1655
|
+
return inserted;
|
|
1656
|
+
};
|
|
1657
|
+
if (this.batching) {
|
|
1658
|
+
let info = null;
|
|
1659
|
+
const queued = enqueueStyleWrite(() => {
|
|
1660
|
+
info = applyWrite();
|
|
1661
|
+
});
|
|
1662
|
+
return { dispose: () => {
|
|
1663
|
+
if (!queued.done) {
|
|
1664
|
+
queued.cancelled = true;
|
|
1665
|
+
return;
|
|
1666
|
+
}
|
|
1667
|
+
if (info) this.sheetManager.deleteGlobalRule(registry, key);
|
|
1668
|
+
} };
|
|
1669
|
+
}
|
|
1670
|
+
const info = applyWrite();
|
|
1671
|
+
return { dispose: () => {
|
|
1672
|
+
if (info) this.sheetManager.deleteGlobalRule(registry, key);
|
|
1673
|
+
} };
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Inject raw CSS text directly without parsing
|
|
1677
|
+
* This is a low-overhead alternative to createGlobalStyle for raw CSS
|
|
1678
|
+
* The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking
|
|
1679
|
+
*/
|
|
1680
|
+
injectRawCSS(css, options) {
|
|
1681
|
+
const root = options?.root || document;
|
|
1682
|
+
if (!this.batching) return this.sheetManager.injectRawCSS(css, root);
|
|
1683
|
+
let result = null;
|
|
1684
|
+
const queued = enqueueStyleWrite(() => {
|
|
1685
|
+
result = this.sheetManager.injectRawCSS(css, root);
|
|
1686
|
+
});
|
|
1687
|
+
return { dispose: () => {
|
|
1688
|
+
if (!queued.done) {
|
|
1689
|
+
queued.cancelled = true;
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
result?.dispose();
|
|
1693
|
+
} };
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Get raw CSS text for SSR
|
|
1697
|
+
*/
|
|
1698
|
+
getRawCSSText(options) {
|
|
1699
|
+
flushStyles();
|
|
1700
|
+
const root = options?.root || document;
|
|
1701
|
+
return this.sheetManager.getRawCSSText(root);
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Take a reference on local `@keyframes`, under the deterministic names the
|
|
1705
|
+
* caller resolved.
|
|
1706
|
+
*
|
|
1707
|
+
* One reference per distinct set of steps, shared by every class that ends up
|
|
1708
|
+
* animating it, so a repeat render takes nothing further. Ownership is
|
|
1709
|
+
* assigned by `ownKeyframes()` once the rules exist to be inspected.
|
|
1710
|
+
*/
|
|
1711
|
+
holdKeyframes(steps, names, options) {
|
|
1712
|
+
const root = options?.root || document;
|
|
1713
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1714
|
+
const keys = /* @__PURE__ */ new Map();
|
|
1715
|
+
for (const [authored, definition] of Object.entries(steps)) {
|
|
1716
|
+
const resolved = names.get(authored) ?? authored;
|
|
1717
|
+
let entry = registry.localKeyframes.get(resolved);
|
|
1718
|
+
if (!entry) {
|
|
1719
|
+
const injected = this.keyframes(definition, {
|
|
1720
|
+
name: resolved,
|
|
1721
|
+
root,
|
|
1722
|
+
distinctByName: true
|
|
1723
|
+
});
|
|
1724
|
+
entry = {
|
|
1725
|
+
name: injected.toString(),
|
|
1726
|
+
dispose: injected.dispose,
|
|
1727
|
+
owners: /* @__PURE__ */ new Set()
|
|
1728
|
+
};
|
|
1729
|
+
registry.localKeyframes.set(resolved, entry);
|
|
1730
|
+
}
|
|
1731
|
+
keys.set(authored, resolved);
|
|
1732
|
+
}
|
|
1733
|
+
return keys;
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Record that `className` animates these keyframes, so the reference is
|
|
1737
|
+
* released when the last such class is collected.
|
|
1738
|
+
*
|
|
1739
|
+
* Only classes whose rules actually reference the animation should be here:
|
|
1740
|
+
* a class that merely rendered alongside one would otherwise keep the
|
|
1741
|
+
* keyframes alive for as long as it lives.
|
|
1742
|
+
*/
|
|
1743
|
+
ownKeyframes(key, className, options) {
|
|
1744
|
+
this.sheetManager.getRegistry(options?.root || document).localKeyframes.get(key)?.owners.add(className);
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Pin an already-injected cacheKey and return the handle that releases it.
|
|
1748
|
+
* For callers that skipped the pipeline on a cache hit but still need the
|
|
1749
|
+
* class held. Returns null if the cacheKey is not found.
|
|
1750
|
+
*/
|
|
1751
|
+
trackRef(cacheKey, options) {
|
|
1752
|
+
const root = options?.root || document;
|
|
1753
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1754
|
+
if (!registry.cacheKeyToClassName.has(cacheKey)) return null;
|
|
1755
|
+
const className = registry.cacheKeyToClassName.get(cacheKey);
|
|
1756
|
+
const pins = registry.pinCounts.get(className) || 0;
|
|
1757
|
+
registry.pinCounts.set(className, pins + 1);
|
|
1758
|
+
if (registry.metrics) registry.metrics.hits++;
|
|
1759
|
+
return {
|
|
1760
|
+
className,
|
|
1761
|
+
dispose: () => this.unpin(className, registry)
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Release one pin on a className. At zero pins the class is not deleted — it
|
|
1766
|
+
* stays cached and collectible, and `gc()` decides when it actually goes.
|
|
1767
|
+
*/
|
|
1768
|
+
unpin(className, registry) {
|
|
1769
|
+
const pins = registry.pinCounts.get(className);
|
|
1770
|
+
if (pins == null || pins <= 0) return;
|
|
1771
|
+
const remaining = pins - 1;
|
|
1772
|
+
registry.pinCounts.set(className, remaining);
|
|
1773
|
+
if (remaining === 0 && registry.metrics) registry.metrics.totalUnused++;
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Remove every style that is neither in the DOM nor referenced by an
|
|
1777
|
+
* outstanding `inject()` handle, ignoring the GC capacity threshold.
|
|
1778
|
+
*/
|
|
1779
|
+
cleanup(root) {
|
|
1780
|
+
this.gc({
|
|
1781
|
+
root,
|
|
1782
|
+
force: true
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
/**
|
|
1786
|
+
* Get CSS text from all sheets (for SSR)
|
|
1787
|
+
*/
|
|
1788
|
+
getCSSText(options) {
|
|
1789
|
+
flushStyles();
|
|
1790
|
+
const root = options?.root || document;
|
|
1791
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1792
|
+
return this.sheetManager.getCSSText(registry);
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1795
|
+
* Get CSS only for the provided tasty classNames (e.g., ["t0","t3"])
|
|
1796
|
+
*/
|
|
1797
|
+
getCSSTextForClasses(classNames, options) {
|
|
1798
|
+
flushStyles();
|
|
1799
|
+
const root = options?.root || document;
|
|
1800
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1801
|
+
const cssChunks = [];
|
|
1802
|
+
for (const cls of classNames) {
|
|
1803
|
+
const info = registry.rules.get(cls);
|
|
1804
|
+
if (info) {
|
|
1805
|
+
const sheet = registry.sheets[info.sheetIndex];
|
|
1806
|
+
const styleSheet = sheet ? this.sheetManager.getCSSSheet(sheet) : null;
|
|
1807
|
+
if (styleSheet) {
|
|
1808
|
+
const start = Math.max(0, info.ruleIndex);
|
|
1809
|
+
const end = Math.min(styleSheet.cssRules.length - 1, info.endRuleIndex ?? info.ruleIndex);
|
|
1810
|
+
if (start >= 0 && end >= start && start < styleSheet.cssRules.length) for (let i = start; i <= end; i++) {
|
|
1811
|
+
const rule = styleSheet.cssRules[i];
|
|
1812
|
+
if (rule) cssChunks.push(rule.cssText);
|
|
1813
|
+
}
|
|
1814
|
+
} else if (info.cssText && info.cssText.length) cssChunks.push(...info.cssText);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
return cssChunks.join("\n");
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* Get cache performance metrics
|
|
1821
|
+
*/
|
|
1822
|
+
getMetrics(options) {
|
|
1823
|
+
flushStyles();
|
|
1824
|
+
const root = options?.root || document;
|
|
1825
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1826
|
+
const metrics = this.sheetManager.getMetrics(registry);
|
|
1827
|
+
if (metrics && typeof document !== "undefined") metrics.unusedHits = this.collectUnused(registry, root).length;
|
|
1828
|
+
return metrics;
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* Reset cache performance metrics
|
|
1832
|
+
*/
|
|
1833
|
+
resetMetrics(options) {
|
|
1834
|
+
const root = options?.root || document;
|
|
1835
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1836
|
+
this.sheetManager.resetMetrics(registry);
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Define a CSS @property custom property.
|
|
1840
|
+
*
|
|
1841
|
+
* Accepts tasty token syntax for the property name:
|
|
1842
|
+
* - `$name` → defines `--name`
|
|
1843
|
+
* - `#name` → defines `--name-color` (auto-sets syntax: '<color>', defaults initialValue: 'transparent')
|
|
1844
|
+
* - `--name` → defines `--name` (legacy format)
|
|
1845
|
+
*
|
|
1846
|
+
* Example:
|
|
1847
|
+
* @property --rotation { syntax: "<angle>"; inherits: false; initial-value: 45deg; }
|
|
1848
|
+
*
|
|
1849
|
+
* Note: No caching or dispose — this defines a global property.
|
|
1850
|
+
*
|
|
1851
|
+
* If the same property is registered with different options, a warning is emitted
|
|
1852
|
+
* but the original definition is preserved (CSS @property cannot be redefined).
|
|
1853
|
+
*/
|
|
1854
|
+
property(name, options) {
|
|
1855
|
+
const root = options?.root || document;
|
|
1856
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1857
|
+
const effectiveResult = getEffectiveDefinition(name, {
|
|
1858
|
+
syntax: options?.syntax,
|
|
1859
|
+
inherits: options?.inherits,
|
|
1860
|
+
initialValue: options?.initialValue
|
|
1861
|
+
});
|
|
1862
|
+
if (!effectiveResult.isValid) {
|
|
1863
|
+
if (isDevEnv()) console.warn(`[Tasty] property(): ${effectiveResult.error}. Got: "${name}"`);
|
|
1864
|
+
return;
|
|
1865
|
+
}
|
|
1866
|
+
const cssName = effectiveResult.cssName;
|
|
1867
|
+
const definition = effectiveResult.definition;
|
|
1868
|
+
this.insertPropertyRule(registry, root, cssName, definition, name);
|
|
1869
|
+
}
|
|
1870
|
+
/**
|
|
1871
|
+
* Build and insert a single `@property` rule into the given registry.
|
|
1872
|
+
* No-op if the property was already injected.
|
|
1873
|
+
*/
|
|
1874
|
+
insertPropertyRule(registry, root, cssName, definition, cacheKey) {
|
|
1875
|
+
if (registry.injectedProperties.has(cssName)) return;
|
|
1876
|
+
const parts = [];
|
|
1877
|
+
if (definition.syntax != null) {
|
|
1878
|
+
let syntax = String(definition.syntax).trim();
|
|
1879
|
+
if (!/^['"]/u.test(syntax)) syntax = `"${syntax}"`;
|
|
1880
|
+
parts.push(`syntax: ${syntax};`);
|
|
1881
|
+
}
|
|
1882
|
+
const inherits = definition.inherits ?? true;
|
|
1883
|
+
parts.push(`inherits: ${inherits ? "true" : "false"};`);
|
|
1884
|
+
if (definition.initialValue != null) {
|
|
1885
|
+
let initialValueStr;
|
|
1886
|
+
if (typeof definition.initialValue === "number") initialValueStr = String(definition.initialValue);
|
|
1887
|
+
else initialValueStr = parseStyle(definition.initialValue).output;
|
|
1888
|
+
parts.push(`initial-value: ${initialValueStr};`);
|
|
1889
|
+
}
|
|
1890
|
+
const declarations = parts.join(" ").trim();
|
|
1891
|
+
const rule = {
|
|
1892
|
+
selector: `@property ${cssName}`,
|
|
1893
|
+
declarations
|
|
1894
|
+
};
|
|
1895
|
+
registry.injectedProperties.set(cssName, normalizePropertyDefinition(definition));
|
|
1896
|
+
this.writeGlobalRule(registry, [rule], `property:${cacheKey}`, root);
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Check whether a given @property name was already injected by this injector.
|
|
1900
|
+
*
|
|
1901
|
+
* Accepts tasty token syntax:
|
|
1902
|
+
* - `$name` → checks `--name`
|
|
1903
|
+
* - `#name` → checks `--name-color`
|
|
1904
|
+
* - `--name` → checks `--name` (legacy format)
|
|
1905
|
+
*/
|
|
1906
|
+
isPropertyDefined(name, options) {
|
|
1907
|
+
flushStyles();
|
|
1908
|
+
const root = options?.root || document;
|
|
1909
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1910
|
+
const effectiveResult = getEffectiveDefinition(name, {});
|
|
1911
|
+
if (!effectiveResult.isValid) return false;
|
|
1912
|
+
return registry.injectedProperties.has(effectiveResult.cssName);
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Inject a CSS @font-face rule.
|
|
1916
|
+
*
|
|
1917
|
+
* Permanent and global — no dispose or ref-counting.
|
|
1918
|
+
* Deduplicates by content hash (family + descriptors).
|
|
1919
|
+
*/
|
|
1920
|
+
fontFace(family, descriptors, options) {
|
|
1921
|
+
const root = options?.root || document;
|
|
1922
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1923
|
+
const hash = fontFaceContentHash(family, descriptors);
|
|
1924
|
+
if (registry.injectedFontFaces.has(hash)) return;
|
|
1925
|
+
const rule = {
|
|
1926
|
+
selector: "@font-face",
|
|
1927
|
+
declarations: formatFontFaceDeclarations(family, descriptors)
|
|
1928
|
+
};
|
|
1929
|
+
this.writeGlobalRule(registry, [rule], `fontface:${hash}`, root, () => {
|
|
1930
|
+
registry.injectedFontFaces.add(hash);
|
|
1931
|
+
});
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Inject a CSS @counter-style rule.
|
|
1935
|
+
*
|
|
1936
|
+
* Permanent and global — no dispose or ref-counting. Deduplicates by name.
|
|
1937
|
+
* By default a definition overrides a previously injected one of the same
|
|
1938
|
+
* name. Pass `weak: true` for global `configure()` definitions, which must
|
|
1939
|
+
* never clobber an existing rule (so component-local definitions win
|
|
1940
|
+
* regardless of injection order).
|
|
1941
|
+
*/
|
|
1942
|
+
counterStyle(name, descriptors, options) {
|
|
1943
|
+
const root = options?.root || document;
|
|
1944
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1945
|
+
const isWeak = options?.weak === true;
|
|
1946
|
+
const existingIsStrong = registry.injectedCounterStyles.get(name);
|
|
1947
|
+
if (existingIsStrong !== void 0) {
|
|
1948
|
+
if (isWeak || existingIsStrong === true) return;
|
|
1949
|
+
this.writeSheet(() => {
|
|
1950
|
+
this.sheetManager.deleteGlobalRule(registry, `counterstyle:${name}`);
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
const rule = {
|
|
1954
|
+
selector: `@counter-style ${name}`,
|
|
1955
|
+
declarations: formatCounterStyleDeclarations(descriptors)
|
|
1956
|
+
};
|
|
1957
|
+
this.writeGlobalRule(registry, [rule], `counterstyle:${name}`, root, () => {
|
|
1958
|
+
registry.injectedCounterStyles.set(name, !isWeak);
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
/**
|
|
1962
|
+
* Inject a CSS @function rule (custom function).
|
|
1963
|
+
*
|
|
1964
|
+
* Permanent and global — no dispose or ref-counting. Deduplicates by function
|
|
1965
|
+
* name. By default a definition overrides a previously injected one of the
|
|
1966
|
+
* same name. Pass `weak: true` for global `configure()` definitions, which
|
|
1967
|
+
* must never clobber an existing rule (so component-local definitions win
|
|
1968
|
+
* regardless of injection order).
|
|
1969
|
+
*/
|
|
1970
|
+
func(name, definition, options) {
|
|
1971
|
+
const root = options?.root || document;
|
|
1972
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
1973
|
+
const isWeak = options?.weak === true;
|
|
1974
|
+
const cssName = parseFunctionName(name);
|
|
1975
|
+
const existingIsStrong = registry.injectedFunctions.get(cssName);
|
|
1976
|
+
if (existingIsStrong !== void 0) {
|
|
1977
|
+
if (isWeak || existingIsStrong === true) return;
|
|
1978
|
+
this.writeSheet(() => {
|
|
1979
|
+
this.sheetManager.deleteGlobalRule(registry, `function:${cssName}`);
|
|
1980
|
+
});
|
|
1981
|
+
}
|
|
1982
|
+
const rule = {
|
|
1983
|
+
selector: formatFunctionPrelude(name, definition.args, definition.returns),
|
|
1984
|
+
declarations: formatFunctionDeclarations(definition)
|
|
1985
|
+
};
|
|
1986
|
+
this.writeGlobalRule(registry, [rule], `function:${cssName}`, root, () => {
|
|
1987
|
+
registry.injectedFunctions.set(cssName, !isWeak);
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Inject keyframes and return object with toString() and dispose()
|
|
1992
|
+
*
|
|
1993
|
+
* Keyframes are cached by content (steps). If the same content is injected
|
|
1994
|
+
* multiple times with different provided names, the first injected name is reused.
|
|
1995
|
+
*
|
|
1996
|
+
* If the same name is provided with different content (collision), a unique
|
|
1997
|
+
* name is generated to avoid overwriting the existing keyframes.
|
|
1998
|
+
*/
|
|
1999
|
+
keyframes(steps, nameOrOptions) {
|
|
2000
|
+
const isStringName = typeof nameOrOptions === "string";
|
|
2001
|
+
const providedName = isStringName ? nameOrOptions : nameOrOptions?.name;
|
|
2002
|
+
const distinctByName = isStringName ? false : nameOrOptions?.distinctByName ?? false;
|
|
2003
|
+
const root = isStringName ? document : nameOrOptions?.root || document;
|
|
2004
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
2005
|
+
if (Object.keys(steps).length === 0) return {
|
|
2006
|
+
toString: () => "",
|
|
2007
|
+
dispose: () => {}
|
|
2008
|
+
};
|
|
2009
|
+
const contentHash = distinctByName && providedName ? `${providedName}\u0000${JSON.stringify(steps)}` : JSON.stringify(steps);
|
|
2010
|
+
const existing = registry.keyframesCache.get(contentHash);
|
|
2011
|
+
if (existing) {
|
|
2012
|
+
existing.refCount++;
|
|
2013
|
+
return {
|
|
2014
|
+
toString: () => existing.name,
|
|
2015
|
+
dispose: () => this.disposeKeyframes(contentHash, registry)
|
|
2016
|
+
};
|
|
2017
|
+
}
|
|
2018
|
+
let actualName;
|
|
2019
|
+
if (providedName) {
|
|
2020
|
+
const existingContentForName = registry.keyframesNameToContent.get(providedName);
|
|
2021
|
+
if (existingContentForName && existingContentForName !== contentHash) actualName = `${providedName}-${makeKeyframeName(this.namePrefix, String(registry.keyframesCounter++))}`;
|
|
2022
|
+
else {
|
|
2023
|
+
actualName = providedName;
|
|
2024
|
+
registry.keyframesNameToContent.set(providedName, contentHash);
|
|
2025
|
+
}
|
|
2026
|
+
} else actualName = makeKeyframeName(this.namePrefix, String(registry.keyframesCounter++));
|
|
2027
|
+
const applyWrite = () => {
|
|
2028
|
+
const result = this.sheetManager.insertKeyframes(registry, steps, actualName, root);
|
|
2029
|
+
if (!result) return false;
|
|
2030
|
+
const { info, declarations } = result;
|
|
2031
|
+
if (this.config.autoPropertyTypes !== false && declarations) registry.propertyTypeResolver.scanDeclarations(declarations, (name) => registry.injectedProperties.has(name), (name, syntax, initialValue) => {
|
|
2032
|
+
this.property(name, {
|
|
2033
|
+
syntax,
|
|
2034
|
+
inherits: true,
|
|
2035
|
+
initialValue,
|
|
2036
|
+
root
|
|
2037
|
+
});
|
|
2038
|
+
});
|
|
2039
|
+
const entry = registry.keyframesCache.get(contentHash);
|
|
2040
|
+
if (entry) {
|
|
2041
|
+
entry.info = info;
|
|
2042
|
+
entry.pending = void 0;
|
|
2043
|
+
} else registry.keyframesCache.set(contentHash, {
|
|
2044
|
+
name: actualName,
|
|
2045
|
+
refCount: 1,
|
|
2046
|
+
info
|
|
2047
|
+
});
|
|
2048
|
+
if (registry.metrics) {
|
|
2049
|
+
registry.metrics.totalInsertions++;
|
|
2050
|
+
registry.metrics.misses++;
|
|
2051
|
+
}
|
|
2052
|
+
return true;
|
|
2053
|
+
};
|
|
2054
|
+
if (this.batching) {
|
|
2055
|
+
const entry = {
|
|
2056
|
+
name: actualName,
|
|
2057
|
+
refCount: 1,
|
|
2058
|
+
info: EMPTY_KEYFRAMES_INFO
|
|
2059
|
+
};
|
|
2060
|
+
registry.keyframesCache.set(contentHash, entry);
|
|
2061
|
+
entry.pending = enqueueStyleWrite(() => {
|
|
2062
|
+
if (applyWrite()) return;
|
|
2063
|
+
if (registry.keyframesCache.get(contentHash) === entry) registry.keyframesCache.delete(contentHash);
|
|
2064
|
+
});
|
|
2065
|
+
return {
|
|
2066
|
+
toString: () => actualName,
|
|
2067
|
+
dispose: () => this.disposeKeyframes(contentHash, registry)
|
|
2068
|
+
};
|
|
2069
|
+
}
|
|
2070
|
+
if (!applyWrite()) return {
|
|
2071
|
+
toString: () => "",
|
|
2072
|
+
dispose: () => {}
|
|
2073
|
+
};
|
|
2074
|
+
return {
|
|
2075
|
+
toString: () => actualName,
|
|
2076
|
+
dispose: () => this.disposeKeyframes(contentHash, registry)
|
|
2077
|
+
};
|
|
2078
|
+
}
|
|
2079
|
+
/**
|
|
2080
|
+
* Dispose keyframes
|
|
2081
|
+
*/
|
|
2082
|
+
disposeKeyframes(contentHash, registry) {
|
|
2083
|
+
const entry = registry.keyframesCache.get(contentHash);
|
|
2084
|
+
if (!entry) return;
|
|
2085
|
+
entry.refCount--;
|
|
2086
|
+
if (entry.refCount <= 0) {
|
|
2087
|
+
if (entry.pending && !entry.pending.done) entry.pending.cancelled = true;
|
|
2088
|
+
else this.sheetManager.deleteKeyframes(registry, entry.info);
|
|
2089
|
+
registry.keyframesCache.delete(contentHash);
|
|
2090
|
+
for (const [name, hash] of registry.keyframesNameToContent.entries()) if (hash === contentHash) {
|
|
2091
|
+
registry.keyframesNameToContent.delete(name);
|
|
2092
|
+
break;
|
|
2093
|
+
}
|
|
2094
|
+
if (registry.metrics) {
|
|
2095
|
+
registry.metrics.totalUnused++;
|
|
2096
|
+
registry.metrics.stylesCleanedUp++;
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
/**
|
|
2101
|
+
* Count a render, and schedule a collection pass every `touchInterval` of
|
|
2102
|
+
* them. Nothing else: what a class is worth keeping is decided by the sweep's
|
|
2103
|
+
* own DOM scan, so rendering does not track usage at all.
|
|
2104
|
+
*
|
|
2105
|
+
* @deprecated The class name is ignored — pass anything, or stop calling it.
|
|
2106
|
+
* Collection no longer records per-class usage, and scheduling does not need
|
|
2107
|
+
* to know which class was rendered. A class handed back by `inject()` is
|
|
2108
|
+
* marked wanted there, which is what reuse actually goes through.
|
|
2109
|
+
*/
|
|
2110
|
+
touch(_className, options) {
|
|
2111
|
+
if (typeof document === "undefined") return;
|
|
2112
|
+
if (!this.config.gc) return;
|
|
2113
|
+
const registry = this.sheetManager.getRegistry(options?.root || document);
|
|
2114
|
+
if (++registry.touchCount >= (this.config.gc.touchInterval ?? 1e3)) {
|
|
2115
|
+
registry.touchCount = 0;
|
|
2116
|
+
this.scheduleGC();
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
/**
|
|
2120
|
+
* Schedule a GC in idle time. Runs GC on all active roots, and avoids
|
|
2121
|
+
* double-scheduling.
|
|
2122
|
+
*
|
|
2123
|
+
* Idle only. Without `requestIdleCallback` nothing is collected
|
|
2124
|
+
* automatically: running the sweep inline here would put it inside the render
|
|
2125
|
+
* that touched the class, and collection is never urgent enough for that.
|
|
2126
|
+
*/
|
|
2127
|
+
scheduleGC() {
|
|
2128
|
+
if (this.cancelPendingGC) return;
|
|
2129
|
+
const runGC = () => {
|
|
2130
|
+
this.cancelPendingGC = null;
|
|
2131
|
+
this.sheetManager.pruneDisconnectedRoots();
|
|
2132
|
+
for (const root of this.sheetManager.getActiveRoots()) this.gc({ root });
|
|
2133
|
+
};
|
|
2134
|
+
if (typeof requestIdleCallback !== "undefined") {
|
|
2135
|
+
const handle = requestIdleCallback(() => runGC());
|
|
2136
|
+
this.cancelPendingGC = () => cancelIdleCallback(handle);
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* The one definition of "unused": this injector owns the class's rules, no
|
|
2141
|
+
* element in `root` carries it, and nobody pinned it.
|
|
2142
|
+
*
|
|
2143
|
+
* `gc()` evicts from this set, `getMetrics()` counts it, and `tastyDebug`
|
|
2144
|
+
* reports it — all through here, so the three can never disagree about what
|
|
2145
|
+
* "unused" means. Entries carry their last `touch()` so callers can drop the
|
|
2146
|
+
* oldest first; a class that was never touched sorts as oldest.
|
|
2147
|
+
*/
|
|
2148
|
+
/**
|
|
2149
|
+
* Everything the injector holds falls into one of five bands, and only the
|
|
2150
|
+
* last of them is ever deleted:
|
|
2151
|
+
*
|
|
2152
|
+
* 1. rendered — some element carries the class right now
|
|
2153
|
+
* 2. not ours — queued for a batched write, pre-allocated, or server-rendered
|
|
2154
|
+
* 3. hot — nothing carries it, but that was noticed less than `grace` ago
|
|
2155
|
+
* 4. cached — cold, but within `capacity` when ordered by when it went cold
|
|
2156
|
+
* 5. the rest
|
|
2157
|
+
*
|
|
2158
|
+
* This returns bands 4 and 5 together, most recently cold first; `gc()` draws
|
|
2159
|
+
* the capacity line through them. Band 3 is what makes collection safe
|
|
2160
|
+
* without a commit signal: a render can resolve a class and commit it a
|
|
2161
|
+
* little later, and during that gap nothing on the page carries it.
|
|
2162
|
+
*/
|
|
2163
|
+
collectUnused(registry, root) {
|
|
2164
|
+
const now = Date.now();
|
|
2165
|
+
const grace = this.config.gc?.grace ?? DEFAULT_GC_GRACE;
|
|
2166
|
+
const liveClasses = /* @__PURE__ */ new Set();
|
|
2167
|
+
for (const el of root.querySelectorAll("[class]")) for (const token of el.classList) if (this.classRegex.test(token)) liveClasses.add(token);
|
|
2168
|
+
const unused = [];
|
|
2169
|
+
for (const [className, ruleInfo] of registry.rules) {
|
|
2170
|
+
if (ruleInfo.sheetIndex < 0) continue;
|
|
2171
|
+
if (liveClasses.has(className)) {
|
|
2172
|
+
registry.unusedSince.delete(className);
|
|
2173
|
+
continue;
|
|
2174
|
+
}
|
|
2175
|
+
if ((registry.pinCounts.get(className) ?? 0) > 0) continue;
|
|
2176
|
+
let since = registry.unusedSince.get(className);
|
|
2177
|
+
if (since === void 0) {
|
|
2178
|
+
since = now;
|
|
2179
|
+
registry.unusedSince.set(className, now);
|
|
2180
|
+
}
|
|
2181
|
+
if (now - since < grace) continue;
|
|
2182
|
+
unused.push(className);
|
|
2183
|
+
}
|
|
2184
|
+
unused.sort((a, b) => (registry.unusedSince.get(b) ?? 0) - (registry.unusedSince.get(a) ?? 0));
|
|
2185
|
+
return unused;
|
|
2186
|
+
}
|
|
2187
|
+
/**
|
|
2188
|
+
* Class names this injector holds CSS for that nothing renders and nobody
|
|
2189
|
+
* pinned — exactly what `gc({ force: true })` would delete. Unordered.
|
|
2190
|
+
*/
|
|
2191
|
+
getUnusedClasses(options) {
|
|
2192
|
+
flushStyles();
|
|
2193
|
+
if (typeof document === "undefined") return [];
|
|
2194
|
+
const root = options?.root || document;
|
|
2195
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
2196
|
+
return this.collectUnused(registry, root);
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* Synchronous garbage collection.
|
|
2200
|
+
*
|
|
2201
|
+
* 1. Quick upper-bound check: skip if the registry is smaller than capacity.
|
|
2202
|
+
* 2. Scans the DOM for live tasty classNames — the DOM, not a ref count, is
|
|
2203
|
+
* what says a class rendered by a component is still in use.
|
|
2204
|
+
* 3. With `force: true`: deletes every unused class.
|
|
2205
|
+
* Without `force`: keeps the `capacity` most recently touched and deletes
|
|
2206
|
+
* the rest, oldest first.
|
|
2207
|
+
*
|
|
2208
|
+
* @returns Number of styles evicted.
|
|
2209
|
+
*/
|
|
2210
|
+
gc(options) {
|
|
2211
|
+
flushStyles();
|
|
2212
|
+
if (typeof document === "undefined") return 0;
|
|
2213
|
+
this.cancelPendingGC?.();
|
|
2214
|
+
this.cancelPendingGC = null;
|
|
2215
|
+
const root = options?.root || document;
|
|
2216
|
+
const force = options?.force;
|
|
2217
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
2218
|
+
const capacity = this.config.gc?.capacity ?? 1e3;
|
|
2219
|
+
if (!force && registry.rules.size <= capacity) return 0;
|
|
2220
|
+
const unused = this.collectUnused(registry, root);
|
|
2221
|
+
let doomed;
|
|
2222
|
+
if (force) doomed = unused;
|
|
2223
|
+
else if (unused.length > capacity) doomed = unused.slice(capacity);
|
|
2224
|
+
else return 0;
|
|
2225
|
+
if (doomed.length === 0) return 0;
|
|
2226
|
+
return this.sheetManager.deleteClasses(registry, doomed);
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* Destroy all resources for a root
|
|
2230
|
+
*/
|
|
2231
|
+
destroy(root) {
|
|
2232
|
+
flushStyles();
|
|
2233
|
+
const targetRoot = root || document;
|
|
2234
|
+
this.sheetManager.cleanup(targetRoot);
|
|
2235
|
+
if (this.cancelPendingGC && !this.sheetManager.hasActiveRoots()) {
|
|
2236
|
+
this.cancelPendingGC();
|
|
2237
|
+
this.cancelPendingGC = null;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
};
|
|
2241
|
+
//#endregion
|
|
2242
|
+
//#region src/config.ts
|
|
2243
|
+
/**
|
|
2244
|
+
* Tasty Configuration Module
|
|
2245
|
+
*
|
|
2246
|
+
* Centralizes all tasty configuration, including:
|
|
2247
|
+
* - Style injector settings (nonce, cleanup thresholds, etc.)
|
|
2248
|
+
* - Global predefined states for advanced state mapping
|
|
2249
|
+
* - stylesGenerated flag that locks configuration after first style generation
|
|
2250
|
+
*
|
|
2251
|
+
* Configuration must be done BEFORE any styles are generated.
|
|
2252
|
+
* After the first `inject()` call, configuration is locked and attempts to
|
|
2253
|
+
* reconfigure will emit a warning and be ignored.
|
|
2254
|
+
*/
|
|
2255
|
+
const emittedWarnings = /* @__PURE__ */ new Set();
|
|
2256
|
+
const devMode = isDevEnv();
|
|
2257
|
+
/**
|
|
2258
|
+
* Emit a warning only once
|
|
2259
|
+
*/
|
|
2260
|
+
function warnOnce(key, message) {
|
|
2261
|
+
if (devMode && !emittedWarnings.has(key)) {
|
|
2262
|
+
emittedWarnings.add(key);
|
|
2263
|
+
console.warn(message);
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
let currentConfig = null;
|
|
2267
|
+
let globalKeyframes = null;
|
|
2268
|
+
let globalFontFace = null;
|
|
2269
|
+
let globalCounterStyle = null;
|
|
2270
|
+
let globalFunction = null;
|
|
2271
|
+
let globalProperties = null;
|
|
2272
|
+
let globalRecipes = null;
|
|
2273
|
+
let globalConfigTokens = null;
|
|
2274
|
+
let globalStyles = null;
|
|
2275
|
+
const GTKEY_TOKENS = "__tasty_cfg_tokens__";
|
|
2276
|
+
const GTKEY_FONT_FACE = "__tasty_cfg_font_face__";
|
|
2277
|
+
const GTKEY_COUNTER_STYLE = "__tasty_cfg_counter_style__";
|
|
2278
|
+
const GTKEY_FUNCTION = "__tasty_cfg_function__";
|
|
2279
|
+
const GTKEY_PROPERTIES = "__tasty_cfg_properties__";
|
|
2280
|
+
const GTKEY_GLOBAL_STYLES = "__tasty_cfg_global_styles__";
|
|
2281
|
+
function setOnGlobalThis(key, value) {
|
|
2282
|
+
globalThis[key] = value;
|
|
2283
|
+
}
|
|
2284
|
+
function getFromGlobalThis(key) {
|
|
2285
|
+
return globalThis[key];
|
|
2286
|
+
}
|
|
2287
|
+
function clearGlobalThisConfig() {
|
|
2288
|
+
const g = globalThis;
|
|
2289
|
+
delete g[GTKEY_TOKENS];
|
|
2290
|
+
delete g[GTKEY_FONT_FACE];
|
|
2291
|
+
delete g[GTKEY_COUNTER_STYLE];
|
|
2292
|
+
delete g[GTKEY_FUNCTION];
|
|
2293
|
+
delete g[GTKEY_PROPERTIES];
|
|
2294
|
+
delete g[GTKEY_GLOBAL_STYLES];
|
|
2295
|
+
}
|
|
2296
|
+
const GLOBAL_INJECTOR_KEY = "__TASTY_GLOBAL_INJECTOR__";
|
|
2297
|
+
/**
|
|
2298
|
+
* Detect if we're running in a test environment
|
|
2299
|
+
*/
|
|
2300
|
+
function isTestEnvironment() {
|
|
2301
|
+
if (typeof global !== "undefined") {
|
|
2302
|
+
const g = global;
|
|
2303
|
+
if (g.vi || g.jest || g.expect || g.describe || g.it) return true;
|
|
2304
|
+
}
|
|
2305
|
+
if (typeof window !== "undefined") {
|
|
2306
|
+
const ua = window.navigator?.userAgent;
|
|
2307
|
+
if (ua?.includes("jsdom") || ua?.includes("HappyDOM")) return true;
|
|
2308
|
+
}
|
|
2309
|
+
if (typeof globalThis !== "undefined") {
|
|
2310
|
+
const gt = globalThis;
|
|
2311
|
+
if (gt.vitest || gt.mocha) return true;
|
|
2312
|
+
}
|
|
2313
|
+
return false;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* Create default configuration with optional test environment detection
|
|
2317
|
+
*/
|
|
2318
|
+
function createDefaultConfig(isTest) {
|
|
2319
|
+
return {
|
|
2320
|
+
maxRulesPerSheet: 8192,
|
|
2321
|
+
forceTextInjection: isTest ?? false,
|
|
2322
|
+
devMode: isDevEnv(),
|
|
2323
|
+
namePrefix: "t"
|
|
2324
|
+
};
|
|
2325
|
+
}
|
|
2326
|
+
/**
|
|
2327
|
+
* Mark that styles have been generated (called by injector on first inject)
|
|
2328
|
+
* This locks the configuration - no further changes allowed.
|
|
2329
|
+
* Also injects internal and global properties.
|
|
2330
|
+
*/
|
|
2331
|
+
function markStylesGenerated() {
|
|
2332
|
+
if (!markStylesGeneratedState()) return;
|
|
2333
|
+
if (typeof document !== "undefined" && document.querySelector("[data-tasty-ssr]")) {
|
|
2334
|
+
warnOnce("ssr-globals-skip", "[Tasty] SSR styles detected — skipping client-side global CSS injection to avoid duplicates.");
|
|
2335
|
+
return;
|
|
2336
|
+
}
|
|
2337
|
+
const injector = getGlobalInjector();
|
|
2338
|
+
for (const [token, definition] of Object.entries(getEffectiveProperties())) injector.property(token, definition);
|
|
2339
|
+
if (globalFontFace && Object.keys(globalFontFace).length > 0) for (const [family, input] of Object.entries(globalFontFace)) {
|
|
2340
|
+
const descriptors = Array.isArray(input) ? input : [input];
|
|
2341
|
+
for (const desc of descriptors) injector.fontFace(family, desc);
|
|
2342
|
+
}
|
|
2343
|
+
if (globalCounterStyle && Object.keys(globalCounterStyle).length > 0) for (const [name, descriptors] of Object.entries(globalCounterStyle)) injector.counterStyle(name, descriptors, { weak: true });
|
|
2344
|
+
if (globalFunction && Object.keys(globalFunction).length > 0) for (const [name, definition] of Object.entries(globalFunction)) injector.func(name, definition, { weak: true });
|
|
2345
|
+
if (globalConfigTokens && Object.keys(globalConfigTokens).length > 0) {
|
|
2346
|
+
const tokenRules = renderStyles(globalConfigTokens, ":root");
|
|
2347
|
+
if (tokenRules.length > 0) injector.injectGlobal(tokenRules);
|
|
2348
|
+
}
|
|
2349
|
+
if (globalStyles) {
|
|
2350
|
+
for (const [selector, styles] of Object.entries(globalStyles)) if (Object.keys(styles).length > 0) {
|
|
2351
|
+
const rules = renderStyles(styles, selector);
|
|
2352
|
+
if (rules.length > 0) injector.injectGlobal(rules);
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
let _hasGlobalKeyframes = false;
|
|
2357
|
+
/**
|
|
2358
|
+
* Check if any global keyframes are configured.
|
|
2359
|
+
* Uses a pre-computed flag to avoid Object.keys() allocation on every call.
|
|
2360
|
+
*/
|
|
2361
|
+
function hasGlobalKeyframes() {
|
|
2362
|
+
return _hasGlobalKeyframes;
|
|
2363
|
+
}
|
|
2364
|
+
/**
|
|
2365
|
+
* Get global keyframes configuration.
|
|
2366
|
+
* Returns null if no keyframes configured (fast path for zero-overhead).
|
|
2367
|
+
*/
|
|
2368
|
+
function getGlobalKeyframes() {
|
|
2369
|
+
return globalKeyframes;
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Set global keyframes (called from configure).
|
|
2373
|
+
* Internal use only.
|
|
2374
|
+
*/
|
|
2375
|
+
function setGlobalKeyframes(keyframes) {
|
|
2376
|
+
if (hasStylesGenerated()) {
|
|
2377
|
+
warnOnce("keyframes-after-styles", "[Tasty] Cannot update keyframes after styles have been generated.\nThe new keyframes will be ignored.");
|
|
2378
|
+
return;
|
|
2379
|
+
}
|
|
2380
|
+
globalKeyframes = {
|
|
2381
|
+
...globalKeyframes ?? {},
|
|
2382
|
+
...keyframes
|
|
2383
|
+
};
|
|
2384
|
+
_hasGlobalKeyframes = Object.keys(globalKeyframes).length > 0;
|
|
2385
|
+
}
|
|
2386
|
+
/**
|
|
2387
|
+
* Set global properties (called from configure).
|
|
2388
|
+
* Internal use only.
|
|
2389
|
+
*/
|
|
2390
|
+
function setGlobalProperties(properties) {
|
|
2391
|
+
if (hasStylesGenerated()) {
|
|
2392
|
+
warnOnce("properties-after-styles", "[Tasty] Cannot update properties after styles have been generated.\nThe new properties will be ignored.");
|
|
2393
|
+
return;
|
|
2394
|
+
}
|
|
2395
|
+
globalProperties = {
|
|
2396
|
+
...globalProperties ?? getFromGlobalThis(GTKEY_PROPERTIES) ?? {},
|
|
2397
|
+
...properties
|
|
2398
|
+
};
|
|
2399
|
+
setOnGlobalThis(GTKEY_PROPERTIES, globalProperties);
|
|
2400
|
+
}
|
|
2401
|
+
/**
|
|
2402
|
+
* Get the effective properties: DEFAULT_PROPERTIES merged with user-configured
|
|
2403
|
+
* properties. User properties override defaults with matching keys.
|
|
2404
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2405
|
+
*/
|
|
2406
|
+
function getEffectiveProperties() {
|
|
2407
|
+
const props = globalProperties ?? getFromGlobalThis(GTKEY_PROPERTIES);
|
|
2408
|
+
if (!props) return DEFAULT_PROPERTIES;
|
|
2409
|
+
return {
|
|
2410
|
+
...DEFAULT_PROPERTIES,
|
|
2411
|
+
...props
|
|
2412
|
+
};
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* Get global font-face configuration.
|
|
2416
|
+
* Returns null if no font faces configured.
|
|
2417
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2418
|
+
*/
|
|
2419
|
+
function getGlobalFontFaces() {
|
|
2420
|
+
return globalFontFace ?? getFromGlobalThis(GTKEY_FONT_FACE) ?? null;
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* Set global font faces (called from configure).
|
|
2424
|
+
* Internal use only.
|
|
2425
|
+
*/
|
|
2426
|
+
function setGlobalFontFace(fontFace) {
|
|
2427
|
+
if (hasStylesGenerated()) {
|
|
2428
|
+
warnOnce("fontface-after-styles", "[Tasty] Cannot update fontFaces after styles have been generated.\nThe new font faces will be ignored.");
|
|
2429
|
+
return;
|
|
2430
|
+
}
|
|
2431
|
+
globalFontFace = {
|
|
2432
|
+
...getGlobalFontFaces() ?? {},
|
|
2433
|
+
...fontFace
|
|
2434
|
+
};
|
|
2435
|
+
setOnGlobalThis(GTKEY_FONT_FACE, globalFontFace);
|
|
2436
|
+
}
|
|
2437
|
+
/**
|
|
2438
|
+
* Get global counter-style configuration.
|
|
2439
|
+
* Returns null if no counter styles configured.
|
|
2440
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2441
|
+
*/
|
|
2442
|
+
function getGlobalCounterStyles() {
|
|
2443
|
+
return globalCounterStyle ?? getFromGlobalThis(GTKEY_COUNTER_STYLE) ?? null;
|
|
2444
|
+
}
|
|
2445
|
+
/**
|
|
2446
|
+
* Set global counter styles (called from configure).
|
|
2447
|
+
* Internal use only.
|
|
2448
|
+
*/
|
|
2449
|
+
function setGlobalCounterStyle(counterStyle) {
|
|
2450
|
+
if (hasStylesGenerated()) {
|
|
2451
|
+
warnOnce("counterstyle-after-styles", "[Tasty] Cannot update counterStyles after styles have been generated.\nThe new counter styles will be ignored.");
|
|
2452
|
+
return;
|
|
2453
|
+
}
|
|
2454
|
+
globalCounterStyle = {
|
|
2455
|
+
...getGlobalCounterStyles() ?? {},
|
|
2456
|
+
...counterStyle
|
|
2457
|
+
};
|
|
2458
|
+
setOnGlobalThis(GTKEY_COUNTER_STYLE, globalCounterStyle);
|
|
2459
|
+
}
|
|
2460
|
+
/**
|
|
2461
|
+
* Get global @function configuration.
|
|
2462
|
+
* Returns null if no functions configured.
|
|
2463
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2464
|
+
*/
|
|
2465
|
+
function getGlobalFunctions() {
|
|
2466
|
+
return globalFunction ?? getFromGlobalThis(GTKEY_FUNCTION) ?? null;
|
|
2467
|
+
}
|
|
2468
|
+
/**
|
|
2469
|
+
* Set global functions (called from configure).
|
|
2470
|
+
* Internal use only.
|
|
2471
|
+
*/
|
|
2472
|
+
function setGlobalFunction(functions) {
|
|
2473
|
+
if (hasStylesGenerated()) {
|
|
2474
|
+
warnOnce("function-after-styles", "[Tasty] Cannot update functions after styles have been generated.\nThe new functions will be ignored.");
|
|
2475
|
+
return;
|
|
2476
|
+
}
|
|
2477
|
+
globalFunction = {
|
|
2478
|
+
...getGlobalFunctions() ?? {},
|
|
2479
|
+
...functions
|
|
2480
|
+
};
|
|
2481
|
+
setOnGlobalThis(GTKEY_FUNCTION, globalFunction);
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Check if any global recipes are configured.
|
|
2485
|
+
* Fast path: returns false if no recipes were ever set.
|
|
2486
|
+
*/
|
|
2487
|
+
function hasGlobalRecipes() {
|
|
2488
|
+
return globalRecipes !== null && Object.keys(globalRecipes).length > 0;
|
|
2489
|
+
}
|
|
2490
|
+
/**
|
|
2491
|
+
* Get global recipes configuration.
|
|
2492
|
+
* Returns null if no recipes configured (fast path for zero-overhead).
|
|
2493
|
+
*/
|
|
2494
|
+
function getGlobalRecipes() {
|
|
2495
|
+
return globalRecipes;
|
|
2496
|
+
}
|
|
2497
|
+
/**
|
|
2498
|
+
* Set global recipes (called from configure).
|
|
2499
|
+
* Internal use only.
|
|
2500
|
+
*/
|
|
2501
|
+
function setGlobalRecipes(recipes) {
|
|
2502
|
+
if (hasStylesGenerated()) {
|
|
2503
|
+
warnOnce("recipes-after-styles", "[Tasty] Cannot update recipes after styles have been generated.\nThe new recipes will be ignored.");
|
|
2504
|
+
return;
|
|
2505
|
+
}
|
|
2506
|
+
if (devMode) for (const [name, recipeStyles] of Object.entries(recipes)) {
|
|
2507
|
+
if (name === "none") warnOnce("recipe-reserved-none", "[Tasty] Recipe name \"none\" is reserved. It is used as a keyword meaning \"no base recipes\" (e.g. recipe: 'none / post-recipe'). Choose a different name for your recipe.");
|
|
2508
|
+
for (const key of Object.keys(recipeStyles)) {
|
|
2509
|
+
if (isSelector(key)) warnOnce(`recipe-selector-${name}-${key}`, `[Tasty] Recipe "${name}" contains sub-element key "${key}". Recipes must be flat styles without sub-element keys. Remove the sub-element key from the recipe definition.`);
|
|
2510
|
+
if (key === "recipe") warnOnce(`recipe-recursive-${name}`, `[Tasty] Recipe "${name}" contains a "recipe" key. Recipes cannot reference other recipes. Use space-separated names for composition: recipe: 'base elevated'.`);
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
globalRecipes = {
|
|
2514
|
+
...globalRecipes ?? {},
|
|
2515
|
+
...recipes
|
|
2516
|
+
};
|
|
2517
|
+
}
|
|
2518
|
+
/**
|
|
2519
|
+
* Get global token styles for :root injection.
|
|
2520
|
+
* Returns null if no tokens configured.
|
|
2521
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2522
|
+
*/
|
|
2523
|
+
function getGlobalConfigTokens() {
|
|
2524
|
+
return globalConfigTokens ?? getFromGlobalThis(GTKEY_TOKENS) ?? null;
|
|
2525
|
+
}
|
|
2526
|
+
/**
|
|
2527
|
+
* Set global token styles (called from configure).
|
|
2528
|
+
* Internal use only.
|
|
2529
|
+
*/
|
|
2530
|
+
function setGlobalConfigTokens(styles) {
|
|
2531
|
+
if (hasStylesGenerated()) {
|
|
2532
|
+
warnOnce("tokens-after-styles", "[Tasty] Cannot update tokens after styles have been generated.\nThe new tokens will be ignored.");
|
|
2533
|
+
return;
|
|
2534
|
+
}
|
|
2535
|
+
globalConfigTokens = globalConfigTokens ? {
|
|
2536
|
+
...globalConfigTokens,
|
|
2537
|
+
...styles
|
|
2538
|
+
} : styles;
|
|
2539
|
+
setOnGlobalThis(GTKEY_TOKENS, globalConfigTokens);
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Get configured global styles for injection.
|
|
2543
|
+
* Returns null if no global styles configured.
|
|
2544
|
+
* Reads from globalThis first for cross-module SSR support.
|
|
2545
|
+
*/
|
|
2546
|
+
function getGlobalStyles() {
|
|
2547
|
+
return globalStyles ?? getFromGlobalThis(GTKEY_GLOBAL_STYLES) ?? null;
|
|
2548
|
+
}
|
|
2549
|
+
/**
|
|
2550
|
+
* Set configured global styles (called from configure).
|
|
2551
|
+
* Internal use only.
|
|
2552
|
+
*/
|
|
2553
|
+
function setGlobalStyles(styles) {
|
|
2554
|
+
if (hasStylesGenerated()) {
|
|
2555
|
+
warnOnce("globalStyles-after-styles", "[Tasty] Cannot update globalStyles after styles have been generated.\nThe new global styles will be ignored.");
|
|
2556
|
+
return;
|
|
2557
|
+
}
|
|
2558
|
+
if (globalStyles) for (const [selector, selectorStyles] of Object.entries(styles)) globalStyles[selector] = globalStyles[selector] ? {
|
|
2559
|
+
...globalStyles[selector],
|
|
2560
|
+
...selectorStyles
|
|
2561
|
+
} : selectorStyles;
|
|
2562
|
+
else globalStyles = { ...styles };
|
|
2563
|
+
setOnGlobalThis(GTKEY_GLOBAL_STYLES, globalStyles);
|
|
2564
|
+
}
|
|
2565
|
+
/**
|
|
2566
|
+
* Check if configuration is locked (styles have been generated)
|
|
2567
|
+
*/
|
|
2568
|
+
function isConfigLocked() {
|
|
2569
|
+
return hasStylesGenerated();
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Configure the Tasty style system.
|
|
2573
|
+
*
|
|
2574
|
+
* Must be called BEFORE any styles are generated (before first render that uses tasty).
|
|
2575
|
+
* After styles are generated, configuration is locked and calls to configure() will
|
|
2576
|
+
* emit a warning and be ignored.
|
|
2577
|
+
*
|
|
2578
|
+
* @example
|
|
2579
|
+
* ```ts
|
|
2580
|
+
* import { configure } from '@tenphi/tasty';
|
|
2581
|
+
*
|
|
2582
|
+
* // Configure before app renders
|
|
2583
|
+
* configure({
|
|
2584
|
+
* nonce: 'abc123',
|
|
2585
|
+
* states: {
|
|
2586
|
+
* '@mobile': '@media(w < 768px)',
|
|
2587
|
+
* '@dark': '@root(theme=dark)',
|
|
2588
|
+
* },
|
|
2589
|
+
* });
|
|
2590
|
+
* ```
|
|
2591
|
+
*/
|
|
2592
|
+
function configure(config = {}) {
|
|
2593
|
+
if (hasStylesGenerated()) {
|
|
2594
|
+
warnOnce("configure-after-styles", "[Tasty] Cannot call configure() after styles have been generated.\nConfiguration must be done before the first render. The configuration will be ignored.");
|
|
2595
|
+
return;
|
|
2596
|
+
}
|
|
2597
|
+
if (config.namePrefix !== void 0) validateNamePrefix(config.namePrefix);
|
|
2598
|
+
const normalized = normalizeConfig(config);
|
|
2599
|
+
const { propHandlers: mergedPropHandlers, propHandlerSources, baseStyleProps: mergedBaseStyleProps, properties: mergedProperties, keyframes: mergedKeyframes, fontFaces: mergedFontFaces, counterStyles: mergedCounterStyles, tokens: mergedConfigTokens, recipes: mergedRecipes, globalStyles: mergedGlobalStyles } = normalized;
|
|
2600
|
+
const functionDefs = applyStyleConfig(config, normalized, warnOnce);
|
|
2601
|
+
if (!isFunctionsPolyfillEnabled() && Object.keys(functionDefs).length > 0) setGlobalFunction(functionDefs);
|
|
2602
|
+
if (Object.keys(mergedKeyframes).length > 0) setGlobalKeyframes(mergedKeyframes);
|
|
2603
|
+
if (Object.keys(mergedProperties).length > 0) setGlobalProperties(mergedProperties);
|
|
2604
|
+
if (Object.keys(mergedFontFaces).length > 0) setGlobalFontFace(mergedFontFaces);
|
|
2605
|
+
if (Object.keys(mergedCounterStyles).length > 0) setGlobalCounterStyle(mergedCounterStyles);
|
|
2606
|
+
if (Object.keys(mergedPropHandlers).length > 0) for (const [name, definition] of Object.entries(mergedPropHandlers)) registerPropHandler(name, definition, { source: propHandlerSources.get(name) });
|
|
2607
|
+
if (mergedBaseStyleProps.length > 0) registerBaseStyleProps(mergedBaseStyleProps);
|
|
2608
|
+
if (Object.keys(mergedConfigTokens).length > 0) setGlobalConfigTokens(mergedConfigTokens);
|
|
2609
|
+
if (Object.keys(mergedRecipes).length > 0) setGlobalRecipes(mergedRecipes);
|
|
2610
|
+
if (Object.keys(mergedGlobalStyles).length > 0) setGlobalStyles(mergedGlobalStyles);
|
|
2611
|
+
const { states: _states, parserCacheSize: _parserCacheSize, units: _units, functions: _functions, polyfills: _polyfills, plugins: _plugins, keyframes: _keyframes, properties: _properties, fontFaces: _fontFaces, counterStyles: _counterStyles, handlers: _handlers, propHandlers: _propHandlers, baseStyleProps: _baseStyleProps, tokens: _tokens, replaceTokens: _replaceTokens, recipes: _recipes, colorSpace: _colorSpace, presets: _presets, globalStyles: _globalStyles, ...injectorConfig } = config;
|
|
2612
|
+
const fullConfig = {
|
|
2613
|
+
...createDefaultConfig(),
|
|
2614
|
+
...currentConfig,
|
|
2615
|
+
...injectorConfig
|
|
2616
|
+
};
|
|
2617
|
+
currentConfig = fullConfig;
|
|
2618
|
+
const storage = typeof window !== "undefined" ? window : globalThis;
|
|
2619
|
+
storage[GLOBAL_INJECTOR_KEY] = new StyleInjector(fullConfig);
|
|
2620
|
+
}
|
|
2621
|
+
/**
|
|
2622
|
+
* Get the current configuration.
|
|
2623
|
+
* If not configured, returns default configuration.
|
|
2624
|
+
*/
|
|
2625
|
+
function getConfig() {
|
|
2626
|
+
if (!currentConfig) currentConfig = createDefaultConfig(isTestEnvironment());
|
|
2627
|
+
return currentConfig;
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* Get the configured prefix used for every generated identifier
|
|
2631
|
+
* (class names, keyframe names, counter-style names).
|
|
2632
|
+
*
|
|
2633
|
+
* Falls back to the default prefix (`'t'`) when `configure()` has not
|
|
2634
|
+
* been called yet — this matches the auto-configuration behavior used
|
|
2635
|
+
* by the rest of the system.
|
|
2636
|
+
*/
|
|
2637
|
+
function getNamePrefix() {
|
|
2638
|
+
return currentConfig?.namePrefix ?? "t";
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* Get the global injector instance.
|
|
2642
|
+
* Auto-configures with defaults if not already configured.
|
|
2643
|
+
*/
|
|
2644
|
+
function getGlobalInjector() {
|
|
2645
|
+
const storage = typeof window !== "undefined" ? window : globalThis;
|
|
2646
|
+
if (!storage[GLOBAL_INJECTOR_KEY]) configure();
|
|
2647
|
+
return storage[GLOBAL_INJECTOR_KEY];
|
|
2648
|
+
}
|
|
2649
|
+
/**
|
|
2650
|
+
* Reset configuration (for testing only).
|
|
2651
|
+
* Clears the global injector and allows reconfiguration.
|
|
2652
|
+
*/
|
|
2653
|
+
function resetConfig() {
|
|
2654
|
+
resetStylesGeneratedState();
|
|
2655
|
+
currentConfig = null;
|
|
2656
|
+
globalKeyframes = null;
|
|
2657
|
+
_hasGlobalKeyframes = false;
|
|
2658
|
+
globalProperties = null;
|
|
2659
|
+
globalFontFace = null;
|
|
2660
|
+
globalCounterStyle = null;
|
|
2661
|
+
globalFunction = null;
|
|
2662
|
+
resetGlobalPolyfillsState();
|
|
2663
|
+
globalRecipes = null;
|
|
2664
|
+
globalConfigTokens = null;
|
|
2665
|
+
globalStyles = null;
|
|
2666
|
+
clearGlobalThisConfig();
|
|
2667
|
+
resetGlobalPredefinedTokens();
|
|
2668
|
+
resetGlobalParseFunctions();
|
|
2669
|
+
resetFunctionPolyfills();
|
|
2670
|
+
resetHandlers();
|
|
2671
|
+
resetStyleChunks();
|
|
2672
|
+
resetPropHandlers();
|
|
2673
|
+
resetBaseStyleProps();
|
|
2674
|
+
clearPipelineCache();
|
|
2675
|
+
emittedWarnings.clear();
|
|
2676
|
+
resetStyleWarnings();
|
|
2677
|
+
const storage = typeof window !== "undefined" ? window : globalThis;
|
|
2678
|
+
delete storage[GLOBAL_INJECTOR_KEY];
|
|
2679
|
+
}
|
|
2680
|
+
//#endregion
|
|
2681
|
+
//#region src/injector/chunk-sheet-registry.ts
|
|
2682
|
+
/**
|
|
2683
|
+
* Global registry mapping CSS content hashes to shared constructable
|
|
2684
|
+
* CSSStyleSheet objects with reference counting.
|
|
2685
|
+
*
|
|
2686
|
+
* Multiple shadow roots adopting the same chunk share a single underlying
|
|
2687
|
+
* stylesheet object — parse once, adopt everywhere.
|
|
2688
|
+
*/
|
|
2689
|
+
var ChunkSheetRegistry = class {
|
|
2690
|
+
sheets = /* @__PURE__ */ new Map();
|
|
2691
|
+
sheetToHash = /* @__PURE__ */ new WeakMap();
|
|
2692
|
+
/**
|
|
2693
|
+
* Get or create a CSSStyleSheet for the given CSS text.
|
|
2694
|
+
* Increments refCount. Uses content hash as the dedup key.
|
|
2695
|
+
*/
|
|
2696
|
+
acquire(cssText) {
|
|
2697
|
+
const hash = hashString(cssText);
|
|
2698
|
+
const existing = this.sheets.get(hash);
|
|
2699
|
+
if (existing) {
|
|
2700
|
+
existing.refCount++;
|
|
2701
|
+
return existing.sheet;
|
|
2702
|
+
}
|
|
2703
|
+
const sheet = new CSSStyleSheet();
|
|
2704
|
+
sheet.replaceSync(cssText);
|
|
2705
|
+
const entry = {
|
|
2706
|
+
sheet,
|
|
2707
|
+
cssText,
|
|
2708
|
+
refCount: 1
|
|
2709
|
+
};
|
|
2710
|
+
this.sheets.set(hash, entry);
|
|
2711
|
+
this.sheetToHash.set(sheet, hash);
|
|
2712
|
+
return sheet;
|
|
2713
|
+
}
|
|
2714
|
+
/**
|
|
2715
|
+
* Decrement refCount for a sheet. When refCount reaches 0,
|
|
2716
|
+
* the sheet is removed from the registry.
|
|
2717
|
+
*/
|
|
2718
|
+
release(sheet) {
|
|
2719
|
+
const hash = this.sheetToHash.get(sheet);
|
|
2720
|
+
if (!hash) return;
|
|
2721
|
+
const entry = this.sheets.get(hash);
|
|
2722
|
+
if (!entry) return;
|
|
2723
|
+
entry.refCount--;
|
|
2724
|
+
if (entry.refCount <= 0) {
|
|
2725
|
+
this.sheets.delete(hash);
|
|
2726
|
+
this.sheetToHash.delete(sheet);
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Bulk acquire — returns an array of CSSStyleSheet in the same order.
|
|
2731
|
+
*/
|
|
2732
|
+
acquireAll(cssTexts) {
|
|
2733
|
+
return cssTexts.map((text) => this.acquire(text));
|
|
2734
|
+
}
|
|
2735
|
+
/**
|
|
2736
|
+
* Bulk release — decrements refCount for each sheet.
|
|
2737
|
+
*/
|
|
2738
|
+
releaseAll(sheets) {
|
|
2739
|
+
for (const sheet of sheets) this.release(sheet);
|
|
2740
|
+
}
|
|
2741
|
+
/** Number of unique sheets currently held. */
|
|
2742
|
+
get size() {
|
|
2743
|
+
return this.sheets.size;
|
|
2744
|
+
}
|
|
2745
|
+
};
|
|
2746
|
+
/** Module-level singleton shared across the entire application. */
|
|
2747
|
+
const chunkSheetRegistry = new ChunkSheetRegistry();
|
|
2748
|
+
//#endregion
|
|
2749
|
+
//#region src/injector/index.ts
|
|
2750
|
+
/**
|
|
2751
|
+
* Inject styles and return className with dispose function
|
|
2752
|
+
*/
|
|
2753
|
+
function inject(rules, options) {
|
|
2754
|
+
const injector = getGlobalInjector();
|
|
2755
|
+
markStylesGenerated();
|
|
2756
|
+
return injector.inject(rules, options);
|
|
2757
|
+
}
|
|
2758
|
+
/**
|
|
2759
|
+
* Inject global rules that should not reserve tasty class names
|
|
2760
|
+
*/
|
|
2761
|
+
function injectGlobal(rules, options) {
|
|
2762
|
+
return getGlobalInjector().injectGlobal(rules, options);
|
|
2763
|
+
}
|
|
2764
|
+
/**
|
|
2765
|
+
* Inject raw CSS text directly without parsing
|
|
2766
|
+
* This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.
|
|
2767
|
+
* The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.
|
|
2768
|
+
*
|
|
2769
|
+
* @example
|
|
2770
|
+
* ```tsx
|
|
2771
|
+
* // Inject raw CSS
|
|
2772
|
+
* const { dispose } = injectRawCSS(`
|
|
2773
|
+
* body { margin: 0; padding: 0; }
|
|
2774
|
+
* .my-class { color: red; }
|
|
2775
|
+
* `);
|
|
2776
|
+
*
|
|
2777
|
+
* // Later, remove the injected CSS
|
|
2778
|
+
* dispose();
|
|
2779
|
+
* ```
|
|
2780
|
+
*/
|
|
2781
|
+
function injectRawCSS(css, options) {
|
|
2782
|
+
return getGlobalInjector().injectRawCSS(css, options);
|
|
2783
|
+
}
|
|
2784
|
+
/**
|
|
2785
|
+
* Get raw CSS text for SSR
|
|
2786
|
+
*/
|
|
2787
|
+
function getRawCSSText(options) {
|
|
2788
|
+
return getGlobalInjector().getRawCSSText(options);
|
|
2789
|
+
}
|
|
2790
|
+
/**
|
|
2791
|
+
* Inject keyframes and return object with toString() and dispose()
|
|
2792
|
+
*/
|
|
2793
|
+
function keyframes(steps, nameOrOptions) {
|
|
2794
|
+
return getGlobalInjector().keyframes(steps, nameOrOptions);
|
|
2795
|
+
}
|
|
2796
|
+
/**
|
|
2797
|
+
* Define a CSS @property custom property.
|
|
2798
|
+
* This enables advanced features like animating custom properties.
|
|
2799
|
+
*
|
|
2800
|
+
* Note: @property rules are global and persistent once defined.
|
|
2801
|
+
* Re-registering the same property name is a no-op.
|
|
2802
|
+
*
|
|
2803
|
+
* @param name - The custom property name (must start with --)
|
|
2804
|
+
* @param options - Property configuration
|
|
2805
|
+
*
|
|
2806
|
+
* @example
|
|
2807
|
+
* ```ts
|
|
2808
|
+
* // Define a color property that can be animated
|
|
2809
|
+
* property('--my-color', {
|
|
2810
|
+
* syntax: '<color>',
|
|
2811
|
+
* initialValue: 'red',
|
|
2812
|
+
* });
|
|
2813
|
+
*
|
|
2814
|
+
* // Define an angle property
|
|
2815
|
+
* property('--rotation', {
|
|
2816
|
+
* syntax: '<angle>',
|
|
2817
|
+
* inherits: false,
|
|
2818
|
+
* initialValue: '0deg',
|
|
2819
|
+
* });
|
|
2820
|
+
* ```
|
|
2821
|
+
*/
|
|
2822
|
+
function property(name, options) {
|
|
2823
|
+
return getGlobalInjector().property(name, options);
|
|
2824
|
+
}
|
|
2825
|
+
/**
|
|
2826
|
+
* Check if a CSS @property has already been defined
|
|
2827
|
+
*
|
|
2828
|
+
* @param name - The custom property name to check
|
|
2829
|
+
* @param options - Options including root
|
|
2830
|
+
*/
|
|
2831
|
+
function isPropertyDefined(name, options) {
|
|
2832
|
+
return getGlobalInjector().isPropertyDefined(name, options);
|
|
2833
|
+
}
|
|
2834
|
+
/**
|
|
2835
|
+
* Inject a CSS @font-face rule.
|
|
2836
|
+
*
|
|
2837
|
+
* Permanent and global — no dispose or ref-counting.
|
|
2838
|
+
* Deduplicates by content hash (family + descriptors).
|
|
2839
|
+
*/
|
|
2840
|
+
function fontFace(family, descriptors, options) {
|
|
2841
|
+
return getGlobalInjector().fontFace(family, descriptors, options);
|
|
2842
|
+
}
|
|
2843
|
+
/**
|
|
2844
|
+
* Inject a CSS @counter-style rule.
|
|
2845
|
+
*
|
|
2846
|
+
* Permanent and global — no dispose or ref-counting. Deduplicates by name and
|
|
2847
|
+
* overrides an existing rule by default. Pass `weak: true` for global
|
|
2848
|
+
* `configure()` definitions, which never clobber an existing rule.
|
|
2849
|
+
*/
|
|
2850
|
+
function counterStyle(name, descriptors, options) {
|
|
2851
|
+
return getGlobalInjector().counterStyle(name, descriptors, options);
|
|
2852
|
+
}
|
|
2853
|
+
/**
|
|
2854
|
+
* Inject a CSS @function rule (custom function).
|
|
2855
|
+
*
|
|
2856
|
+
* Permanent and global — no dispose or ref-counting. Deduplicates by function
|
|
2857
|
+
* name and overrides an existing rule by default. Pass `weak: true` for global
|
|
2858
|
+
* `configure()` definitions, which never clobber an existing rule.
|
|
2859
|
+
*
|
|
2860
|
+
* @param name - The function name (`$$name`, `$name`, or `--name`)
|
|
2861
|
+
* @param definition - Function definition (args, returns, result, local vars)
|
|
2862
|
+
*
|
|
2863
|
+
* @example
|
|
2864
|
+
* ```ts
|
|
2865
|
+
* func('$$negative', { args: ['$value'], result: '(-1 * $value)' });
|
|
2866
|
+
* ```
|
|
2867
|
+
*/
|
|
2868
|
+
function func(name, definition, options) {
|
|
2869
|
+
return getGlobalInjector().func(name, definition, options);
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* Get CSS text from all sheets (for SSR)
|
|
2873
|
+
*/
|
|
2874
|
+
function getCSSText(options) {
|
|
2875
|
+
return getGlobalInjector().getCSSText(options);
|
|
2876
|
+
}
|
|
2877
|
+
/**
|
|
2878
|
+
* Collect only CSS used by a rendered subtree (like jest-styled-components).
|
|
2879
|
+
* Pass the container returned by render(...).
|
|
2880
|
+
*/
|
|
2881
|
+
function getCSSTextForNode(node, options) {
|
|
2882
|
+
const classRegex = tastyClassRegex(getNamePrefix());
|
|
2883
|
+
const classSet = /* @__PURE__ */ new Set();
|
|
2884
|
+
const readClasses = (el) => {
|
|
2885
|
+
const cls = el.getAttribute("class");
|
|
2886
|
+
if (!cls) return;
|
|
2887
|
+
for (const token of cls.split(/\s+/)) if (classRegex.test(token)) classSet.add(token);
|
|
2888
|
+
};
|
|
2889
|
+
if (node.getAttribute) readClasses(node);
|
|
2890
|
+
const elements = node.querySelectorAll ? node.querySelectorAll("[class]") : [];
|
|
2891
|
+
if (elements) elements.forEach(readClasses);
|
|
2892
|
+
return getGlobalInjector().getCSSTextForClasses(classSet, options);
|
|
2893
|
+
}
|
|
2894
|
+
/**
|
|
2895
|
+
* Take a reference on local `@keyframes` under the deterministic names the
|
|
2896
|
+
* caller resolved, and report which entry holds each. Pair with
|
|
2897
|
+
* `ownKeyframes()` once the rules exist to inspect.
|
|
2898
|
+
*/
|
|
2899
|
+
function holdKeyframes(steps, names, options) {
|
|
2900
|
+
return getGlobalInjector().holdKeyframes(steps, names, options);
|
|
2901
|
+
}
|
|
2902
|
+
/**
|
|
2903
|
+
* Record that a class animates these keyframes, so the reference is released
|
|
2904
|
+
* when the last such class is collected.
|
|
2905
|
+
*/
|
|
2906
|
+
function ownKeyframes(key, className, options) {
|
|
2907
|
+
getGlobalInjector().ownKeyframes(key, className, options);
|
|
2908
|
+
}
|
|
2909
|
+
/**
|
|
2910
|
+
* Remove every injected rule that is neither in the DOM nor held by an
|
|
2911
|
+
* outstanding `inject()` handle. Equivalent to `gc({ force: true })`.
|
|
2912
|
+
*/
|
|
2913
|
+
function cleanup(root) {
|
|
2914
|
+
return getGlobalInjector().cleanup(root);
|
|
2915
|
+
}
|
|
2916
|
+
/**
|
|
2917
|
+
* Count a render, so that a collection pass is scheduled every
|
|
2918
|
+
* `gc.touchInterval` of them. Used internally by computeStyles and tasty().
|
|
2919
|
+
*
|
|
2920
|
+
* @deprecated The class name is ignored — collection asks the DOM what is
|
|
2921
|
+
* rendered rather than recording usage per class. The argument is kept so
|
|
2922
|
+
* existing calls still compile.
|
|
2923
|
+
*/
|
|
2924
|
+
function touch(className, options) {
|
|
2925
|
+
if (!getConfig().gc) return;
|
|
2926
|
+
getGlobalInjector().touch(className, options);
|
|
2927
|
+
}
|
|
2928
|
+
/**
|
|
2929
|
+
* Synchronous garbage collection of unused styles — those no element carries
|
|
2930
|
+
* and no `inject()` handle references. Evicts the oldest ones once they exceed
|
|
2931
|
+
* capacity. With `{ force: true }`, removes all of them regardless of capacity.
|
|
2932
|
+
*
|
|
2933
|
+
* @returns Number of styles evicted.
|
|
2934
|
+
*/
|
|
2935
|
+
function gc(options) {
|
|
2936
|
+
return getGlobalInjector().gc(options);
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
* Get the global injector instance for debugging
|
|
2940
|
+
*/
|
|
2941
|
+
const injector = { get instance() {
|
|
2942
|
+
return getGlobalInjector();
|
|
2943
|
+
} };
|
|
2944
|
+
/**
|
|
2945
|
+
* Destroy all resources and clean up
|
|
2946
|
+
*/
|
|
2947
|
+
function destroy(root) {
|
|
2948
|
+
return getGlobalInjector().destroy(root);
|
|
2949
|
+
}
|
|
2950
|
+
/**
|
|
2951
|
+
* Create a new isolated injector instance
|
|
2952
|
+
*/
|
|
2953
|
+
function createInjector(config = {}) {
|
|
2954
|
+
return new StyleInjector({
|
|
2955
|
+
...getConfig(),
|
|
2956
|
+
forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),
|
|
2957
|
+
...config
|
|
2958
|
+
});
|
|
2959
|
+
}
|
|
2960
|
+
//#endregion
|
|
2961
|
+
//#region src/ssr/ssr-collector-ref.ts
|
|
2962
|
+
const GETTER_KEY = "__tasty_ssr_collector_getter__";
|
|
2963
|
+
let _getSSRCollector = null;
|
|
2964
|
+
/**
|
|
2965
|
+
* Register the collector getter in the current module graph only.
|
|
2966
|
+
* Used by Next.js TastyRegistry.
|
|
2967
|
+
*/
|
|
2968
|
+
function registerSSRCollectorGetter(fn) {
|
|
2969
|
+
_getSSRCollector = fn;
|
|
2970
|
+
}
|
|
2971
|
+
/**
|
|
2972
|
+
* Register the collector getter on globalThis so it is visible across
|
|
2973
|
+
* separate module graphs (e.g. Astro middleware ↔ page components).
|
|
2974
|
+
*/
|
|
2975
|
+
function registerSSRCollectorGetterGlobal(fn) {
|
|
2976
|
+
globalThis[GETTER_KEY] = fn;
|
|
2977
|
+
}
|
|
2978
|
+
/**
|
|
2979
|
+
* Retrieve the SSR collector: module-level first, globalThis fallback.
|
|
2980
|
+
*/
|
|
2981
|
+
function getRegisteredSSRCollector() {
|
|
2982
|
+
if (_getSSRCollector) return _getSSRCollector();
|
|
2983
|
+
const getter = globalThis[GETTER_KEY];
|
|
2984
|
+
return getter ? getter() : null;
|
|
2985
|
+
}
|
|
2986
|
+
//#endregion
|
|
2987
|
+
//#region src/utils/resolve-recipes.ts
|
|
2988
|
+
/** Resolve recipe references against the globally configured recipe map. */
|
|
2989
|
+
function resolveRecipes(styles) {
|
|
2990
|
+
return resolveRecipesWith(styles, getGlobalRecipes());
|
|
2991
|
+
}
|
|
2992
|
+
//#endregion
|
|
2993
|
+
//#region src/utils/cache-wrapper.ts
|
|
2994
|
+
/**
|
|
2995
|
+
* Create a function that caches the result with LRU eviction.
|
|
2996
|
+
*/
|
|
2997
|
+
function cacheWrapper(handler, limit = 1e3) {
|
|
2998
|
+
const cache = new Lru(limit);
|
|
2999
|
+
return (firstArg, secondArg) => {
|
|
3000
|
+
const key = typeof firstArg === "string" && secondArg == null ? firstArg : JSON.stringify([firstArg, secondArg]);
|
|
3001
|
+
let result = cache.get(key);
|
|
3002
|
+
if (result === void 0) {
|
|
3003
|
+
result = secondArg == null ? handler(firstArg) : handler(firstArg, secondArg);
|
|
3004
|
+
cache.set(key, result);
|
|
3005
|
+
}
|
|
3006
|
+
return result;
|
|
3007
|
+
};
|
|
3008
|
+
}
|
|
3009
|
+
//#endregion
|
|
3010
|
+
//#region src/utils/client-state.ts
|
|
3011
|
+
/**
|
|
3012
|
+
* Build a per-(injector, root) client state cache for the standalone style
|
|
3013
|
+
* functions (`useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useCounterStyle`).
|
|
3014
|
+
*
|
|
3015
|
+
* Two levels, both weak:
|
|
3016
|
+
*
|
|
3017
|
+
* - **injector** — `configure()` replaces the global injector, and every dispose
|
|
3018
|
+
* handle and generated name we cache belongs to the one that produced it.
|
|
3019
|
+
* Keying by injector makes stale state fall away with it, instead of letting
|
|
3020
|
+
* change-detection keys suppress re-injection into the new sheets.
|
|
3021
|
+
* - **root** — the same selector or slot name can be used in several shadow
|
|
3022
|
+
* roots, and each holds its own injection.
|
|
3023
|
+
*/
|
|
3024
|
+
function createClientState(create) {
|
|
3025
|
+
const byInjector = /* @__PURE__ */ new WeakMap();
|
|
3026
|
+
return (root) => {
|
|
3027
|
+
const injector = getGlobalInjector();
|
|
3028
|
+
let byRoot = byInjector.get(injector);
|
|
3029
|
+
if (!byRoot) {
|
|
3030
|
+
byRoot = /* @__PURE__ */ new WeakMap();
|
|
3031
|
+
byInjector.set(injector, byRoot);
|
|
3032
|
+
}
|
|
3033
|
+
let state = byRoot.get(root);
|
|
3034
|
+
if (!state) {
|
|
3035
|
+
state = create();
|
|
3036
|
+
byRoot.set(root, state);
|
|
3037
|
+
}
|
|
3038
|
+
return state;
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
//#endregion
|
|
3042
|
+
//#region src/utils/deps-equal.ts
|
|
3043
|
+
/**
|
|
3044
|
+
* Shallow comparison of two dependency arrays using Object.is semantics.
|
|
3045
|
+
* Returns true when both arrays have the same length and every element
|
|
3046
|
+
* at the same index is identical.
|
|
3047
|
+
*/
|
|
3048
|
+
function depsEqual(a, b) {
|
|
3049
|
+
if (a.length !== b.length) return false;
|
|
3050
|
+
for (let i = 0; i < a.length; i++) if (!Object.is(a[i], b[i])) return false;
|
|
3051
|
+
return true;
|
|
3052
|
+
}
|
|
3053
|
+
//#endregion
|
|
3054
|
+
export { resetStyleBatch as $, configure as A, getGlobalStyles as B, isPropertyDefined as C, touch as D, property as E, getGlobalFontFaces as F, isTestEnvironment as G, hasGlobalKeyframes as H, getGlobalFunctions as I, SheetManager as J, resetConfig as K, getGlobalInjector as L, getEffectiveProperties as M, getGlobalConfigTokens as N, ChunkSheetRegistry as O, getGlobalCounterStyles as P, openBatchWindow as Q, getGlobalKeyframes as R, injector as S, ownKeyframes as T, hasGlobalRecipes as U, getNamePrefix as V, isConfigLocked as W, flushStyles as X, closeBatchWindow as Y, hasPendingStyleWrites as Z, getRawCSSText as _, getRegisteredSSRCollector as a, injectGlobal as b, cleanup as c, destroy as d, propHandlerRegistry as et, fontFace as f, getCSSTextForNode as g, getCSSText as h, resolveRecipes as i, getConfig as j, chunkSheetRegistry as k, counterStyle as l, gc as m, createClientState as n, registerSSRCollectorGetter as o, func as p, StyleInjector as q, cacheWrapper as r, registerSSRCollectorGetterGlobal as s, depsEqual as t, createInjector as u, holdKeyframes as v, keyframes as w, injectRawCSS as x, inject as y, getGlobalRecipes as z };
|
|
3055
|
+
|
|
3056
|
+
//# sourceMappingURL=runtime-engine-DQ5laRou.js.map
|