@tenphi/tasty 0.0.0-snapshot.2705ab9 → 0.0.0-snapshot.275370e
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 +26 -20
- package/dist/_virtual/_rolldown/runtime.js +1 -2
- package/dist/chunks/cacheKey.d.ts +1 -0
- package/dist/chunks/cacheKey.js +1 -2
- package/dist/chunks/cacheKey.js.map +1 -1
- package/dist/chunks/definitions.js +1 -2
- package/dist/chunks/definitions.js.map +1 -1
- package/dist/chunks/index.d.ts +1 -0
- package/dist/chunks/renderChunk.d.ts +1 -0
- package/dist/chunks/renderChunk.js +1 -2
- package/dist/chunks/renderChunk.js.map +1 -1
- package/dist/compute-styles.d.ts +31 -0
- package/dist/compute-styles.js +322 -0
- package/dist/compute-styles.js.map +1 -0
- package/dist/config.d.ts +61 -20
- package/dist/config.js +119 -32
- package/dist/config.js.map +1 -1
- package/dist/core/index.d.ts +6 -6
- package/dist/core/index.js +7 -7
- package/dist/counter-style/index.js +1 -1
- package/dist/counter-style/index.js.map +1 -1
- package/dist/debug.js +5 -6
- package/dist/debug.js.map +1 -1
- package/dist/font-face/index.js +1 -1
- package/dist/font-face/index.js.map +1 -1
- package/dist/hooks/index.d.ts +7 -0
- package/dist/hooks/useCounterStyle.d.ts +3 -17
- package/dist/hooks/useCounterStyle.js +56 -38
- package/dist/hooks/useCounterStyle.js.map +1 -1
- package/dist/hooks/useFontFace.d.ts +3 -1
- package/dist/hooks/useFontFace.js +22 -27
- package/dist/hooks/useFontFace.js.map +1 -1
- package/dist/hooks/useGlobalStyles.d.ts +18 -2
- package/dist/hooks/useGlobalStyles.js +52 -43
- package/dist/hooks/useGlobalStyles.js.map +1 -1
- package/dist/hooks/useKeyframes.d.ts +4 -2
- package/dist/hooks/useKeyframes.js +43 -53
- package/dist/hooks/useKeyframes.js.map +1 -1
- package/dist/hooks/useProperty.d.ts +4 -2
- package/dist/hooks/useProperty.js +30 -44
- package/dist/hooks/useProperty.js.map +1 -1
- package/dist/hooks/useRawCSS.d.ts +13 -44
- package/dist/hooks/useRawCSS.js +91 -24
- package/dist/hooks/useRawCSS.js.map +1 -1
- package/dist/hooks/useStyles.d.ts +3 -8
- package/dist/hooks/useStyles.js +7 -214
- package/dist/hooks/useStyles.js.map +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +8 -8
- package/dist/injector/index.d.ts +18 -19
- package/dist/injector/index.js +25 -20
- package/dist/injector/index.js.map +1 -1
- package/dist/injector/injector.d.ts +35 -3
- package/dist/injector/injector.js +200 -14
- package/dist/injector/injector.js.map +1 -1
- package/dist/injector/sheet-manager.d.ts +9 -13
- package/dist/injector/sheet-manager.js +34 -69
- package/dist/injector/sheet-manager.js.map +1 -1
- package/dist/injector/types.d.ts +52 -21
- package/dist/keyframes/index.js +1 -1
- package/dist/parser/classify.js +1 -2
- package/dist/parser/classify.js.map +1 -1
- package/dist/parser/const.js +14 -3
- package/dist/parser/const.js.map +1 -1
- package/dist/parser/lru.js +1 -1
- package/dist/parser/lru.js.map +1 -1
- package/dist/parser/parser.js +1 -2
- package/dist/parser/parser.js.map +1 -1
- package/dist/parser/tokenizer.js +1 -1
- package/dist/parser/tokenizer.js.map +1 -1
- package/dist/parser/types.js +1 -1
- package/dist/parser/types.js.map +1 -1
- package/dist/pipeline/conditions.js +1 -1
- package/dist/pipeline/conditions.js.map +1 -1
- package/dist/pipeline/exclusive.js +58 -4
- package/dist/pipeline/exclusive.js.map +1 -1
- package/dist/pipeline/index.js +4 -5
- package/dist/pipeline/index.js.map +1 -1
- package/dist/pipeline/materialize.js +57 -4
- package/dist/pipeline/materialize.js.map +1 -1
- package/dist/pipeline/parseStateKey.js +5 -6
- package/dist/pipeline/parseStateKey.js.map +1 -1
- package/dist/pipeline/simplify.js +181 -7
- package/dist/pipeline/simplify.js.map +1 -1
- package/dist/pipeline/warnings.js +1 -1
- package/dist/plugins/index.d.ts +2 -0
- package/dist/plugins/okhsl-plugin.js +1 -2
- package/dist/plugins/okhsl-plugin.js.map +1 -1
- package/dist/plugins/types.d.ts +12 -1
- package/dist/properties/index.js +2 -3
- package/dist/properties/index.js.map +1 -1
- package/dist/properties/property-type-resolver.js +1 -2
- package/dist/properties/property-type-resolver.js.map +1 -1
- package/dist/rsc-cache.js +79 -0
- package/dist/rsc-cache.js.map +1 -0
- package/dist/ssr/astro-client.d.ts +1 -0
- package/dist/ssr/astro-client.js +19 -0
- package/dist/ssr/astro-client.js.map +1 -0
- package/dist/ssr/astro-middleware.d.ts +15 -0
- package/dist/ssr/astro-middleware.js +19 -0
- package/dist/ssr/astro-middleware.js.map +1 -0
- package/dist/ssr/astro.d.ts +89 -10
- package/dist/ssr/astro.js +113 -29
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/async-storage.js +15 -6
- package/dist/ssr/async-storage.js.map +1 -1
- package/dist/ssr/collect-auto-properties.js +29 -11
- package/dist/ssr/collect-auto-properties.js.map +1 -1
- package/dist/ssr/collector.d.ts +9 -13
- package/dist/ssr/collector.js +35 -27
- package/dist/ssr/collector.js.map +1 -1
- package/dist/ssr/context.js +4 -2
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/format-global-rules.js +1 -1
- package/dist/ssr/format-keyframes.js +1 -2
- package/dist/ssr/format-keyframes.js.map +1 -1
- package/dist/ssr/format-property.js +1 -2
- package/dist/ssr/format-property.js.map +1 -1
- package/dist/ssr/format-rules.js +1 -1
- package/dist/ssr/hydrate.d.ts +20 -13
- package/dist/ssr/hydrate.js +25 -30
- package/dist/ssr/hydrate.js.map +1 -1
- package/dist/ssr/index.d.ts +3 -4
- package/dist/ssr/index.js +5 -7
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next.d.ts +6 -5
- package/dist/ssr/next.js +14 -10
- package/dist/ssr/next.js.map +1 -1
- package/dist/ssr/ssr-collector-ref.js +20 -3
- package/dist/ssr/ssr-collector-ref.js.map +1 -1
- package/dist/states/index.js +1 -2
- package/dist/states/index.js.map +1 -1
- package/dist/static/index.js +1 -2
- package/dist/static/inject.d.ts +5 -0
- package/dist/static/inject.js +17 -0
- package/dist/static/inject.js.map +1 -0
- package/dist/static/tastyStatic.js +1 -2
- package/dist/static/tastyStatic.js.map +1 -1
- package/dist/static/types.js +1 -1
- package/dist/styles/border.d.ts +1 -1
- package/dist/styles/border.js +28 -22
- package/dist/styles/border.js.map +1 -1
- package/dist/styles/color.d.ts +1 -1
- package/dist/styles/color.js +2 -3
- package/dist/styles/color.js.map +1 -1
- package/dist/styles/const.js +17 -0
- package/dist/styles/const.js.map +1 -0
- package/dist/styles/createStyle.js +4 -5
- package/dist/styles/createStyle.js.map +1 -1
- package/dist/styles/dimension.js +15 -3
- package/dist/styles/dimension.js.map +1 -1
- package/dist/styles/directional.js +133 -0
- package/dist/styles/directional.js.map +1 -0
- package/dist/styles/display.d.ts +3 -10
- package/dist/styles/display.js +45 -39
- package/dist/styles/display.js.map +1 -1
- package/dist/styles/fade.d.ts +1 -1
- package/dist/styles/fade.js +9 -5
- package/dist/styles/fade.js.map +1 -1
- package/dist/styles/fill.d.ts +2 -2
- package/dist/styles/fill.js +3 -4
- package/dist/styles/fill.js.map +1 -1
- package/dist/styles/flow.js +1 -1
- package/dist/styles/gap.d.ts +1 -1
- package/dist/styles/gap.js +4 -3
- package/dist/styles/gap.js.map +1 -1
- package/dist/styles/height.d.ts +1 -1
- package/dist/styles/height.js +1 -2
- package/dist/styles/height.js.map +1 -1
- package/dist/styles/index.d.ts +0 -1
- package/dist/styles/index.js +3 -4
- package/dist/styles/index.js.map +1 -1
- package/dist/styles/inset.d.ts +1 -29
- package/dist/styles/inset.js +19 -135
- package/dist/styles/inset.js.map +1 -1
- package/dist/styles/list.d.ts +5 -5
- package/dist/styles/list.js +4 -2
- package/dist/styles/list.js.map +1 -1
- package/dist/styles/margin.d.ts +1 -1
- package/dist/styles/margin.js +17 -89
- package/dist/styles/margin.js.map +1 -1
- package/dist/styles/outline.d.ts +1 -1
- package/dist/styles/outline.js +6 -16
- package/dist/styles/outline.js.map +1 -1
- package/dist/styles/padding.d.ts +1 -1
- package/dist/styles/padding.js +17 -89
- package/dist/styles/padding.js.map +1 -1
- package/dist/styles/placement.d.ts +37 -0
- package/dist/styles/placement.js +74 -0
- package/dist/styles/placement.js.map +1 -0
- package/dist/styles/predefined.d.ts +4 -4
- package/dist/styles/predefined.js +8 -9
- package/dist/styles/predefined.js.map +1 -1
- package/dist/styles/preset.d.ts +1 -1
- package/dist/styles/preset.js +7 -7
- package/dist/styles/preset.js.map +1 -1
- package/dist/styles/radius.d.ts +1 -3
- package/dist/styles/radius.js +38 -6
- package/dist/styles/radius.js.map +1 -1
- package/dist/styles/scrollMargin.d.ts +24 -0
- package/dist/styles/scrollMargin.js +32 -0
- package/dist/styles/scrollMargin.js.map +1 -0
- package/dist/styles/scrollbar.d.ts +1 -1
- package/dist/styles/scrollbar.js +8 -5
- package/dist/styles/scrollbar.js.map +1 -1
- package/dist/styles/shadow.d.ts +1 -1
- package/dist/styles/shadow.js +4 -3
- package/dist/styles/shadow.js.map +1 -1
- package/dist/styles/shared.js +17 -0
- package/dist/styles/shared.js.map +1 -0
- package/dist/styles/transition.d.ts +1 -1
- package/dist/styles/transition.js +5 -4
- package/dist/styles/transition.js.map +1 -1
- package/dist/styles/types.d.ts +24 -7
- package/dist/styles/width.d.ts +1 -1
- package/dist/styles/width.js +1 -2
- package/dist/styles/width.js.map +1 -1
- package/dist/tasty.d.ts +29 -14
- package/dist/tasty.js +78 -62
- package/dist/tasty.js.map +1 -1
- package/dist/utils/cache-wrapper.js +1 -2
- package/dist/utils/cache-wrapper.js.map +1 -1
- package/dist/utils/case-converter.js +1 -1
- package/dist/utils/color-math.js +1 -1
- package/dist/utils/color-math.js.map +1 -1
- package/dist/utils/color-space.js +1 -2
- package/dist/utils/color-space.js.map +1 -1
- package/dist/utils/colors.js +1 -2
- package/dist/utils/colors.js.map +1 -1
- package/dist/utils/deps-equal.js +15 -0
- package/dist/utils/deps-equal.js.map +1 -0
- package/dist/utils/dotize.js +1 -1
- package/dist/utils/dotize.js.map +1 -1
- package/dist/utils/filter-base-props.d.ts +1 -1
- package/dist/utils/filter-base-props.js +1 -1
- package/dist/utils/filter-base-props.js.map +1 -1
- package/dist/utils/get-display-name.js +1 -1
- package/dist/utils/has-keys.js +1 -1
- package/dist/utils/hash.js +14 -0
- package/dist/utils/hash.js.map +1 -0
- package/dist/utils/is-dev-env.js +1 -1
- package/dist/utils/is-dev-env.js.map +1 -1
- package/dist/utils/is-valid-element-type.js +1 -1
- package/dist/utils/merge-styles.js +1 -2
- package/dist/utils/merge-styles.js.map +1 -1
- package/dist/utils/mod-attrs.d.ts +0 -2
- package/dist/utils/mod-attrs.js +1 -2
- package/dist/utils/mod-attrs.js.map +1 -1
- package/dist/utils/process-tokens.d.ts +1 -5
- package/dist/utils/process-tokens.js +3 -11
- package/dist/utils/process-tokens.js.map +1 -1
- package/dist/utils/resolve-recipes.js +1 -2
- package/dist/utils/resolve-recipes.js.map +1 -1
- package/dist/utils/selector-transform.js +1 -1
- package/dist/utils/string.js +1 -1
- package/dist/utils/styles.d.ts +1 -1
- package/dist/utils/styles.js +2 -3
- package/dist/utils/styles.js.map +1 -1
- package/dist/utils/typography.d.ts +21 -10
- package/dist/utils/typography.js +2 -2
- package/dist/utils/typography.js.map +1 -1
- package/dist/utils/warnings.js +1 -1
- package/dist/zero/babel.d.ts +24 -110
- package/dist/zero/babel.js +130 -42
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/css-writer.js +1 -2
- package/dist/zero/css-writer.js.map +1 -1
- package/dist/zero/extractor.js +1 -2
- package/dist/zero/extractor.js.map +1 -1
- package/dist/zero/index.js +1 -2
- package/dist/zero/next.d.ts +12 -0
- package/dist/zero/next.js +5 -4
- package/dist/zero/next.js.map +1 -1
- package/docs/README.md +2 -2
- package/docs/adoption.md +5 -3
- package/docs/comparison.md +24 -25
- package/docs/configuration.md +69 -1
- package/docs/design-system.md +22 -10
- package/docs/dsl.md +23 -8
- package/docs/getting-started.md +10 -10
- package/docs/injector.md +41 -25
- package/docs/methodology.md +52 -3
- package/docs/{runtime.md → react-api.md} +104 -32
- package/docs/ssr.md +139 -81
- package/docs/styles.md +17 -0
- package/docs/tasty-static.md +101 -2
- package/package.json +20 -9
- package/dist/hooks/resolve-ssr-collector.js +0 -15
- package/dist/hooks/resolve-ssr-collector.js.map +0 -1
- package/dist/ssr/context.d.ts +0 -8
- package/dist/styles/align.d.ts +0 -15
- package/dist/styles/align.js +0 -14
- package/dist/styles/align.js.map +0 -1
- package/dist/styles/justify.d.ts +0 -15
- package/dist/styles/justify.js +0 -14
- package/dist/styles/justify.js.map +0 -1
package/dist/injector/index.js
CHANGED
|
@@ -1,28 +1,14 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "./sheet-manager.js";
|
|
2
2
|
import { StyleInjector } from "./injector.js";
|
|
3
3
|
import { getConfig, getGlobalInjector, isTestEnvironment, markStylesGenerated } from "../config.js";
|
|
4
|
-
|
|
5
4
|
//#region src/injector/index.ts
|
|
6
5
|
/**
|
|
7
|
-
* Allocate a className for a cacheKey without injecting styles yet
|
|
8
|
-
*/
|
|
9
|
-
function allocateClassName(cacheKey, options) {
|
|
10
|
-
return getGlobalInjector().allocateClassName(cacheKey, options);
|
|
11
|
-
}
|
|
12
|
-
/**
|
|
13
|
-
* Track a reference to an already-injected cacheKey (refCount + dispose).
|
|
14
|
-
* Used on cache hits (SSR hydration or runtime reuse) where the pipeline
|
|
15
|
-
* was skipped. Returns null if the cacheKey is not in the cache.
|
|
16
|
-
*/
|
|
17
|
-
function trackRef(cacheKey, options) {
|
|
18
|
-
return getGlobalInjector().trackRef(cacheKey, options);
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
6
|
* Inject styles and return className with dispose function
|
|
22
7
|
*/
|
|
23
8
|
function inject(rules, options) {
|
|
9
|
+
const injector = getGlobalInjector();
|
|
24
10
|
markStylesGenerated();
|
|
25
|
-
return
|
|
11
|
+
return injector.inject(rules, options);
|
|
26
12
|
}
|
|
27
13
|
/**
|
|
28
14
|
* Inject global rules that should not reserve tasty class names
|
|
@@ -133,7 +119,7 @@ function getCssTextForNode(node, options) {
|
|
|
133
119
|
const readClasses = (el) => {
|
|
134
120
|
const cls = el.getAttribute("class");
|
|
135
121
|
if (!cls) return;
|
|
136
|
-
for (const token of cls.split(/\s+/)) if (/^t
|
|
122
|
+
for (const token of cls.split(/\s+/)) if (/^t[a-z0-9]+$/.test(token)) classSet.add(token);
|
|
137
123
|
};
|
|
138
124
|
if (node.getAttribute) readClasses(node);
|
|
139
125
|
const elements = node.querySelectorAll ? node.querySelectorAll("[class]") : [];
|
|
@@ -147,6 +133,25 @@ function cleanup(root) {
|
|
|
147
133
|
return getGlobalInjector().cleanup(root);
|
|
148
134
|
}
|
|
149
135
|
/**
|
|
136
|
+
* Record a render-time usage hit for one or more classNames.
|
|
137
|
+
* Used internally by computeStyles and tasty() to track usage for GC.
|
|
138
|
+
* When the global touch counter reaches `touchInterval`, schedules GC.
|
|
139
|
+
*/
|
|
140
|
+
function touch(className, options) {
|
|
141
|
+
if (!getConfig().gc) return;
|
|
142
|
+
getGlobalInjector().touch(className, options);
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Synchronous garbage collection of unused styles.
|
|
146
|
+
* Evicts the oldest unused styles when usageMap exceeds capacity.
|
|
147
|
+
* With `{ force: true }`, removes ALL unused styles regardless of capacity.
|
|
148
|
+
*
|
|
149
|
+
* @returns Number of styles evicted.
|
|
150
|
+
*/
|
|
151
|
+
function gc(options) {
|
|
152
|
+
return getGlobalInjector().gc(options);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
150
155
|
* Check if we're currently running in a test environment
|
|
151
156
|
*/
|
|
152
157
|
function getIsTestEnvironment() {
|
|
@@ -174,7 +179,7 @@ function createInjector(config = {}) {
|
|
|
174
179
|
...config
|
|
175
180
|
});
|
|
176
181
|
}
|
|
177
|
-
|
|
178
182
|
//#endregion
|
|
179
|
-
export {
|
|
183
|
+
export { cleanup, counterStyle, createInjector, destroy, fontFace, gc, getCssText, getCssTextForNode, getIsTestEnvironment, getRawCSSText, inject, injectGlobal, injectRawCSS, injector, isPropertyDefined, keyframes, property, touch };
|
|
184
|
+
|
|
180
185
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/injector/index.ts"],"sourcesContent":["import {\n getConfig,\n getGlobalInjector,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Allocate a className for a cacheKey without injecting styles yet\n */\nexport function allocateClassName(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n): { className: string; isNewAllocation: boolean } {\n return getGlobalInjector().allocateClassName(cacheKey, options);\n}\n\n/**\n * Track a reference to an already-injected cacheKey (refCount + dispose).\n * Used on cache hits (SSR hydration or runtime reuse) where the pipeline\n * was skipped. Returns null if the cacheKey is not in the cache.\n */\nexport function trackRef(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n): InjectResult | null {\n return getGlobalInjector().trackRef(cacheKey, options);\n}\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n): InjectResult {\n // Mark that styles have been generated (prevents configuration changes)\n markStylesGenerated();\n\n return getGlobalInjector().inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\nexport interface PropertyOptions {\n /**\n * CSS syntax string for the property (e.g., '<color>', '<length>', '<angle>')\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@property/syntax\n */\n syntax?: string;\n /**\n * Whether the property inherits from parent elements\n * @default true\n */\n inherits?: boolean;\n /**\n * Initial value for the property\n */\n initialValue?: string | number;\n /**\n * Shadow root or document to inject into\n */\n root?: Document | ShadowRoot;\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by name (first definition wins).\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCssText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCssText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCssTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names (t<number>) from the subtree\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (/^t\\d+$/.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCssTextForClasses(classSet, options);\n}\n\n/**\n * Force cleanup of unused rules\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Check if we're currently running in a test environment\n */\nexport function getIsTestEnvironment(): boolean {\n return isTestEnvironment();\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n} from './types';\n\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\n"],"mappings":";;;;;;;;AAsBA,SAAgB,kBACd,UACA,SACiD;AACjD,QAAO,mBAAmB,CAAC,kBAAkB,UAAU,QAAQ;;;;;;;AAQjE,SAAgB,SACd,UACA,SACqB;AACrB,QAAO,mBAAmB,CAAC,SAAS,UAAU,QAAQ;;;;;AAMxD,SAAgB,OACd,OACA,SACc;AAEd,sBAAqB;AAErB,QAAO,mBAAmB,CAAC,OAAO,OAAO,QAAQ;;;;;AAMnD,SAAgB,aACd,OACA,SACoB;AACpB,QAAO,mBAAmB,CAAC,aAAa,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;AAoBzD,SAAgB,aACd,KACA,SACyB;AACzB,QAAO,mBAAmB,CAAC,aAAa,KAAK,QAAQ;;;;;AAMvD,SAAgB,cAAc,SAEnB;AACT,QAAO,mBAAmB,CAAC,cAAc,QAAQ;;;;;AAMnD,SAAgB,UACd,OACA,eACiB;AACjB,QAAO,mBAAmB,CAAC,UAAU,OAAO,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,SAAgB,SAAS,MAAc,SAAiC;AACtE,QAAO,mBAAmB,CAAC,SAAS,MAAM,QAAQ;;;;;;;;AASpD,SAAgB,kBACd,MACA,SACS;AACT,QAAO,mBAAmB,CAAC,kBAAkB,MAAM,QAAQ;;;;;;;;AAS7D,SAAgB,SACd,QACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,SAAS,QAAQ,aAAa,QAAQ;;;;;;;;AASnE,SAAgB,aACd,MACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,aAAa,MAAM,aAAa,QAAQ;;;;;AAMrE,SAAgB,WAAW,SAAoD;AAC7E,QAAO,mBAAmB,CAAC,WAAW,QAAQ;;;;;;AAOhD,SAAgB,kBACd,MACA,SACQ;CAER,MAAM,2BAAW,IAAI,KAAa;CAElC,MAAM,eAAe,OAAgB;EACnC,MAAM,MAAM,GAAG,aAAa,QAAQ;AACpC,MAAI,CAAC,IAAK;AACV,OAAK,MAAM,SAAS,IAAI,MAAM,MAAM,CAClC,KAAI,SAAS,KAAK,MAAM,CAAE,UAAS,IAAI,MAAM;;AAKjD,KAAK,KAAiB,aACpB,aAAY,KAAgB;CAG9B,MAAM,WAAY,KAAoB,mBACjC,KAAoB,iBAAiB,UAAU,GAC/C,EAAE;AACP,KAAI,SAAU,UAAS,QAAQ,YAAY;AAE3C,QAAO,mBAAmB,CAAC,qBAAqB,UAAU,QAAQ;;;;;AAMpE,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,uBAAgC;AAC9C,QAAO,mBAAmB;;;;;AAM5B,MAAa,WAAW,EACtB,IAAI,WAAW;AACb,QAAO,mBAAmB;GAE7B;;;;AAKD,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,eACd,SAAuC,EAAE,EAC1B;AAUf,QAAO,IAAI,cAP6B;EACtC,GAHoB,WAAW;EAK/B,oBAAoB,OAAO,sBAAsB,mBAAmB;EACpE,GAAG;EACJ,CAEmC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/injector/index.ts"],"sourcesContent":["import {\n getConfig,\n getGlobalInjector,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n GCOptions,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n): InjectResult {\n const injector = getGlobalInjector();\n\n markStylesGenerated();\n\n return injector.inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\nexport interface PropertyOptions {\n /**\n * CSS syntax string for the property (e.g., '<color>', '<length>', '<angle>')\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@property/syntax\n */\n syntax?: string;\n /**\n * Whether the property inherits from parent elements\n * @default true\n */\n inherits?: boolean;\n /**\n * Initial value for the property\n */\n initialValue?: string | number;\n /**\n * Shadow root or document to inject into\n */\n root?: Document | ShadowRoot;\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by name (first definition wins).\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCssText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCssText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCssTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names (t<number>) from the subtree\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (/^t[a-z0-9]+$/.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCssTextForClasses(classSet, options);\n}\n\n/**\n * Force cleanup of unused rules\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Record a render-time usage hit for one or more classNames.\n * Used internally by computeStyles and tasty() to track usage for GC.\n * When the global touch counter reaches `touchInterval`, schedules GC.\n */\nexport function touch(\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n if (!getConfig().gc) return;\n getGlobalInjector().touch(className, options);\n}\n\n/**\n * Synchronous garbage collection of unused styles.\n * Evicts the oldest unused styles when usageMap exceeds capacity.\n * With `{ force: true }`, removes ALL unused styles regardless of capacity.\n *\n * @returns Number of styles evicted.\n */\nexport function gc(options?: GCOptions): number {\n return getGlobalInjector().gc(options);\n}\n\n/**\n * Check if we're currently running in a test environment\n */\nexport function getIsTestEnvironment(): boolean {\n return isTestEnvironment();\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n StyleUsage,\n GCConfig,\n GCOptions,\n} from './types';\n\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\n"],"mappings":";;;;;;;AAuBA,SAAgB,OACd,OACA,SACc;CACd,MAAM,WAAW,mBAAmB;AAEpC,sBAAqB;AAErB,QAAO,SAAS,OAAO,OAAO,QAAQ;;;;;AAMxC,SAAgB,aACd,OACA,SACoB;AACpB,QAAO,mBAAmB,CAAC,aAAa,OAAO,QAAQ;;;;;;;;;;;;;;;;;;;AAoBzD,SAAgB,aACd,KACA,SACyB;AACzB,QAAO,mBAAmB,CAAC,aAAa,KAAK,QAAQ;;;;;AAMvD,SAAgB,cAAc,SAEnB;AACT,QAAO,mBAAmB,CAAC,cAAc,QAAQ;;;;;AAMnD,SAAgB,UACd,OACA,eACiB;AACjB,QAAO,mBAAmB,CAAC,UAAU,OAAO,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkD5D,SAAgB,SAAS,MAAc,SAAiC;AACtE,QAAO,mBAAmB,CAAC,SAAS,MAAM,QAAQ;;;;;;;;AASpD,SAAgB,kBACd,MACA,SACS;AACT,QAAO,mBAAmB,CAAC,kBAAkB,MAAM,QAAQ;;;;;;;;AAS7D,SAAgB,SACd,QACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,SAAS,QAAQ,aAAa,QAAQ;;;;;;;;AASnE,SAAgB,aACd,MACA,aACA,SACM;AACN,QAAO,mBAAmB,CAAC,aAAa,MAAM,aAAa,QAAQ;;;;;AAMrE,SAAgB,WAAW,SAAoD;AAC7E,QAAO,mBAAmB,CAAC,WAAW,QAAQ;;;;;;AAOhD,SAAgB,kBACd,MACA,SACQ;CAER,MAAM,2BAAW,IAAI,KAAa;CAElC,MAAM,eAAe,OAAgB;EACnC,MAAM,MAAM,GAAG,aAAa,QAAQ;AACpC,MAAI,CAAC,IAAK;AACV,OAAK,MAAM,SAAS,IAAI,MAAM,MAAM,CAClC,KAAI,eAAe,KAAK,MAAM,CAAE,UAAS,IAAI,MAAM;;AAKvD,KAAK,KAAiB,aACpB,aAAY,KAAgB;CAG9B,MAAM,WAAY,KAAoB,mBACjC,KAAoB,iBAAiB,UAAU,GAC/C,EAAE;AACP,KAAI,SAAU,UAAS,QAAQ,YAAY;AAE3C,QAAO,mBAAmB,CAAC,qBAAqB,UAAU,QAAQ;;;;;AAMpE,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;;;AAQ1C,SAAgB,MACd,WACA,SACM;AACN,KAAI,CAAC,WAAW,CAAC,GAAI;AACrB,oBAAmB,CAAC,MAAM,WAAW,QAAQ;;;;;;;;;AAU/C,SAAgB,GAAG,SAA6B;AAC9C,QAAO,mBAAmB,CAAC,GAAG,QAAQ;;;;;AAMxC,SAAgB,uBAAgC;AAC9C,QAAO,mBAAmB;;;;;AAM5B,MAAa,WAAW,EACtB,IAAI,WAAW;AACb,QAAO,mBAAmB;GAE7B;;;;AAKD,SAAgB,QAAQ,MAAoC;AAC1D,QAAO,mBAAmB,CAAC,QAAQ,KAAK;;;;;AAM1C,SAAgB,eACd,SAAuC,EAAE,EAC1B;AAUf,QAAO,IAAI,cAP6B;EACtC,GAHoB,WAAW;EAK/B,oBAAoB,OAAO,sBAAsB,mBAAmB;EACpE,GAAG;EACJ,CAEmC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CacheMetrics, CounterStyleDescriptors, FontFaceDescriptors, GlobalInjectResult, InjectResult, KeyframesResult, KeyframesSteps, PropertyDefinition, RawCSSResult, StyleInjectorConfig } from "./types.js";
|
|
1
|
+
import { CacheMetrics, CounterStyleDescriptors, FontFaceDescriptors, GCOptions, GlobalInjectResult, InjectResult, KeyframesResult, KeyframesSteps, PropertyDefinition, RawCSSResult, StyleInjectorConfig } from "./types.js";
|
|
2
2
|
import { StyleResult } from "../pipeline/index.js";
|
|
3
3
|
import { SheetManager } from "./sheet-manager.js";
|
|
4
4
|
|
|
@@ -6,11 +6,16 @@ import { SheetManager } from "./sheet-manager.js";
|
|
|
6
6
|
declare class StyleInjector {
|
|
7
7
|
private sheetManager;
|
|
8
8
|
private config;
|
|
9
|
-
private cleanupScheduled;
|
|
10
9
|
private globalRuleCounter;
|
|
10
|
+
private pendingGCHandle;
|
|
11
11
|
/** @internal — exposed for debug utilities only */
|
|
12
12
|
get _sheetManager(): SheetManager;
|
|
13
13
|
constructor(config?: StyleInjectorConfig);
|
|
14
|
+
/**
|
|
15
|
+
* Check if `className` was hydrated from server-rendered styles and,
|
|
16
|
+
* if so, wire the cacheKey mapping. Returns true on hit.
|
|
17
|
+
*/
|
|
18
|
+
private tryHydratedHit;
|
|
14
19
|
/**
|
|
15
20
|
* Allocate a className for a cacheKey without injecting styles yet.
|
|
16
21
|
* This allows separating className allocation (render phase) from style injection (insertion phase).
|
|
@@ -60,7 +65,7 @@ declare class StyleInjector {
|
|
|
60
65
|
root?: Document | ShadowRoot;
|
|
61
66
|
}): InjectResult | null;
|
|
62
67
|
/**
|
|
63
|
-
* Dispose of a className
|
|
68
|
+
* Dispose of a className (decrements refCount only).
|
|
64
69
|
*/
|
|
65
70
|
private dispose;
|
|
66
71
|
/**
|
|
@@ -156,6 +161,33 @@ declare class StyleInjector {
|
|
|
156
161
|
* Dispose keyframes
|
|
157
162
|
*/
|
|
158
163
|
private disposeKeyframes;
|
|
164
|
+
private static readonly TASTY_CLASS_RE;
|
|
165
|
+
/**
|
|
166
|
+
* Record a render-time usage hit for one or more classNames.
|
|
167
|
+
* Handles space-separated multi-chunk classNames.
|
|
168
|
+
* When the global touch counter reaches `touchInterval`, schedules a GC
|
|
169
|
+
* via `requestIdleCallback`.
|
|
170
|
+
* No-op on the server.
|
|
171
|
+
*/
|
|
172
|
+
touch(className: string, options?: {
|
|
173
|
+
root?: Document | ShadowRoot;
|
|
174
|
+
}): void;
|
|
175
|
+
/**
|
|
176
|
+
* Schedule a GC via `requestIdleCallback` (or synchronously as fallback).
|
|
177
|
+
* Runs GC on all active roots. Avoids double-scheduling via `pendingGCHandle`.
|
|
178
|
+
*/
|
|
179
|
+
private scheduleGC;
|
|
180
|
+
/**
|
|
181
|
+
* Synchronous garbage collection.
|
|
182
|
+
*
|
|
183
|
+
* 1. Quick upper-bound check: skip if unused count can't exceed capacity.
|
|
184
|
+
* 2. Scans the DOM for live tasty classNames (safety guard).
|
|
185
|
+
* 3. With `force: true`: deletes all unused entries inline.
|
|
186
|
+
* Without `force`: collects unused, sorts oldest-first, evicts over capacity.
|
|
187
|
+
*
|
|
188
|
+
* @returns Number of styles evicted.
|
|
189
|
+
*/
|
|
190
|
+
gc(options?: GCOptions): number;
|
|
159
191
|
/**
|
|
160
192
|
* Destroy all resources for a root
|
|
161
193
|
*/
|
|
@@ -1,22 +1,73 @@
|
|
|
1
1
|
import { getEffectiveDefinition, normalizePropertyDefinition } from "../properties/index.js";
|
|
2
|
+
import { hashString } from "../utils/hash.js";
|
|
2
3
|
import { isDevEnv } from "../utils/is-dev-env.js";
|
|
3
4
|
import { parseStyle } from "../utils/styles.js";
|
|
4
5
|
import { SheetManager } from "./sheet-manager.js";
|
|
5
6
|
import { fontFaceContentHash, formatFontFaceDeclarations } from "../font-face/index.js";
|
|
6
7
|
import { formatCounterStyleDeclarations } from "../counter-style/index.js";
|
|
7
|
-
|
|
8
8
|
//#region src/injector/injector.ts
|
|
9
9
|
/**
|
|
10
|
-
* Generate
|
|
10
|
+
* Generate a deterministic class name from a cache key using content hash.
|
|
11
|
+
* The same cache key always produces the same class name across environments.
|
|
12
|
+
*/
|
|
13
|
+
function generateClassName(cacheKey) {
|
|
14
|
+
return `t${hashString(cacheKey)}`;
|
|
15
|
+
}
|
|
16
|
+
const RSC_CLASS_RE = /\.(t[a-z0-9]+)\.\1/g;
|
|
17
|
+
/**
|
|
18
|
+
* Extract class names from `<style data-tasty-rsc>` tags.
|
|
19
|
+
* The doubled-specificity pattern `.tXXX.tXXX` makes extraction reliable.
|
|
11
20
|
*/
|
|
12
|
-
function
|
|
13
|
-
return
|
|
21
|
+
function extractRSCClassNames() {
|
|
22
|
+
if (typeof document === "undefined") return [];
|
|
23
|
+
const styles = document.querySelectorAll("style[data-tasty-rsc]");
|
|
24
|
+
if (styles.length === 0) return [];
|
|
25
|
+
const classSet = /* @__PURE__ */ new Set();
|
|
26
|
+
for (const style of styles) {
|
|
27
|
+
const text = style.textContent;
|
|
28
|
+
if (!text) continue;
|
|
29
|
+
let match;
|
|
30
|
+
RSC_CLASS_RE.lastIndex = 0;
|
|
31
|
+
while ((match = RSC_CLASS_RE.exec(text)) !== null) classSet.add(match[1]);
|
|
32
|
+
}
|
|
33
|
+
return Array.from(classSet);
|
|
14
34
|
}
|
|
15
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Lazily sync server-rendered class names into the client registry.
|
|
37
|
+
*
|
|
38
|
+
* Sources:
|
|
39
|
+
* 1. `window.__TASTY__` — pushed by SSR/RSC streaming scripts
|
|
40
|
+
* 2. `<style data-tasty-rsc>` tags — inline CSS emitted by RSC components
|
|
41
|
+
*
|
|
42
|
+
* Called inside `inject()` / `allocateClassName()` to pick up
|
|
43
|
+
* class names rendered on the server (including during SPA navigation).
|
|
44
|
+
*/
|
|
45
|
+
function syncServerClasses(registry) {
|
|
46
|
+
if (typeof window === "undefined") return;
|
|
47
|
+
const classes = window.__TASTY__;
|
|
48
|
+
if (classes && classes.length > registry.serverClassSyncIndex) {
|
|
49
|
+
for (let i = registry.serverClassSyncIndex; i < classes.length; i++) registerHydratedClass(registry, classes[i]);
|
|
50
|
+
registry.serverClassSyncIndex = classes.length;
|
|
51
|
+
}
|
|
52
|
+
if (!registry.rscStylesScanned) {
|
|
53
|
+
registry.rscStylesScanned = true;
|
|
54
|
+
for (const cls of extractRSCClassNames()) registerHydratedClass(registry, cls);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function registerHydratedClass(registry, className) {
|
|
58
|
+
if (registry.rules.has(className)) return;
|
|
59
|
+
registry.rules.set(className, {
|
|
60
|
+
className,
|
|
61
|
+
ruleIndex: -2,
|
|
62
|
+
sheetIndex: -2
|
|
63
|
+
});
|
|
64
|
+
registry.refCounts.set(className, 0);
|
|
65
|
+
}
|
|
66
|
+
var StyleInjector = class StyleInjector {
|
|
16
67
|
sheetManager;
|
|
17
68
|
config;
|
|
18
|
-
cleanupScheduled = false;
|
|
19
69
|
globalRuleCounter = 0;
|
|
70
|
+
pendingGCHandle = null;
|
|
20
71
|
/** @internal — exposed for debug utilities only */
|
|
21
72
|
get _sheetManager() {
|
|
22
73
|
return this.sheetManager;
|
|
@@ -26,6 +77,19 @@ var StyleInjector = class {
|
|
|
26
77
|
this.sheetManager = new SheetManager(config);
|
|
27
78
|
}
|
|
28
79
|
/**
|
|
80
|
+
* Check if `className` was hydrated from server-rendered styles and,
|
|
81
|
+
* if so, wire the cacheKey mapping. Returns true on hit.
|
|
82
|
+
*/
|
|
83
|
+
tryHydratedHit(registry, cacheKey, className) {
|
|
84
|
+
syncServerClasses(registry);
|
|
85
|
+
const rule = registry.rules.get(className);
|
|
86
|
+
if (rule && rule.ruleIndex === -2 && rule.sheetIndex === -2) {
|
|
87
|
+
registry.cacheKeyToClassName.set(cacheKey, className);
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
29
93
|
* Allocate a className for a cacheKey without injecting styles yet.
|
|
30
94
|
* This allows separating className allocation (render phase) from style injection (insertion phase).
|
|
31
95
|
*/
|
|
@@ -36,7 +100,19 @@ var StyleInjector = class {
|
|
|
36
100
|
className: registry.cacheKeyToClassName.get(cacheKey),
|
|
37
101
|
isNewAllocation: false
|
|
38
102
|
};
|
|
39
|
-
const className = generateClassName(
|
|
103
|
+
const className = generateClassName(cacheKey);
|
|
104
|
+
if (this.tryHydratedHit(registry, cacheKey, className)) return {
|
|
105
|
+
className,
|
|
106
|
+
isNewAllocation: false
|
|
107
|
+
};
|
|
108
|
+
if (registry.rules.get(className)) {
|
|
109
|
+
if (isDevEnv()) console.warn(`[tasty] Hash collision: cache keys produce the same class "${className}". Styles may be incorrect.`);
|
|
110
|
+
registry.cacheKeyToClassName.set(cacheKey, className);
|
|
111
|
+
return {
|
|
112
|
+
className,
|
|
113
|
+
isNewAllocation: false
|
|
114
|
+
};
|
|
115
|
+
}
|
|
40
116
|
const placeholderRuleInfo = {
|
|
41
117
|
className,
|
|
42
118
|
ruleIndex: -1,
|
|
@@ -75,7 +151,17 @@ var StyleInjector = class {
|
|
|
75
151
|
dispose: () => this.dispose(className, registry)
|
|
76
152
|
};
|
|
77
153
|
}
|
|
78
|
-
} else
|
|
154
|
+
} else if (cacheKey) {
|
|
155
|
+
className = generateClassName(cacheKey);
|
|
156
|
+
if (this.tryHydratedHit(registry, cacheKey, className)) {
|
|
157
|
+
registry.refCounts.set(className, (registry.refCounts.get(className) || 0) + 1);
|
|
158
|
+
if (registry.metrics) registry.metrics.hits++;
|
|
159
|
+
return {
|
|
160
|
+
className,
|
|
161
|
+
dispose: () => this.dispose(className, registry)
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
} else className = `t${hashString(rules.map((r) => `${r.selector}\0${r.declarations}`).join("\n"))}`;
|
|
79
165
|
const rulesToInsert = rules.map((rule) => {
|
|
80
166
|
let newSelector = rule.selector;
|
|
81
167
|
if (rule.needsClassName) {
|
|
@@ -199,17 +285,14 @@ var StyleInjector = class {
|
|
|
199
285
|
};
|
|
200
286
|
}
|
|
201
287
|
/**
|
|
202
|
-
* Dispose of a className
|
|
288
|
+
* Dispose of a className (decrements refCount only).
|
|
203
289
|
*/
|
|
204
290
|
dispose(className, registry) {
|
|
205
291
|
const currentRefCount = registry.refCounts.get(className);
|
|
206
292
|
if (currentRefCount == null || currentRefCount <= 0) return;
|
|
207
293
|
const newRefCount = currentRefCount - 1;
|
|
208
294
|
registry.refCounts.set(className, newRefCount);
|
|
209
|
-
if (newRefCount === 0)
|
|
210
|
-
if (registry.metrics) registry.metrics.totalUnused++;
|
|
211
|
-
this.sheetManager.checkCleanupNeeded(registry);
|
|
212
|
-
}
|
|
295
|
+
if (newRefCount === 0 && registry.metrics) registry.metrics.totalUnused++;
|
|
213
296
|
}
|
|
214
297
|
/**
|
|
215
298
|
* Force bulk cleanup of unused styles
|
|
@@ -451,15 +534,118 @@ var StyleInjector = class {
|
|
|
451
534
|
}
|
|
452
535
|
}
|
|
453
536
|
}
|
|
537
|
+
static TASTY_CLASS_RE = /^t[a-z0-9]+$/;
|
|
538
|
+
/**
|
|
539
|
+
* Record a render-time usage hit for one or more classNames.
|
|
540
|
+
* Handles space-separated multi-chunk classNames.
|
|
541
|
+
* When the global touch counter reaches `touchInterval`, schedules a GC
|
|
542
|
+
* via `requestIdleCallback`.
|
|
543
|
+
* No-op on the server.
|
|
544
|
+
*/
|
|
545
|
+
touch(className, options) {
|
|
546
|
+
if (typeof document === "undefined") return;
|
|
547
|
+
if (!this.config.gc) return;
|
|
548
|
+
const root = options?.root || document;
|
|
549
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
550
|
+
const now = Date.now();
|
|
551
|
+
const parts = className.indexOf(" ") === -1 ? [className] : className.split(" ");
|
|
552
|
+
for (const cls of parts) {
|
|
553
|
+
if (!StyleInjector.TASTY_CLASS_RE.test(cls)) continue;
|
|
554
|
+
if (!registry.rules.has(cls)) continue;
|
|
555
|
+
const entry = registry.usageMap.get(cls);
|
|
556
|
+
if (entry) entry.lastTouchedAt = now;
|
|
557
|
+
else registry.usageMap.set(cls, { lastTouchedAt: now });
|
|
558
|
+
registry.touchCount++;
|
|
559
|
+
}
|
|
560
|
+
const touchInterval = this.config.gc.touchInterval ?? 1e3;
|
|
561
|
+
if (registry.touchCount >= touchInterval) {
|
|
562
|
+
registry.touchCount = 0;
|
|
563
|
+
this.scheduleGC();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Schedule a GC via `requestIdleCallback` (or synchronously as fallback).
|
|
568
|
+
* Runs GC on all active roots. Avoids double-scheduling via `pendingGCHandle`.
|
|
569
|
+
*/
|
|
570
|
+
scheduleGC() {
|
|
571
|
+
if (this.pendingGCHandle != null) return;
|
|
572
|
+
const runGC = () => {
|
|
573
|
+
this.pendingGCHandle = null;
|
|
574
|
+
this.sheetManager.pruneDisconnectedRoots();
|
|
575
|
+
for (const root of this.sheetManager.getActiveRoots()) this.gc({ root });
|
|
576
|
+
};
|
|
577
|
+
if (typeof requestIdleCallback !== "undefined") this.pendingGCHandle = requestIdleCallback(() => runGC());
|
|
578
|
+
else runGC();
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Synchronous garbage collection.
|
|
582
|
+
*
|
|
583
|
+
* 1. Quick upper-bound check: skip if unused count can't exceed capacity.
|
|
584
|
+
* 2. Scans the DOM for live tasty classNames (safety guard).
|
|
585
|
+
* 3. With `force: true`: deletes all unused entries inline.
|
|
586
|
+
* Without `force`: collects unused, sorts oldest-first, evicts over capacity.
|
|
587
|
+
*
|
|
588
|
+
* @returns Number of styles evicted.
|
|
589
|
+
*/
|
|
590
|
+
gc(options) {
|
|
591
|
+
if (typeof document === "undefined") return 0;
|
|
592
|
+
if (this.pendingGCHandle != null) {
|
|
593
|
+
if (typeof cancelIdleCallback !== "undefined") cancelIdleCallback(this.pendingGCHandle);
|
|
594
|
+
this.pendingGCHandle = null;
|
|
595
|
+
}
|
|
596
|
+
const root = options?.root || document;
|
|
597
|
+
const force = options?.force ?? false;
|
|
598
|
+
const registry = this.sheetManager.getRegistry(root);
|
|
599
|
+
const capacity = this.config.gc?.capacity ?? 1e3;
|
|
600
|
+
if (!force) {
|
|
601
|
+
let activeCount = 0;
|
|
602
|
+
for (const refCount of registry.refCounts.values()) if (refCount > 0) activeCount++;
|
|
603
|
+
if (registry.usageMap.size - activeCount <= capacity) return 0;
|
|
604
|
+
}
|
|
605
|
+
const liveClasses = /* @__PURE__ */ new Set();
|
|
606
|
+
for (const el of root.querySelectorAll("[class]")) for (const token of el.classList) if (StyleInjector.TASTY_CLASS_RE.test(token)) liveClasses.add(token);
|
|
607
|
+
let swept = 0;
|
|
608
|
+
if (force) for (const [className] of registry.usageMap) {
|
|
609
|
+
if (liveClasses.has(className)) continue;
|
|
610
|
+
if ((registry.refCounts.get(className) ?? 0) > 0) continue;
|
|
611
|
+
registry.usageMap.delete(className);
|
|
612
|
+
swept++;
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
const unused = [];
|
|
616
|
+
for (const [className, usage] of registry.usageMap) {
|
|
617
|
+
if (liveClasses.has(className)) continue;
|
|
618
|
+
if ((registry.refCounts.get(className) ?? 0) > 0) continue;
|
|
619
|
+
unused.push({
|
|
620
|
+
className,
|
|
621
|
+
lastTouchedAt: usage.lastTouchedAt
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
if (unused.length > capacity) {
|
|
625
|
+
unused.sort((a, b) => a.lastTouchedAt - b.lastTouchedAt);
|
|
626
|
+
const toEvict = unused.length - capacity;
|
|
627
|
+
for (let i = 0; i < toEvict; i++) {
|
|
628
|
+
registry.usageMap.delete(unused[i].className);
|
|
629
|
+
swept++;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (swept > 0) this.sheetManager.forceCleanup(registry);
|
|
634
|
+
return swept;
|
|
635
|
+
}
|
|
454
636
|
/**
|
|
455
637
|
* Destroy all resources for a root
|
|
456
638
|
*/
|
|
457
639
|
destroy(root) {
|
|
458
640
|
const targetRoot = root || document;
|
|
459
641
|
this.sheetManager.cleanup(targetRoot);
|
|
642
|
+
if (this.pendingGCHandle != null && !this.sheetManager.hasActiveRoots()) {
|
|
643
|
+
if (typeof cancelIdleCallback !== "undefined") cancelIdleCallback(this.pendingGCHandle);
|
|
644
|
+
this.pendingGCHandle = null;
|
|
645
|
+
}
|
|
460
646
|
}
|
|
461
647
|
};
|
|
462
|
-
|
|
463
648
|
//#endregion
|
|
464
649
|
export { StyleInjector };
|
|
650
|
+
|
|
465
651
|
//# sourceMappingURL=injector.js.map
|