nitrowind 0.0.0-stage → 0.1.1
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/CHANGELOG.md +29 -0
- package/LICENSE +21 -0
- package/README.md +51 -2
- package/css.d.ts +6 -0
- package/dist/color.d.ts +24 -0
- package/dist/color.d.ts.map +1 -0
- package/dist/color.js +158 -0
- package/dist/color.js.map +1 -0
- package/dist/core.d.ts +121 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +1026 -0
- package/dist/core.js.map +1 -0
- package/dist/css/compile.d.ts +18 -0
- package/dist/css/compile.d.ts.map +1 -0
- package/dist/css/compile.js +1018 -0
- package/dist/css/compile.js.map +1 -0
- package/dist/css/declarations.d.ts +18 -0
- package/dist/css/declarations.d.ts.map +1 -0
- package/dist/css/declarations.js +1173 -0
- package/dist/css/declarations.js.map +1 -0
- package/dist/css/index.d.ts +7 -0
- package/dist/css/index.d.ts.map +1 -0
- package/dist/css/index.js +7 -0
- package/dist/css/index.js.map +1 -0
- package/dist/css/parser.d.ts +9 -0
- package/dist/css/parser.d.ts.map +1 -0
- package/dist/css/parser.js +188 -0
- package/dist/css/parser.js.map +1 -0
- package/dist/css/tokenizer.d.ts +14 -0
- package/dist/css/tokenizer.d.ts.map +1 -0
- package/dist/css/tokenizer.js +200 -0
- package/dist/css/tokenizer.js.map +1 -0
- package/dist/css/types.d.ts +128 -0
- package/dist/css/types.d.ts.map +1 -0
- package/dist/css/types.js +19 -0
- package/dist/css/types.js.map +1 -0
- package/dist/css/values.d.ts +37 -0
- package/dist/css/values.d.ts.map +1 -0
- package/dist/css/values.js +343 -0
- package/dist/css/values.js.map +1 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.d.ts.map +1 -0
- package/dist/environment.js +99 -0
- package/dist/environment.js.map +1 -0
- package/dist/hooks.d.ts +22 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +140 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/jsx-dev-runtime.d.ts +17 -0
- package/dist/jsx-dev-runtime.d.ts.map +1 -0
- package/dist/jsx-dev-runtime.js +12 -0
- package/dist/jsx-dev-runtime.js.map +1 -0
- package/dist/jsx-namespace.d.ts +29 -0
- package/dist/jsx-namespace.d.ts.map +1 -0
- package/dist/jsx-namespace.js +2 -0
- package/dist/jsx-namespace.js.map +1 -0
- package/dist/jsx-runtime.d.ts +22 -0
- package/dist/jsx-runtime.d.ts.map +1 -0
- package/dist/jsx-runtime.js +21 -0
- package/dist/jsx-runtime.js.map +1 -0
- package/dist/math.d.ts +50 -0
- package/dist/math.d.ts.map +1 -0
- package/dist/math.js +442 -0
- package/dist/math.js.map +1 -0
- package/dist/plugin.d.ts +45 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +172 -0
- package/dist/plugin.js.map +1 -0
- package/dist/props.d.ts +29 -0
- package/dist/props.d.ts.map +1 -0
- package/dist/props.js +163 -0
- package/dist/props.js.map +1 -0
- package/dist/scope.d.ts +99 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +228 -0
- package/dist/scope.js.map +1 -0
- package/dist/store.d.ts +18 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +244 -0
- package/dist/store.js.map +1 -0
- package/dist/tokens/index.d.ts +12 -0
- package/dist/tokens/index.d.ts.map +1 -0
- package/dist/tokens/index.js +237 -0
- package/dist/tokens/index.js.map +1 -0
- package/dist/tokens/tailwind.generated.d.ts +3 -0
- package/dist/tokens/tailwind.generated.d.ts.map +1 -0
- package/dist/tokens/tailwind.generated.js +610 -0
- package/dist/tokens/tailwind.generated.js.map +1 -0
- package/dist/tokens/types.d.ts +95 -0
- package/dist/tokens/types.d.ts.map +1 -0
- package/dist/tokens/types.js +2 -0
- package/dist/tokens/types.js.map +1 -0
- package/dist/transform.d.ts +22 -0
- package/dist/transform.d.ts.map +1 -0
- package/dist/transform.js +79 -0
- package/dist/transform.js.map +1 -0
- package/dist/transition.d.ts +7 -0
- package/dist/transition.d.ts.map +1 -0
- package/dist/transition.js +355 -0
- package/dist/transition.js.map +1 -0
- package/dist/types.d.ts +214 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utilities.d.ts +109 -0
- package/dist/utilities.d.ts.map +1 -0
- package/dist/utilities.js +2000 -0
- package/dist/utilities.js.map +1 -0
- package/dist/variables.d.ts +65 -0
- package/dist/variables.d.ts.map +1 -0
- package/dist/variables.js +408 -0
- package/dist/variables.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/dist/withNitroWind.d.ts +11 -0
- package/dist/withNitroWind.d.ts.map +1 -0
- package/dist/withNitroWind.js +27 -0
- package/dist/withNitroWind.js.map +1 -0
- package/package.json +89 -4
- package/src/color.ts +164 -0
- package/src/core.ts +1248 -0
- package/src/css/compile.ts +1198 -0
- package/src/css/declarations.ts +1141 -0
- package/src/css/index.ts +22 -0
- package/src/css/parser.ts +196 -0
- package/src/css/tokenizer.ts +227 -0
- package/src/css/types.ts +178 -0
- package/src/css/values.ts +330 -0
- package/src/environment.ts +112 -0
- package/src/hooks.ts +190 -0
- package/src/index.ts +61 -0
- package/src/jsx-dev-runtime.ts +43 -0
- package/src/jsx-namespace.ts +23 -0
- package/src/jsx-runtime.ts +39 -0
- package/src/math.ts +488 -0
- package/src/plugin.ts +230 -0
- package/src/props.ts +173 -0
- package/src/scope.ts +331 -0
- package/src/store.ts +288 -0
- package/src/tokens/index.ts +252 -0
- package/src/tokens/tailwind.generated.ts +613 -0
- package/src/tokens/types.ts +99 -0
- package/src/transform.ts +115 -0
- package/src/transition.ts +414 -0
- package/src/types.ts +248 -0
- package/src/utilities.ts +1992 -0
- package/src/variables.ts +509 -0
- package/src/version.ts +2 -0
- package/src/withNitroWind.ts +36 -0
package/src/core.ts
ADDED
|
@@ -0,0 +1,1248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The platform-independent part of NitroWind: it turns a class string into
|
|
3
|
+
* NitroUI props and never touches native code, so it runs in tests and tools.
|
|
4
|
+
*/
|
|
5
|
+
import {
|
|
6
|
+
applyCSSTokenResets,
|
|
7
|
+
applyRawDeclaration,
|
|
8
|
+
type CSSCustomClassDefinition,
|
|
9
|
+
type CSSCustomClassEntry,
|
|
10
|
+
CSSParseError,
|
|
11
|
+
classifyRawDeclaration,
|
|
12
|
+
detectCustomClassCycles,
|
|
13
|
+
formatLocation,
|
|
14
|
+
type NitroWindCSSConfig,
|
|
15
|
+
parseCSS,
|
|
16
|
+
} from './css'
|
|
17
|
+
import { evaluateMathInString, hasMathFunction, hasViewportUnit } from './math'
|
|
18
|
+
import { createStore, type NitroWindStore } from './store'
|
|
19
|
+
import { createTokens, parseBreakpointLength, type Tokens, type TokensConfig, tailwindTokens } from './tokens'
|
|
20
|
+
import { createThemeTransitionController } from './transition'
|
|
21
|
+
import type {
|
|
22
|
+
ClassDependencies,
|
|
23
|
+
CSSVariableName,
|
|
24
|
+
CSSVariables,
|
|
25
|
+
NitroWindEnvironment,
|
|
26
|
+
NitroWindNative,
|
|
27
|
+
ResolveContext,
|
|
28
|
+
ResolvedClasses,
|
|
29
|
+
SetThemeOptions,
|
|
30
|
+
ThemeDefinition,
|
|
31
|
+
ThemePreference,
|
|
32
|
+
ThemeState,
|
|
33
|
+
ThemeTransitionConfig,
|
|
34
|
+
UnknownClassBehavior,
|
|
35
|
+
Unsubscribe,
|
|
36
|
+
UpdateCSSVariablesOptions,
|
|
37
|
+
} from './types'
|
|
38
|
+
import {
|
|
39
|
+
applyUtility,
|
|
40
|
+
classifyUtility,
|
|
41
|
+
createDraft,
|
|
42
|
+
extractUtilityVariableNames,
|
|
43
|
+
finalizeDraft,
|
|
44
|
+
type UtilityConflict,
|
|
45
|
+
utilityUsesViewport,
|
|
46
|
+
type VariableError,
|
|
47
|
+
type VariableResolver,
|
|
48
|
+
} from './utilities'
|
|
49
|
+
import { createVariableRegistry, extractCSSVariableNames, type VariableRegistry } from './variables'
|
|
50
|
+
import { VERSION } from './version'
|
|
51
|
+
|
|
52
|
+
export interface NitroWindConfig {
|
|
53
|
+
/** CSS stylesheet string or pre-parsed `NitroWindCSSConfig` (from `parseCSS` or `nitrowind/plugin`). */
|
|
54
|
+
css?: string | NitroWindCSSConfig
|
|
55
|
+
/** Design tokens. Groups set here replace Tailwind's; groups under `extend` add to them. */
|
|
56
|
+
tokens?: TokensConfig
|
|
57
|
+
/** Shared CSS variables available to every theme unless overridden by a theme's own `variables`. */
|
|
58
|
+
variables?: Readonly<CSSVariables>
|
|
59
|
+
/** Named themes, each declaring a color scheme and optional CSS variables. `light` and `dark` are built in. */
|
|
60
|
+
themes?: Record<string, ThemeDefinition>
|
|
61
|
+
/** Initial theme preference (`'system'` or a registered theme name). Defaults to `'system'`. */
|
|
62
|
+
initialTheme?: ThemePreference
|
|
63
|
+
/** Default transition settings for `setTheme`. Defaults to `{ style: false, duration: 400 }`. */
|
|
64
|
+
transition?: ThemeTransitionConfig
|
|
65
|
+
/**
|
|
66
|
+
* What to do with classes NitroWind can't map onto NitroUI, such as `grid` or `hover:`.
|
|
67
|
+
* Defaults to `'warn'` in development builds and `'ignore'` in release builds.
|
|
68
|
+
*/
|
|
69
|
+
unknownClasses?: UnknownClassBehavior
|
|
70
|
+
/** Optional native capabilities from `nitrowind-native` (reduced motion, animated theme transitions). */
|
|
71
|
+
native?: NitroWindNative
|
|
72
|
+
/** Platform and runtime signals. Defaults to the NitroUI-backed environment. */
|
|
73
|
+
environment?: NitroWindEnvironment
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface NitroWind {
|
|
77
|
+
readonly tokens: Tokens
|
|
78
|
+
readonly themes: Readonly<Record<string, ThemeDefinition>>
|
|
79
|
+
readonly environment: NitroWindEnvironment
|
|
80
|
+
readonly store: NitroWindStore
|
|
81
|
+
/** Switches the active theme preference (`'system'` or a registered theme name). */
|
|
82
|
+
setTheme(preference: ThemePreference, options?: SetThemeOptions): Promise<void>
|
|
83
|
+
/** Returns `{ theme, colorScheme, preference }` for the active theme. */
|
|
84
|
+
getTheme(): ThemeState
|
|
85
|
+
/** Subscribes to theme changes; the listener receives the new `ThemeState`. */
|
|
86
|
+
subscribeTheme(listener: (state: ThemeState) => void): Unsubscribe
|
|
87
|
+
/** Returns the active (or specified) theme's expanded value for a CSS variable, or `undefined` if unset or cyclic. */
|
|
88
|
+
getCSSVariable(name: CSSVariableName, theme?: string): string | undefined
|
|
89
|
+
/** Merges runtime CSS variable updates into the shared layer or a specific theme. */
|
|
90
|
+
updateCSSVariables(variables: Readonly<CSSVariables>, options?: UpdateCSSVariablesOptions): void
|
|
91
|
+
/** Compiles a class string. Results are cached by class string, then by signature. */
|
|
92
|
+
resolve(className: string | null | undefined, context?: ResolveContext): ResolvedClasses
|
|
93
|
+
/** Which context channels the class string depends on, derived from its parse and cached. */
|
|
94
|
+
dependencies(className: string | null | undefined): ClassDependencies
|
|
95
|
+
/** Cache key holding only the context values this class string depends on. */
|
|
96
|
+
signature(className: string | null | undefined, context?: ResolveContext): string
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const RESERVED_THEME_NAMES = new Set([
|
|
100
|
+
'system',
|
|
101
|
+
'ios',
|
|
102
|
+
'android',
|
|
103
|
+
'sm',
|
|
104
|
+
'md',
|
|
105
|
+
'lg',
|
|
106
|
+
'xl',
|
|
107
|
+
'2xl',
|
|
108
|
+
'portrait',
|
|
109
|
+
'landscape',
|
|
110
|
+
'motion-reduce',
|
|
111
|
+
'motion-safe',
|
|
112
|
+
])
|
|
113
|
+
|
|
114
|
+
function validateThemeName(name: string): void {
|
|
115
|
+
if (!name || /[\s:[\]]/.test(name)) {
|
|
116
|
+
throw new Error(`[nitrowind] Invalid theme name "${name}"`)
|
|
117
|
+
}
|
|
118
|
+
if (RESERVED_THEME_NAMES.has(name) || name.startsWith('min-') || name.startsWith('max-')) {
|
|
119
|
+
throw new Error(`[nitrowind] Theme name "${name}" clashes with a reserved variant name`)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function buildThemes(configured?: Record<string, ThemeDefinition>): Readonly<Record<string, ThemeDefinition>> {
|
|
124
|
+
const result: Record<string, ThemeDefinition> = {
|
|
125
|
+
light: Object.freeze({ colorScheme: 'light' }),
|
|
126
|
+
dark: Object.freeze({ colorScheme: 'dark' }),
|
|
127
|
+
}
|
|
128
|
+
if (!configured) return Object.freeze(result)
|
|
129
|
+
for (const [name, definition] of Object.entries(configured)) {
|
|
130
|
+
validateThemeName(name)
|
|
131
|
+
if (name === 'light' && definition.colorScheme !== 'light') {
|
|
132
|
+
throw new Error('[nitrowind] Built-in theme "light" must have colorScheme "light"')
|
|
133
|
+
}
|
|
134
|
+
if (name === 'dark' && definition.colorScheme !== 'dark') {
|
|
135
|
+
throw new Error('[nitrowind] Built-in theme "dark" must have colorScheme "dark"')
|
|
136
|
+
}
|
|
137
|
+
if (definition.colorScheme !== 'light' && definition.colorScheme !== 'dark') {
|
|
138
|
+
throw new Error(`[nitrowind] Invalid colorScheme "${String(definition.colorScheme)}" for theme "${name}"`)
|
|
139
|
+
}
|
|
140
|
+
result[name] = Object.freeze({ ...definition })
|
|
141
|
+
}
|
|
142
|
+
return Object.freeze(result)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const VARIANTS: Record<string, (context: ResolveContext) => boolean> = {
|
|
146
|
+
dark: (context) => context.colorScheme === 'dark',
|
|
147
|
+
light: (context) => context.colorScheme !== 'dark',
|
|
148
|
+
ios: (context) => context.platform === 'ios',
|
|
149
|
+
android: (context) => context.platform === 'android',
|
|
150
|
+
portrait: (context) => context.viewport !== undefined && context.viewport.height >= context.viewport.width,
|
|
151
|
+
landscape: (context) => context.viewport !== undefined && context.viewport.width > context.viewport.height,
|
|
152
|
+
'motion-reduce': (context) => context.reducedMotion === true,
|
|
153
|
+
'motion-safe': (context) => context.reducedMotion !== true,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const COLOR_SCHEME_VARIANTS = new Set(['dark', 'light'])
|
|
157
|
+
const ORIENTATION_VARIANTS = new Set(['portrait', 'landscape'])
|
|
158
|
+
const MOTION_VARIANTS = new Set(['motion-reduce', 'motion-safe'])
|
|
159
|
+
|
|
160
|
+
interface BreakpointCondition {
|
|
161
|
+
readonly kind: 'min' | 'max'
|
|
162
|
+
readonly value: number
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface BreakpointRank {
|
|
166
|
+
/** 0 for max-only classes (applied first), 1 for min classes (applied after max-only). */
|
|
167
|
+
readonly group: 0 | 1
|
|
168
|
+
/** For max-only: -minMax (larger max first, smaller max wins). For min: maxMin (smaller min first, larger min wins). */
|
|
169
|
+
readonly primary: number
|
|
170
|
+
/** 1 when a min class also has a max bound (e.g. `md:max-xl:`), 0 otherwise. */
|
|
171
|
+
readonly hasMax: 0 | 1
|
|
172
|
+
/** Secondary tie-breaker for min+max ranges: -minMax (tighter upper bound wins). */
|
|
173
|
+
readonly secondary: number
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface ClassPrecedence {
|
|
177
|
+
/** 0 = component (@layer components / top-level .class), 1 = utility (built-in / @utility). Defaults to 1. */
|
|
178
|
+
readonly rank?: 0 | 1
|
|
179
|
+
/** 0 = unconditional/scheme/platform/orientation/motion, 1 = breakpoint, 2 = theme-name. */
|
|
180
|
+
readonly tier: 0 | 1 | 2
|
|
181
|
+
readonly breakpointRank: BreakpointRank | null
|
|
182
|
+
readonly position: number
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Precedence sort comparator: earlier classes are applied first, later classes win.
|
|
187
|
+
* Utility rank (1) beats component rank (0). Within each rank, Tier 2 (theme-name) beats
|
|
188
|
+
* Tier 1 (breakpoint), which beats Tier 0 (unconditional/other). Inside Tier 1 (and Tier 2),
|
|
189
|
+
* `max-*` sort largest-first, then `min` sort smallest-first.
|
|
190
|
+
*/
|
|
191
|
+
export function compareClassPrecedence(a: ClassPrecedence, b: ClassPrecedence): number {
|
|
192
|
+
const rankA = a.rank ?? 1
|
|
193
|
+
const rankB = b.rank ?? 1
|
|
194
|
+
if (rankA !== rankB) return rankA - rankB
|
|
195
|
+
if (a.tier !== b.tier) return a.tier - b.tier
|
|
196
|
+
if (a.breakpointRank !== b.breakpointRank) {
|
|
197
|
+
if (a.breakpointRank === null) return -1
|
|
198
|
+
if (b.breakpointRank === null) return 1
|
|
199
|
+
if (a.breakpointRank.group !== b.breakpointRank.group) return a.breakpointRank.group - b.breakpointRank.group
|
|
200
|
+
if (a.breakpointRank.primary !== b.breakpointRank.primary)
|
|
201
|
+
return a.breakpointRank.primary - b.breakpointRank.primary
|
|
202
|
+
if (a.breakpointRank.hasMax !== b.breakpointRank.hasMax) return a.breakpointRank.hasMax - b.breakpointRank.hasMax
|
|
203
|
+
if (a.breakpointRank.secondary !== b.breakpointRank.secondary) {
|
|
204
|
+
return a.breakpointRank.secondary - b.breakpointRank.secondary
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return a.position - b.position
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function hasOwn(record: Record<string, number>, key: string): boolean {
|
|
211
|
+
return Object.prototype.hasOwnProperty.call(record, key)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function parseBreakpointVariant(variant: string, breakpoints: Record<string, number>): BreakpointCondition | null {
|
|
215
|
+
if (variant.startsWith('min-[') && variant.endsWith(']')) {
|
|
216
|
+
const value = parseBreakpointLength(variant.slice(5, -1))
|
|
217
|
+
return value === null ? null : { kind: 'min', value }
|
|
218
|
+
}
|
|
219
|
+
if (variant.startsWith('max-[') && variant.endsWith(']')) {
|
|
220
|
+
const value = parseBreakpointLength(variant.slice(5, -1))
|
|
221
|
+
return value === null ? null : { kind: 'max', value }
|
|
222
|
+
}
|
|
223
|
+
if (variant.startsWith('max-')) {
|
|
224
|
+
const name = variant.slice(4)
|
|
225
|
+
return hasOwn(breakpoints, name) ? { kind: 'max', value: breakpoints[name]! } : null
|
|
226
|
+
}
|
|
227
|
+
if (variant.startsWith('min-')) {
|
|
228
|
+
const name = variant.slice(4)
|
|
229
|
+
return hasOwn(breakpoints, name) ? { kind: 'min', value: breakpoints[name]! } : null
|
|
230
|
+
}
|
|
231
|
+
if (hasOwn(breakpoints, variant)) {
|
|
232
|
+
return { kind: 'min', value: breakpoints[variant]! }
|
|
233
|
+
}
|
|
234
|
+
return null
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function computeBreakpointRank(conditions: readonly BreakpointCondition[]): BreakpointRank | null {
|
|
238
|
+
if (conditions.length === 0) return null
|
|
239
|
+
let maxMin = -Infinity
|
|
240
|
+
let minMax = Infinity
|
|
241
|
+
for (const cond of conditions) {
|
|
242
|
+
if (cond.kind === 'min' && cond.value > maxMin) maxMin = cond.value
|
|
243
|
+
if (cond.kind === 'max' && cond.value < minMax) minMax = cond.value
|
|
244
|
+
}
|
|
245
|
+
const hasMin = maxMin !== -Infinity
|
|
246
|
+
const hasMax = minMax !== Infinity
|
|
247
|
+
if (!hasMin) {
|
|
248
|
+
return { group: 0, primary: -minMax, hasMax: 1, secondary: 0 }
|
|
249
|
+
}
|
|
250
|
+
return { group: 1, primary: maxMin, hasMax: hasMax ? 1 : 0, secondary: hasMax ? -minMax : 0 }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
interface ParsedClass extends ClassPrecedence {
|
|
254
|
+
readonly rank: 0 | 1
|
|
255
|
+
readonly kind: 'utility' | 'declaration'
|
|
256
|
+
raw: string
|
|
257
|
+
variants: string[]
|
|
258
|
+
breakpoints: BreakpointCondition[]
|
|
259
|
+
themeVariants: string[]
|
|
260
|
+
otherVariants: string[]
|
|
261
|
+
unknownVariant: string | null
|
|
262
|
+
utility: string
|
|
263
|
+
property?: string
|
|
264
|
+
value?: string
|
|
265
|
+
variables: string[]
|
|
266
|
+
usesViewport: boolean
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Splits `dark:ios:!bg-red-500` into variant prefixes and the bare utility, ignoring `:` inside brackets or parentheses. */
|
|
270
|
+
function splitRawClass(raw: string): [variants: string[], utility: string] {
|
|
271
|
+
const parts: string[] = []
|
|
272
|
+
let bracketDepth = 0
|
|
273
|
+
let parenDepth = 0
|
|
274
|
+
let start = 0
|
|
275
|
+
for (let i = 0; i < raw.length; i++) {
|
|
276
|
+
const char = raw[i]
|
|
277
|
+
if (char === '[') bracketDepth++
|
|
278
|
+
else if (char === ']') bracketDepth = Math.max(0, bracketDepth - 1)
|
|
279
|
+
else if (char === '(') parenDepth++
|
|
280
|
+
else if (char === ')') parenDepth = Math.max(0, parenDepth - 1)
|
|
281
|
+
else if (char === ':' && bracketDepth === 0 && parenDepth === 0) {
|
|
282
|
+
parts.push(raw.slice(start, i))
|
|
283
|
+
start = i + 1
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
let utility = raw.slice(start)
|
|
287
|
+
// Important modifiers have no meaning here: later classes already win.
|
|
288
|
+
if (utility.startsWith('!')) utility = utility.slice(1)
|
|
289
|
+
else if (utility.endsWith('!')) utility = utility.slice(0, -1)
|
|
290
|
+
return [parts, utility]
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function classifyVariants(
|
|
294
|
+
variants: readonly string[],
|
|
295
|
+
tokens: Tokens,
|
|
296
|
+
customThemeNames: ReadonlySet<string>,
|
|
297
|
+
): {
|
|
298
|
+
breakpoints: BreakpointCondition[]
|
|
299
|
+
themeVariants: string[]
|
|
300
|
+
otherVariants: string[]
|
|
301
|
+
unknownVariant: string | null
|
|
302
|
+
breakpointRank: BreakpointRank | null
|
|
303
|
+
tier: 0 | 1 | 2
|
|
304
|
+
} {
|
|
305
|
+
const bpConditions: BreakpointCondition[] = []
|
|
306
|
+
const themeVariants: string[] = []
|
|
307
|
+
const otherVariants: string[] = []
|
|
308
|
+
let unknownVariant: string | null = null
|
|
309
|
+
|
|
310
|
+
for (const variant of variants) {
|
|
311
|
+
if (VARIANTS[variant] !== undefined) {
|
|
312
|
+
otherVariants.push(variant)
|
|
313
|
+
} else if (customThemeNames.has(variant)) {
|
|
314
|
+
themeVariants.push(variant)
|
|
315
|
+
} else {
|
|
316
|
+
const bp = parseBreakpointVariant(variant, tokens.breakpoints)
|
|
317
|
+
if (bp !== null) {
|
|
318
|
+
bpConditions.push(bp)
|
|
319
|
+
} else if (unknownVariant === null) {
|
|
320
|
+
unknownVariant = variant
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const breakpointRank = computeBreakpointRank(bpConditions)
|
|
326
|
+
const tier: 0 | 1 | 2 = themeVariants.length > 0 ? 2 : breakpointRank !== null ? 1 : 0
|
|
327
|
+
return { breakpoints: bpConditions, themeVariants, otherVariants, unknownVariant, breakpointRank, tier }
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function buildParsedUtility(
|
|
331
|
+
raw: string,
|
|
332
|
+
variants: string[],
|
|
333
|
+
utility: string,
|
|
334
|
+
rank: 0 | 1,
|
|
335
|
+
position: number,
|
|
336
|
+
tokens: Tokens,
|
|
337
|
+
customThemeNames: ReadonlySet<string>,
|
|
338
|
+
): ParsedClass {
|
|
339
|
+
const classified = classifyVariants(variants, tokens, customThemeNames)
|
|
340
|
+
return {
|
|
341
|
+
kind: 'utility',
|
|
342
|
+
raw,
|
|
343
|
+
variants,
|
|
344
|
+
...classified,
|
|
345
|
+
utility,
|
|
346
|
+
variables: extractUtilityVariableNames(utility, tokens),
|
|
347
|
+
usesViewport: utilityUsesViewport(utility),
|
|
348
|
+
rank,
|
|
349
|
+
position,
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function buildParsedDeclaration(
|
|
354
|
+
raw: string,
|
|
355
|
+
variants: string[],
|
|
356
|
+
property: string,
|
|
357
|
+
value: string,
|
|
358
|
+
rank: 0 | 1,
|
|
359
|
+
position: number,
|
|
360
|
+
tokens: Tokens,
|
|
361
|
+
customThemeNames: ReadonlySet<string>,
|
|
362
|
+
): ParsedClass {
|
|
363
|
+
const classified = classifyVariants(variants, tokens, customThemeNames)
|
|
364
|
+
return {
|
|
365
|
+
kind: 'declaration',
|
|
366
|
+
raw,
|
|
367
|
+
variants,
|
|
368
|
+
...classified,
|
|
369
|
+
utility: '',
|
|
370
|
+
property,
|
|
371
|
+
value,
|
|
372
|
+
variables: extractCSSVariableNames(value),
|
|
373
|
+
usesViewport: hasViewportUnit(value),
|
|
374
|
+
rank,
|
|
375
|
+
position,
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
interface CustomClassExpandContext {
|
|
380
|
+
readonly rawOrigin: string
|
|
381
|
+
readonly rank: 0 | 1
|
|
382
|
+
readonly tokens: Tokens
|
|
383
|
+
readonly customThemeNames: ReadonlySet<string>
|
|
384
|
+
readonly customClasses: Readonly<Record<string, CSSCustomClassDefinition>>
|
|
385
|
+
readonly out: ParsedClass[]
|
|
386
|
+
readonly visiting: Set<string>
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function expandCustomClassEntries(
|
|
390
|
+
entries: readonly CSSCustomClassEntry[],
|
|
391
|
+
enclosingVariants: readonly string[],
|
|
392
|
+
ctx: CustomClassExpandContext,
|
|
393
|
+
): void {
|
|
394
|
+
for (const entry of entries) {
|
|
395
|
+
if (entry.kind === 'variant') {
|
|
396
|
+
expandCustomClassEntries(entry.entries, [...enclosingVariants, entry.variant], ctx)
|
|
397
|
+
continue
|
|
398
|
+
}
|
|
399
|
+
if (entry.kind === 'declaration') {
|
|
400
|
+
ctx.out.push(
|
|
401
|
+
buildParsedDeclaration(
|
|
402
|
+
`${ctx.rawOrigin} (${entry.property}: ${entry.value})`,
|
|
403
|
+
[...enclosingVariants],
|
|
404
|
+
entry.property,
|
|
405
|
+
entry.value,
|
|
406
|
+
ctx.rank,
|
|
407
|
+
ctx.out.length,
|
|
408
|
+
ctx.tokens,
|
|
409
|
+
ctx.customThemeNames,
|
|
410
|
+
),
|
|
411
|
+
)
|
|
412
|
+
continue
|
|
413
|
+
}
|
|
414
|
+
if (entry.kind === 'apply') {
|
|
415
|
+
for (const applied of entry.classes) {
|
|
416
|
+
const [applyVariants, applyUtility] = splitRawClass(applied)
|
|
417
|
+
const combinedVariants = [...enclosingVariants, ...applyVariants]
|
|
418
|
+
if (Object.prototype.hasOwnProperty.call(ctx.customClasses, applyUtility)) {
|
|
419
|
+
if (ctx.visiting.has(applyUtility)) continue
|
|
420
|
+
ctx.visiting.add(applyUtility)
|
|
421
|
+
expandCustomClassEntries(ctx.customClasses[applyUtility]!.entries, combinedVariants, ctx)
|
|
422
|
+
ctx.visiting.delete(applyUtility)
|
|
423
|
+
} else {
|
|
424
|
+
ctx.out.push(
|
|
425
|
+
buildParsedUtility(
|
|
426
|
+
`${ctx.rawOrigin} (@apply ${applied})`,
|
|
427
|
+
combinedVariants,
|
|
428
|
+
applyUtility,
|
|
429
|
+
ctx.rank,
|
|
430
|
+
ctx.out.length,
|
|
431
|
+
ctx.tokens,
|
|
432
|
+
ctx.customThemeNames,
|
|
433
|
+
),
|
|
434
|
+
)
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function parseClassList(
|
|
442
|
+
className: string,
|
|
443
|
+
tokens: Tokens,
|
|
444
|
+
customThemeNames: ReadonlySet<string>,
|
|
445
|
+
customClasses: Readonly<Record<string, CSSCustomClassDefinition>> | undefined,
|
|
446
|
+
): ParsedClass[] {
|
|
447
|
+
const out: ParsedClass[] = []
|
|
448
|
+
for (const raw of className.split(/\s+/)) {
|
|
449
|
+
if (!raw) continue
|
|
450
|
+
const [variants, utility] = splitRawClass(raw)
|
|
451
|
+
if (customClasses !== undefined && Object.prototype.hasOwnProperty.call(customClasses, utility)) {
|
|
452
|
+
const outerClassified = classifyVariants(variants, tokens, customThemeNames)
|
|
453
|
+
if (outerClassified.unknownVariant !== null) {
|
|
454
|
+
out.push(buildParsedUtility(raw, variants, utility, 1, out.length, tokens, customThemeNames))
|
|
455
|
+
continue
|
|
456
|
+
}
|
|
457
|
+
const def = customClasses[utility]!
|
|
458
|
+
const rank: 0 | 1 = def.rank === 'utility' ? 1 : 0
|
|
459
|
+
expandCustomClassEntries(def.entries, variants, {
|
|
460
|
+
rawOrigin: raw,
|
|
461
|
+
rank,
|
|
462
|
+
tokens,
|
|
463
|
+
customThemeNames,
|
|
464
|
+
customClasses,
|
|
465
|
+
out,
|
|
466
|
+
visiting: new Set<string>([utility]),
|
|
467
|
+
})
|
|
468
|
+
continue
|
|
469
|
+
}
|
|
470
|
+
out.push(buildParsedUtility(raw, variants, utility, 1, out.length, tokens, customThemeNames))
|
|
471
|
+
}
|
|
472
|
+
return out.sort(compareClassPrecedence)
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function isDevelopment(): boolean {
|
|
476
|
+
const dev = (globalThis as { __DEV__?: boolean }).__DEV__
|
|
477
|
+
return dev !== false
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const EMPTY: ResolvedClasses = Object.freeze({})
|
|
481
|
+
const EMPTY_STRINGS: readonly string[] = Object.freeze([])
|
|
482
|
+
const EMPTY_NUMBERS: readonly number[] = Object.freeze([])
|
|
483
|
+
const NO_DEPENDENCIES: ClassDependencies = Object.freeze({
|
|
484
|
+
colorScheme: false,
|
|
485
|
+
themes: EMPTY_STRINGS,
|
|
486
|
+
reducedMotion: false,
|
|
487
|
+
breakpoints: EMPTY_NUMBERS,
|
|
488
|
+
variables: EMPTY_STRINGS,
|
|
489
|
+
orientation: false,
|
|
490
|
+
viewport: false,
|
|
491
|
+
})
|
|
492
|
+
const MAX_SIGNATURES_PER_CLASS = 16
|
|
493
|
+
|
|
494
|
+
function freezeResult(draft: ReturnType<typeof createDraft>): ResolvedClasses {
|
|
495
|
+
const result: ResolvedClasses = {}
|
|
496
|
+
if (Object.keys(draft.layout).length > 0) result.layout = Object.freeze(draft.layout)
|
|
497
|
+
if (Object.keys(draft.style).length > 0) result.style = Object.freeze(draft.style)
|
|
498
|
+
if (Object.keys(draft.text).length > 0) result.text = Object.freeze(draft.text)
|
|
499
|
+
return Object.freeze(result)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const FALLBACK_ENVIRONMENT: NitroWindEnvironment = {
|
|
503
|
+
platform: 'ios',
|
|
504
|
+
getColorScheme: () => 'light',
|
|
505
|
+
setColorScheme: () => {},
|
|
506
|
+
subscribeColorScheme: () => () => {},
|
|
507
|
+
getViewportSize: () => undefined,
|
|
508
|
+
subscribeViewportSize: () => () => {},
|
|
509
|
+
native: undefined,
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
let defaultEnvironment: NitroWindEnvironment = FALLBACK_ENVIRONMENT
|
|
513
|
+
/** Each instance's variable registry, for internal callers that need more than the public interface. */
|
|
514
|
+
const registries = new WeakMap<NitroWind, VariableRegistry>()
|
|
515
|
+
/** Each instance's CSS custom classes, for `cn()` precedence and deduplication. */
|
|
516
|
+
const customClassesByInstance = new WeakMap<NitroWind, Readonly<Record<string, CSSCustomClassDefinition>>>()
|
|
517
|
+
let configured = false
|
|
518
|
+
|
|
519
|
+
function mergeThemesWithCSS(
|
|
520
|
+
cssConfig: NitroWindCSSConfig | undefined,
|
|
521
|
+
jsThemes: Record<string, ThemeDefinition> | undefined,
|
|
522
|
+
): Record<string, ThemeDefinition> | undefined {
|
|
523
|
+
const cssThemes = cssConfig?.themes
|
|
524
|
+
if (!cssThemes || Object.keys(cssThemes).length === 0) return jsThemes
|
|
525
|
+
|
|
526
|
+
const merged: Record<string, ThemeDefinition> = {}
|
|
527
|
+
const allNames = new Set([...Object.keys(cssThemes), ...Object.keys(jsThemes ?? {})])
|
|
528
|
+
for (const name of allNames) {
|
|
529
|
+
const cssEntry = cssThemes[name]
|
|
530
|
+
const jsEntry = jsThemes?.[name]
|
|
531
|
+
const colorScheme =
|
|
532
|
+
jsEntry?.colorScheme ??
|
|
533
|
+
cssEntry?.colorScheme ??
|
|
534
|
+
(name === 'light' ? 'light' : name === 'dark' ? 'dark' : undefined)
|
|
535
|
+
if (colorScheme === undefined) {
|
|
536
|
+
const message = `Custom theme "@variant ${name}" must declare "color-scheme: light;" or "color-scheme: dark;" (or provide colorScheme in JS themes)`
|
|
537
|
+
if (cssEntry?.location) {
|
|
538
|
+
throw new CSSParseError(message, cssEntry.location)
|
|
539
|
+
}
|
|
540
|
+
throw new Error(`[nitrowind] ${message}`)
|
|
541
|
+
}
|
|
542
|
+
const variables =
|
|
543
|
+
cssEntry?.variables || jsEntry?.variables ? { ...cssEntry?.variables, ...jsEntry?.variables } : undefined
|
|
544
|
+
merged[name] = variables !== undefined ? { colorScheme, variables } : { colorScheme }
|
|
545
|
+
}
|
|
546
|
+
return merged
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Creates an independent NitroWind instance with its own tokens, themes, store and caches. */
|
|
550
|
+
export function createNitroWind(config: NitroWindConfig = {}): NitroWind {
|
|
551
|
+
const isDev = isDevelopment()
|
|
552
|
+
const cssConfig: NitroWindCSSConfig | undefined =
|
|
553
|
+
typeof config.css === 'string'
|
|
554
|
+
? parseCSS(config.css, {
|
|
555
|
+
onWarning: isDev
|
|
556
|
+
? (warning) => {
|
|
557
|
+
// Variable parity is validated below against the final merged shared + theme layers.
|
|
558
|
+
if (warning.code === 'variable-parity') return
|
|
559
|
+
console.warn(`[nitrowind] ${warning.message} (${formatLocation(warning)})`)
|
|
560
|
+
}
|
|
561
|
+
: undefined,
|
|
562
|
+
})
|
|
563
|
+
: config.css
|
|
564
|
+
const cssBaseTokens =
|
|
565
|
+
cssConfig !== undefined
|
|
566
|
+
? createTokens(cssConfig.tokens, applyCSSTokenResets(tailwindTokens, cssConfig.tokenResets))
|
|
567
|
+
: tailwindTokens
|
|
568
|
+
const tokens = createTokens(config.tokens, cssBaseTokens)
|
|
569
|
+
const themes = buildThemes(mergeThemesWithCSS(cssConfig, config.themes))
|
|
570
|
+
const mergedVariables =
|
|
571
|
+
cssConfig?.variables || config.variables ? { ...cssConfig?.variables, ...config.variables } : undefined
|
|
572
|
+
const variables = createVariableRegistry(mergedVariables, themes, isDev)
|
|
573
|
+
const initialTheme = config.initialTheme ?? 'system'
|
|
574
|
+
if (initialTheme !== 'system' && !Object.prototype.hasOwnProperty.call(themes, initialTheme)) {
|
|
575
|
+
throw new Error(`[nitrowind] Unregistered initialTheme "${initialTheme}"`)
|
|
576
|
+
}
|
|
577
|
+
const baseEnvironment = config.environment ?? defaultEnvironment
|
|
578
|
+
const environment = config.native !== undefined ? { ...baseEnvironment, native: config.native } : baseEnvironment
|
|
579
|
+
if (environment.native !== undefined && environment.native.version !== VERSION && isDevelopment()) {
|
|
580
|
+
console.warn(
|
|
581
|
+
`[nitrowind] Version mismatch: nitrowind@${VERSION} was configured with nitrowind-native@${environment.native.version}. Keep both packages on the same version.`,
|
|
582
|
+
)
|
|
583
|
+
}
|
|
584
|
+
const store = createStore(environment, themes, initialTheme)
|
|
585
|
+
const transitions = createThemeTransitionController(environment, store, themes, config.transition, isDevelopment)
|
|
586
|
+
const customClasses = cssConfig?.customClasses
|
|
587
|
+
if (customClasses !== undefined) {
|
|
588
|
+
detectCustomClassCycles(customClasses)
|
|
589
|
+
}
|
|
590
|
+
const customThemeNames = new Set(Object.keys(themes).filter((name) => name !== 'light' && name !== 'dark'))
|
|
591
|
+
const unknownClasses = config.unknownClasses ?? (isDevelopment() ? 'warn' : 'ignore')
|
|
592
|
+
const parsedCache = new Map<string, ParsedClass[]>()
|
|
593
|
+
const dependencyCache = new Map<string, ClassDependencies>()
|
|
594
|
+
const resultCache = new Map<string, Map<string, ResolvedClasses>>()
|
|
595
|
+
const warned = new Set<string>()
|
|
596
|
+
|
|
597
|
+
function reportUnknown(raw: string, reason: string): void {
|
|
598
|
+
if (unknownClasses === 'ignore') return
|
|
599
|
+
const message = `[nitrowind] ${reason}: "${raw}"`
|
|
600
|
+
if (unknownClasses === 'throw') throw new Error(message)
|
|
601
|
+
if (!warned.has(raw)) {
|
|
602
|
+
warned.add(raw)
|
|
603
|
+
console.warn(message)
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function reportVariableError(raw: string, theme: string, error: VariableError): void {
|
|
608
|
+
if (unknownClasses === 'ignore') return
|
|
609
|
+
let message: string
|
|
610
|
+
switch (error.kind) {
|
|
611
|
+
case 'missing':
|
|
612
|
+
message = `[nitrowind] Missing CSS variable "${error.variable ?? ''}" in theme "${theme}" (used by "${raw}")`
|
|
613
|
+
break
|
|
614
|
+
case 'cycle':
|
|
615
|
+
message = `[nitrowind] Cyclic CSS variable "${error.variable ?? ''}" in theme "${theme}" (used by "${raw}")`
|
|
616
|
+
break
|
|
617
|
+
case 'calc':
|
|
618
|
+
message = error.variable
|
|
619
|
+
? `[nitrowind] Cannot evaluate CSS math in variable "${error.variable}" in theme "${theme}" (used by "${raw}"): ${error.reason ?? error.value ?? 'invalid expression'}`
|
|
620
|
+
: `[nitrowind] Cannot evaluate CSS math in "${raw}": ${error.reason ?? error.value ?? 'invalid expression'}`
|
|
621
|
+
break
|
|
622
|
+
case 'invalid':
|
|
623
|
+
message = `[nitrowind] Invalid ${error.expected ?? 'value'} "${error.value ?? ''}" for CSS variable "${error.variable ?? ''}" in theme "${theme}" (used by "${raw}")`
|
|
624
|
+
break
|
|
625
|
+
}
|
|
626
|
+
if (unknownClasses === 'throw') throw new Error(message)
|
|
627
|
+
const key = error.variable !== undefined ? `var:${error.variable}:${theme}` : `raw:${raw}`
|
|
628
|
+
if (!warned.has(key)) {
|
|
629
|
+
warned.add(key)
|
|
630
|
+
console.warn(message)
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function resolveThemeAndScheme(context: ResolveContext): { theme: string; colorScheme: 'light' | 'dark' } {
|
|
635
|
+
const registered = context.theme !== undefined ? themes[context.theme] : undefined
|
|
636
|
+
const colorScheme = context.colorScheme ?? registered?.colorScheme ?? 'light'
|
|
637
|
+
const theme = context.theme ?? colorScheme
|
|
638
|
+
return { theme, colorScheme }
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function parse(className: string): ParsedClass[] {
|
|
642
|
+
let parsed = parsedCache.get(className)
|
|
643
|
+
if (parsed === undefined) {
|
|
644
|
+
parsed = parseClassList(className, tokens, customThemeNames, customClasses)
|
|
645
|
+
parsedCache.set(className, parsed)
|
|
646
|
+
}
|
|
647
|
+
return parsed
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function dependencies(className: string | null | undefined): ClassDependencies {
|
|
651
|
+
if (!className) return NO_DEPENDENCIES
|
|
652
|
+
let deps = dependencyCache.get(className)
|
|
653
|
+
if (deps === undefined) {
|
|
654
|
+
let colorScheme = false
|
|
655
|
+
let themeSet: Set<string> | undefined
|
|
656
|
+
let reducedMotion = false
|
|
657
|
+
let bpSet: Set<number> | undefined
|
|
658
|
+
let varSet: Set<string> | undefined
|
|
659
|
+
let orientation = false
|
|
660
|
+
let viewport = false
|
|
661
|
+
for (const parsed of parse(className)) {
|
|
662
|
+
for (const variant of parsed.otherVariants) {
|
|
663
|
+
if (COLOR_SCHEME_VARIANTS.has(variant)) colorScheme = true
|
|
664
|
+
else if (ORIENTATION_VARIANTS.has(variant)) orientation = true
|
|
665
|
+
else if (MOTION_VARIANTS.has(variant)) reducedMotion = true
|
|
666
|
+
}
|
|
667
|
+
for (const themeVariant of parsed.themeVariants) {
|
|
668
|
+
if (themeSet === undefined) themeSet = new Set()
|
|
669
|
+
themeSet.add(themeVariant)
|
|
670
|
+
}
|
|
671
|
+
for (const bp of parsed.breakpoints) {
|
|
672
|
+
if (bpSet === undefined) bpSet = new Set()
|
|
673
|
+
bpSet.add(bp.value)
|
|
674
|
+
}
|
|
675
|
+
for (const variable of parsed.variables) {
|
|
676
|
+
if (varSet === undefined) varSet = new Set()
|
|
677
|
+
varSet.add(variable)
|
|
678
|
+
}
|
|
679
|
+
if (parsed.usesViewport) viewport = true
|
|
680
|
+
}
|
|
681
|
+
if (
|
|
682
|
+
!colorScheme &&
|
|
683
|
+
!reducedMotion &&
|
|
684
|
+
!orientation &&
|
|
685
|
+
!viewport &&
|
|
686
|
+
themeSet === undefined &&
|
|
687
|
+
bpSet === undefined &&
|
|
688
|
+
varSet === undefined
|
|
689
|
+
) {
|
|
690
|
+
deps = NO_DEPENDENCIES
|
|
691
|
+
} else {
|
|
692
|
+
const themeList = themeSet ? Object.freeze([...themeSet].sort()) : EMPTY_STRINGS
|
|
693
|
+
const breakpoints = bpSet ? Object.freeze([...bpSet].sort((a, b) => a - b)) : EMPTY_NUMBERS
|
|
694
|
+
const variableList = varSet ? Object.freeze([...varSet].sort()) : EMPTY_STRINGS
|
|
695
|
+
deps = Object.freeze({
|
|
696
|
+
colorScheme,
|
|
697
|
+
themes: themeList,
|
|
698
|
+
reducedMotion,
|
|
699
|
+
breakpoints,
|
|
700
|
+
variables: variableList,
|
|
701
|
+
orientation,
|
|
702
|
+
viewport,
|
|
703
|
+
})
|
|
704
|
+
}
|
|
705
|
+
dependencyCache.set(className, deps)
|
|
706
|
+
}
|
|
707
|
+
return deps
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function signature(className: string | null | undefined, context: ResolveContext = {}): string {
|
|
711
|
+
const deps = dependencies(className)
|
|
712
|
+
if (
|
|
713
|
+
!deps.colorScheme &&
|
|
714
|
+
deps.themes.length === 0 &&
|
|
715
|
+
!deps.reducedMotion &&
|
|
716
|
+
deps.breakpoints.length === 0 &&
|
|
717
|
+
deps.variables.length === 0 &&
|
|
718
|
+
!deps.orientation &&
|
|
719
|
+
!deps.viewport
|
|
720
|
+
) {
|
|
721
|
+
return ''
|
|
722
|
+
}
|
|
723
|
+
const parts: string[] = []
|
|
724
|
+
let resolvedTheme: { theme: string; colorScheme: 'light' | 'dark' } | undefined
|
|
725
|
+
if (deps.colorScheme || deps.themes.length > 0 || deps.variables.length > 0) {
|
|
726
|
+
resolvedTheme = resolveThemeAndScheme(context)
|
|
727
|
+
if (deps.colorScheme) parts.push(`s:${resolvedTheme.colorScheme}`)
|
|
728
|
+
if (deps.themes.length > 0) {
|
|
729
|
+
parts.push(`t:${deps.themes.includes(resolvedTheme.theme) ? resolvedTheme.theme : ''}`)
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
if (deps.reducedMotion) parts.push(`m:${context.reducedMotion === true ? 'reduce' : 'safe'}`)
|
|
733
|
+
if (deps.breakpoints.length > 0) {
|
|
734
|
+
if (context.viewport === undefined) {
|
|
735
|
+
parts.push('b:-')
|
|
736
|
+
} else {
|
|
737
|
+
const width = context.viewport.width
|
|
738
|
+
let bucket = 0
|
|
739
|
+
for (const bp of deps.breakpoints) {
|
|
740
|
+
if (width >= bp) bucket++
|
|
741
|
+
else break
|
|
742
|
+
}
|
|
743
|
+
parts.push(`b:${bucket}`)
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
let varsUseViewport = false
|
|
747
|
+
if (deps.variables.length > 0) {
|
|
748
|
+
const theme = resolvedTheme!.theme
|
|
749
|
+
const varParts = deps.variables.map((name) => {
|
|
750
|
+
const expanded = variables.expandVariable(name, theme, context.variables, {
|
|
751
|
+
outerScope: context.outerVariables,
|
|
752
|
+
})
|
|
753
|
+
if (expanded.ok && hasViewportUnit(expanded.value)) varsUseViewport = true
|
|
754
|
+
return expanded.ok ? `${name}=${JSON.stringify(expanded.value)}` : `${name}=${expanded.kind}`
|
|
755
|
+
})
|
|
756
|
+
parts.push(`v:${varParts.join(',')}`)
|
|
757
|
+
}
|
|
758
|
+
if (deps.orientation) {
|
|
759
|
+
if (context.viewport === undefined) {
|
|
760
|
+
parts.push('o:-')
|
|
761
|
+
} else {
|
|
762
|
+
parts.push(context.viewport.height >= context.viewport.width ? 'o:p' : 'o:l')
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
if (deps.viewport || varsUseViewport) {
|
|
766
|
+
if (context.viewport === undefined) {
|
|
767
|
+
parts.push('vp:-')
|
|
768
|
+
} else {
|
|
769
|
+
parts.push(`vp:${context.viewport.width}x${context.viewport.height}`)
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return parts.join('|')
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
function resolve(className: string | null | undefined, context: ResolveContext = {}): ResolvedClasses {
|
|
776
|
+
if (!className) return EMPTY
|
|
777
|
+
const deps = dependencies(className)
|
|
778
|
+
const sig = signature(className, context)
|
|
779
|
+
const { theme, colorScheme } = resolveThemeAndScheme(context)
|
|
780
|
+
const cacheKey =
|
|
781
|
+
deps.variables.length > 0 && unknownClasses !== 'ignore'
|
|
782
|
+
? `${context.platform ?? ''}|${theme}|${sig}`
|
|
783
|
+
: `${context.platform ?? ''}|${sig}`
|
|
784
|
+
let bySignature = resultCache.get(className)
|
|
785
|
+
const cached = bySignature?.get(cacheKey)
|
|
786
|
+
if (cached !== undefined) return cached
|
|
787
|
+
|
|
788
|
+
const effectiveContext: ResolveContext = {
|
|
789
|
+
platform: context.platform,
|
|
790
|
+
theme,
|
|
791
|
+
colorScheme,
|
|
792
|
+
reducedMotion: context.reducedMotion,
|
|
793
|
+
viewport: context.viewport,
|
|
794
|
+
variables: context.variables,
|
|
795
|
+
outerVariables: context.outerVariables,
|
|
796
|
+
}
|
|
797
|
+
const draft = createDraft()
|
|
798
|
+
let currentRaw = ''
|
|
799
|
+
let hadVariableError = false
|
|
800
|
+
let missingViewport = false
|
|
801
|
+
const resolveExpandedMath = (
|
|
802
|
+
value: string,
|
|
803
|
+
vars: readonly string[],
|
|
804
|
+
variable?: string,
|
|
805
|
+
): { readonly value: string; readonly variables: readonly string[] } | null => {
|
|
806
|
+
if (!hasMathFunction(value)) return { value, variables: vars }
|
|
807
|
+
const evaluated = evaluateMathInString(value, effectiveContext.viewport)
|
|
808
|
+
if (evaluated.ok) return { value: evaluated.value, variables: vars }
|
|
809
|
+
if (evaluated.reason === 'missing-viewport') {
|
|
810
|
+
missingViewport = true
|
|
811
|
+
return null
|
|
812
|
+
}
|
|
813
|
+
hadVariableError = true
|
|
814
|
+
reportVariableError(currentRaw, theme, {
|
|
815
|
+
kind: 'calc',
|
|
816
|
+
variable,
|
|
817
|
+
value,
|
|
818
|
+
reason: evaluated.message,
|
|
819
|
+
})
|
|
820
|
+
return null
|
|
821
|
+
}
|
|
822
|
+
const varResolver: VariableResolver = {
|
|
823
|
+
expand(expr) {
|
|
824
|
+
const result = variables.expandExpression(expr, theme, context.variables, {
|
|
825
|
+
outerScope: context.outerVariables,
|
|
826
|
+
})
|
|
827
|
+
if (!result.ok) {
|
|
828
|
+
hadVariableError = true
|
|
829
|
+
reportVariableError(currentRaw, theme, result)
|
|
830
|
+
return null
|
|
831
|
+
}
|
|
832
|
+
return resolveExpandedMath(result.value, result.variables, result.variables[0])
|
|
833
|
+
},
|
|
834
|
+
tryVariable(name) {
|
|
835
|
+
if (variables.lookupRaw(name, theme, context.variables, context.outerVariables) === undefined) return null
|
|
836
|
+
const result = variables.expandVariable(name, theme, context.variables, {
|
|
837
|
+
outerScope: context.outerVariables,
|
|
838
|
+
})
|
|
839
|
+
if (!result.ok) {
|
|
840
|
+
hadVariableError = true
|
|
841
|
+
reportVariableError(currentRaw, theme, result)
|
|
842
|
+
return null
|
|
843
|
+
}
|
|
844
|
+
return resolveExpandedMath(result.value, result.variables, result.variables[0] ?? name)
|
|
845
|
+
},
|
|
846
|
+
reportError(error) {
|
|
847
|
+
hadVariableError = true
|
|
848
|
+
reportVariableError(currentRaw, theme, error)
|
|
849
|
+
},
|
|
850
|
+
hasError() {
|
|
851
|
+
return hadVariableError
|
|
852
|
+
},
|
|
853
|
+
isMissingViewport() {
|
|
854
|
+
return missingViewport
|
|
855
|
+
},
|
|
856
|
+
}
|
|
857
|
+
// Classes are pre-sorted by tier, breakpoint rank, and position so later classes override earlier ones.
|
|
858
|
+
for (const parsed of parse(className)) {
|
|
859
|
+
if (parsed.unknownVariant !== null) {
|
|
860
|
+
reportUnknown(parsed.raw, `Unsupported variant "${parsed.unknownVariant}"`)
|
|
861
|
+
continue
|
|
862
|
+
}
|
|
863
|
+
let matches = true
|
|
864
|
+
for (const variant of parsed.otherVariants) {
|
|
865
|
+
if (!VARIANTS[variant]!(effectiveContext)) {
|
|
866
|
+
matches = false
|
|
867
|
+
break
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
if (!matches) continue
|
|
871
|
+
for (const themeVariant of parsed.themeVariants) {
|
|
872
|
+
if (theme !== themeVariant) {
|
|
873
|
+
matches = false
|
|
874
|
+
break
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (!matches) continue
|
|
878
|
+
if (parsed.breakpoints.length > 0) {
|
|
879
|
+
if (effectiveContext.viewport === undefined) continue
|
|
880
|
+
const width = effectiveContext.viewport.width
|
|
881
|
+
for (const bp of parsed.breakpoints) {
|
|
882
|
+
if (bp.kind === 'min' ? width < bp.value : width >= bp.value) {
|
|
883
|
+
matches = false
|
|
884
|
+
break
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
if (!matches) continue
|
|
888
|
+
}
|
|
889
|
+
currentRaw = parsed.raw
|
|
890
|
+
hadVariableError = false
|
|
891
|
+
missingViewport = false
|
|
892
|
+
if (parsed.kind === 'declaration') {
|
|
893
|
+
if (
|
|
894
|
+
!applyRawDeclaration(parsed.property!, parsed.value!, draft, varResolver, effectiveContext.viewport) &&
|
|
895
|
+
!hadVariableError &&
|
|
896
|
+
!missingViewport
|
|
897
|
+
) {
|
|
898
|
+
reportUnknown(parsed.raw, 'Unsupported declaration')
|
|
899
|
+
}
|
|
900
|
+
} else if (
|
|
901
|
+
!applyUtility(parsed.utility, draft, tokens, varResolver, effectiveContext.viewport) &&
|
|
902
|
+
!hadVariableError &&
|
|
903
|
+
!missingViewport
|
|
904
|
+
) {
|
|
905
|
+
reportUnknown(parsed.raw, 'Unsupported class')
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
finalizeDraft(draft)
|
|
909
|
+
|
|
910
|
+
const result = freezeResult(draft)
|
|
911
|
+
if (bySignature === undefined) {
|
|
912
|
+
bySignature = new Map()
|
|
913
|
+
resultCache.set(className, bySignature)
|
|
914
|
+
} else if (bySignature.size >= MAX_SIGNATURES_PER_CLASS) {
|
|
915
|
+
const oldest = bySignature.keys().next().value
|
|
916
|
+
if (oldest !== undefined) bySignature.delete(oldest)
|
|
917
|
+
}
|
|
918
|
+
bySignature.set(cacheKey, result)
|
|
919
|
+
return result
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function setTheme(preference: ThemePreference, options?: SetThemeOptions): Promise<void> {
|
|
923
|
+
return transitions.setTheme(preference, options)
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function getTheme(): ThemeState {
|
|
927
|
+
return store.getTheme()
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function subscribeTheme(listener: (state: ThemeState) => void): Unsubscribe {
|
|
931
|
+
return store.subscribeTheme(() => listener(store.getTheme()))
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function getCSSVariable(name: CSSVariableName, theme?: string): string | undefined {
|
|
935
|
+
return variables.getCSSVariable(name, theme ?? store.getTheme().theme)
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
function updateCSSVariables(updates: Readonly<CSSVariables>, options?: UpdateCSSVariablesOptions): void {
|
|
939
|
+
const activeTheme = store.getTheme().theme
|
|
940
|
+
const subscribedThemes = [...store.getSubscribedVariableThemes()]
|
|
941
|
+
const affectedByTheme = variables.update(updates, activeTheme, options?.theme, subscribedThemes)
|
|
942
|
+
const activeAffected = affectedByTheme.get(activeTheme)
|
|
943
|
+
if (activeAffected !== undefined && activeAffected.size > 0) {
|
|
944
|
+
store.notifyVariables(activeAffected)
|
|
945
|
+
}
|
|
946
|
+
for (const theme of subscribedThemes) {
|
|
947
|
+
const scopedAffected = affectedByTheme.get(theme)
|
|
948
|
+
if (scopedAffected !== undefined && scopedAffected.size > 0) {
|
|
949
|
+
store.notifyVariables(scopedAffected, theme)
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const nitroWind: NitroWind = {
|
|
955
|
+
tokens,
|
|
956
|
+
themes,
|
|
957
|
+
environment,
|
|
958
|
+
store,
|
|
959
|
+
setTheme,
|
|
960
|
+
getTheme,
|
|
961
|
+
subscribeTheme,
|
|
962
|
+
getCSSVariable,
|
|
963
|
+
updateCSSVariables,
|
|
964
|
+
resolve,
|
|
965
|
+
dependencies,
|
|
966
|
+
signature,
|
|
967
|
+
}
|
|
968
|
+
registries.set(nitroWind, variables)
|
|
969
|
+
if (customClasses !== undefined) {
|
|
970
|
+
customClassesByInstance.set(nitroWind, customClasses)
|
|
971
|
+
}
|
|
972
|
+
return nitroWind
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Internal: `getCSSVariable` inside a variable scope, whose merged values win over the theme's.
|
|
977
|
+
* `useCSSVariable` calls it; the public `getCSSVariable` never sees a scope.
|
|
978
|
+
*/
|
|
979
|
+
export function getScopedCSSVariable(
|
|
980
|
+
nitroWind: NitroWind,
|
|
981
|
+
name: CSSVariableName,
|
|
982
|
+
theme: string,
|
|
983
|
+
scope: Readonly<CSSVariables> | undefined,
|
|
984
|
+
outerScope?: Readonly<CSSVariables>,
|
|
985
|
+
): string | undefined {
|
|
986
|
+
const registry = registries.get(nitroWind)
|
|
987
|
+
return registry !== undefined
|
|
988
|
+
? registry.getCSSVariable(name, theme, scope, outerScope)
|
|
989
|
+
: nitroWind.getCSSVariable(name, theme)
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/** Internal: returns true if any of `names` currently expands to a value using `vw` or `vh`. */
|
|
993
|
+
export function variablesUseViewport(
|
|
994
|
+
nitroWind: NitroWind,
|
|
995
|
+
names: readonly string[],
|
|
996
|
+
theme: string,
|
|
997
|
+
scope?: Readonly<CSSVariables>,
|
|
998
|
+
outerScope?: Readonly<CSSVariables>,
|
|
999
|
+
): boolean {
|
|
1000
|
+
const registry = registries.get(nitroWind)
|
|
1001
|
+
if (registry === undefined) return false
|
|
1002
|
+
for (const name of names) {
|
|
1003
|
+
const value = registry.getCSSVariable(name, theme, scope, outerScope)
|
|
1004
|
+
if (value !== undefined && hasViewportUnit(value)) return true
|
|
1005
|
+
}
|
|
1006
|
+
return false
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
let instance: NitroWind = createNitroWind()
|
|
1010
|
+
|
|
1011
|
+
/** Registers the runtime's default environment (NitroUI in apps). */
|
|
1012
|
+
export function setDefaultEnvironment(environment: NitroWindEnvironment): void {
|
|
1013
|
+
defaultEnvironment = environment
|
|
1014
|
+
if (!configured) {
|
|
1015
|
+
instance = createNitroWind({ environment })
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/**
|
|
1020
|
+
* Replaces the shared instance used by `className`, `tw` and `useTw`.
|
|
1021
|
+
* Call it once in your entry file, before the first render.
|
|
1022
|
+
*/
|
|
1023
|
+
export function configure(config: NitroWindConfig): NitroWind {
|
|
1024
|
+
configured = true
|
|
1025
|
+
instance = createNitroWind(config)
|
|
1026
|
+
return instance
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/** The shared instance. */
|
|
1030
|
+
export function getNitroWind(): NitroWind {
|
|
1031
|
+
return instance
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/** Switches the active theme preference on the shared instance (`'system'` or a registered theme name). */
|
|
1035
|
+
export function setTheme(preference: ThemePreference, options?: SetThemeOptions): Promise<void> {
|
|
1036
|
+
return getNitroWind().setTheme(preference, options)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/** Returns `{ theme, colorScheme, preference }` from the shared instance. */
|
|
1040
|
+
export function getTheme(): ThemeState {
|
|
1041
|
+
return getNitroWind().getTheme()
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
/** Subscribes to theme changes on the shared instance. */
|
|
1045
|
+
export function subscribeTheme(listener: (state: ThemeState) => void): Unsubscribe {
|
|
1046
|
+
return getNitroWind().subscribeTheme(listener)
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/** Returns the active theme's expanded value for a CSS variable on the shared instance. */
|
|
1050
|
+
export function getCSSVariable(name: CSSVariableName): string | undefined {
|
|
1051
|
+
return getNitroWind().getCSSVariable(name)
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/** Merges runtime CSS variable updates into the shared layer or a specific theme on the shared instance. */
|
|
1055
|
+
export function updateCSSVariables(variables: Readonly<CSSVariables>, options?: UpdateCSSVariablesOptions): void {
|
|
1056
|
+
getNitroWind().updateCSSVariables(variables, options)
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* Compiles classes to `{ layout, style, text }` outside of JSX, for example to pass
|
|
1061
|
+
* `tw('p-4').layout` to a component that takes NitroUI props.
|
|
1062
|
+
* Theme and scheme variants read the store once at call time; prefer `useTw` in components.
|
|
1063
|
+
*/
|
|
1064
|
+
export function tw(className: string | null | undefined): ResolvedClasses {
|
|
1065
|
+
const nitroWind = getNitroWind()
|
|
1066
|
+
const deps = nitroWind.dependencies(className)
|
|
1067
|
+
const needsTheme = deps.colorScheme || deps.themes.length > 0 || deps.variables.length > 0
|
|
1068
|
+
const themeState = needsTheme ? nitroWind.store.getTheme() : undefined
|
|
1069
|
+
const reducedMotion = deps.reducedMotion ? nitroWind.store.getReducedMotion() : undefined
|
|
1070
|
+
const viewport =
|
|
1071
|
+
deps.breakpoints.length > 0 || deps.orientation || deps.viewport || deps.variables.length > 0
|
|
1072
|
+
? nitroWind.store.getViewportSize()
|
|
1073
|
+
: undefined
|
|
1074
|
+
return nitroWind.resolve(className, {
|
|
1075
|
+
platform: nitroWind.environment.platform,
|
|
1076
|
+
theme: themeState?.theme,
|
|
1077
|
+
colorScheme: themeState?.colorScheme,
|
|
1078
|
+
reducedMotion,
|
|
1079
|
+
viewport,
|
|
1080
|
+
})
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
type ClassValue = string | false | null | undefined | 0 | ClassValue[]
|
|
1084
|
+
|
|
1085
|
+
function flattenClassValues(values: readonly ClassValue[], out: string[]): void {
|
|
1086
|
+
for (const value of values) {
|
|
1087
|
+
if (!value) continue
|
|
1088
|
+
if (Array.isArray(value)) {
|
|
1089
|
+
flattenClassValues(value, out)
|
|
1090
|
+
} else {
|
|
1091
|
+
for (const token of value.split(/\s+/)) {
|
|
1092
|
+
if (token) out.push(token)
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/** Splits a raw class token into its canonical variant key and bare utility (without `!`). */
|
|
1099
|
+
function splitVariantAndUtility(raw: string): [variantKey: string, utility: string] {
|
|
1100
|
+
const variants: string[] = []
|
|
1101
|
+
let bracketDepth = 0
|
|
1102
|
+
let parenDepth = 0
|
|
1103
|
+
let start = 0
|
|
1104
|
+
for (let i = 0; i < raw.length; i++) {
|
|
1105
|
+
const char = raw[i]
|
|
1106
|
+
if (char === '[') bracketDepth++
|
|
1107
|
+
else if (char === ']') bracketDepth = Math.max(0, bracketDepth - 1)
|
|
1108
|
+
else if (char === '(') parenDepth++
|
|
1109
|
+
else if (char === ')') parenDepth = Math.max(0, parenDepth - 1)
|
|
1110
|
+
else if (char === ':' && bracketDepth === 0 && parenDepth === 0) {
|
|
1111
|
+
variants.push(raw.slice(start, i))
|
|
1112
|
+
start = i + 1
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
let utility = raw.slice(start)
|
|
1116
|
+
if (utility.startsWith('!')) utility = utility.slice(1)
|
|
1117
|
+
else if (utility.endsWith('!')) utility = utility.slice(0, -1)
|
|
1118
|
+
const variantKey = variants.length === 0 ? '' : variants.length === 1 ? variants[0]! : variants.sort().join(':')
|
|
1119
|
+
return [variantKey, utility]
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
interface CustomUtilityConflicts {
|
|
1123
|
+
readonly conflicts: readonly UtilityConflict[]
|
|
1124
|
+
/** True when the custom utility has nested `@variant`, variant-prefixed `@apply`, or unclassifiable declarations. */
|
|
1125
|
+
readonly opaque: boolean
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
function collectCustomUtilityConflicts(
|
|
1129
|
+
def: CSSCustomClassDefinition,
|
|
1130
|
+
tokens: Tokens,
|
|
1131
|
+
customClasses: Readonly<Record<string, CSSCustomClassDefinition>>,
|
|
1132
|
+
visiting = new Set<string>(),
|
|
1133
|
+
): CustomUtilityConflicts {
|
|
1134
|
+
const conflicts: UtilityConflict[] = []
|
|
1135
|
+
let opaque = false
|
|
1136
|
+
|
|
1137
|
+
for (const entry of def.entries) {
|
|
1138
|
+
if (entry.kind === 'variant') {
|
|
1139
|
+
opaque = true
|
|
1140
|
+
continue
|
|
1141
|
+
}
|
|
1142
|
+
if (entry.kind === 'declaration') {
|
|
1143
|
+
const conflict = classifyRawDeclaration(entry.property)
|
|
1144
|
+
if (conflict === null) opaque = true
|
|
1145
|
+
else conflicts.push(conflict)
|
|
1146
|
+
continue
|
|
1147
|
+
}
|
|
1148
|
+
for (const applied of entry.classes) {
|
|
1149
|
+
const [variants, util] = splitRawClass(applied)
|
|
1150
|
+
if (variants.length > 0) {
|
|
1151
|
+
opaque = true
|
|
1152
|
+
continue
|
|
1153
|
+
}
|
|
1154
|
+
if (Object.prototype.hasOwnProperty.call(customClasses, util)) {
|
|
1155
|
+
if (visiting.has(util)) continue
|
|
1156
|
+
visiting.add(util)
|
|
1157
|
+
const nested = collectCustomUtilityConflicts(customClasses[util]!, tokens, customClasses, visiting)
|
|
1158
|
+
visiting.delete(util)
|
|
1159
|
+
if (nested.opaque) opaque = true
|
|
1160
|
+
for (const c of nested.conflicts) conflicts.push(c)
|
|
1161
|
+
} else {
|
|
1162
|
+
const conflict = classifyUtility(util, tokens)
|
|
1163
|
+
if (conflict === null) opaque = true
|
|
1164
|
+
else conflicts.push(conflict)
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
return { conflicts, opaque }
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* Joins class names, skipping falsy values, enforcing component-vs-utility rank
|
|
1174
|
+
* (`.class` / `@layer components` always precede utilities and `@utility`), and
|
|
1175
|
+
* deduplicating conflicting utilities under the same variant so later classes win.
|
|
1176
|
+
*/
|
|
1177
|
+
export function cn(...values: ClassValue[]): string {
|
|
1178
|
+
const rawTokens: string[] = []
|
|
1179
|
+
flattenClassValues(values, rawTokens)
|
|
1180
|
+
if (rawTokens.length <= 1) return rawTokens[0] ?? ''
|
|
1181
|
+
|
|
1182
|
+
const nitroWind = getNitroWind()
|
|
1183
|
+
const tokens = nitroWind.tokens
|
|
1184
|
+
const customClasses = customClassesByInstance.get(nitroWind)
|
|
1185
|
+
const superseded = new Set<string>()
|
|
1186
|
+
const seenComponents = new Set<string>()
|
|
1187
|
+
const seenCustomUtilities = new Set<string>()
|
|
1188
|
+
const keptComponents: string[] = []
|
|
1189
|
+
const keptUtilities: string[] = []
|
|
1190
|
+
|
|
1191
|
+
for (let i = rawTokens.length - 1; i >= 0; i--) {
|
|
1192
|
+
const raw = rawTokens[i]!
|
|
1193
|
+
const [variantKey, utility] = splitVariantAndUtility(raw)
|
|
1194
|
+
const customDef =
|
|
1195
|
+
customClasses !== undefined && Object.prototype.hasOwnProperty.call(customClasses, utility)
|
|
1196
|
+
? customClasses[utility]
|
|
1197
|
+
: undefined
|
|
1198
|
+
|
|
1199
|
+
if (customDef !== undefined && customDef.rank === 'component') {
|
|
1200
|
+
const compKey = `${variantKey}\0${utility}`
|
|
1201
|
+
if (seenComponents.has(compKey)) continue
|
|
1202
|
+
seenComponents.add(compKey)
|
|
1203
|
+
keptComponents.push(raw)
|
|
1204
|
+
continue
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
if (customDef !== undefined && customDef.rank === 'utility') {
|
|
1208
|
+
const customKey = `${variantKey}\0${utility}`
|
|
1209
|
+
if (seenCustomUtilities.has(customKey)) continue
|
|
1210
|
+
const { conflicts, opaque } = collectCustomUtilityConflicts(customDef, tokens, customClasses!, new Set([utility]))
|
|
1211
|
+
if (!opaque && conflicts.length > 0 && conflicts.every((c) => superseded.has(`${variantKey}\0${c.group}`))) {
|
|
1212
|
+
continue
|
|
1213
|
+
}
|
|
1214
|
+
seenCustomUtilities.add(customKey)
|
|
1215
|
+
keptUtilities.push(raw)
|
|
1216
|
+
for (const conflict of conflicts) {
|
|
1217
|
+
superseded.add(`${variantKey}\0${conflict.group}`)
|
|
1218
|
+
if (conflict.overrides !== undefined) {
|
|
1219
|
+
for (const overridden of conflict.overrides) {
|
|
1220
|
+
superseded.add(`${variantKey}\0${overridden}`)
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
continue
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
const conflict = classifyUtility(utility, tokens)
|
|
1228
|
+
if (conflict === null) {
|
|
1229
|
+
keptUtilities.push(raw)
|
|
1230
|
+
continue
|
|
1231
|
+
}
|
|
1232
|
+
const key = `${variantKey}\0${conflict.group}`
|
|
1233
|
+
if (superseded.has(key)) continue
|
|
1234
|
+
keptUtilities.push(raw)
|
|
1235
|
+
superseded.add(key)
|
|
1236
|
+
if (conflict.overrides !== undefined) {
|
|
1237
|
+
for (const overridden of conflict.overrides) {
|
|
1238
|
+
superseded.add(`${variantKey}\0${overridden}`)
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
keptComponents.reverse()
|
|
1244
|
+
keptUtilities.reverse()
|
|
1245
|
+
if (keptComponents.length === 0) return keptUtilities.join(' ')
|
|
1246
|
+
if (keptUtilities.length === 0) return keptComponents.join(' ')
|
|
1247
|
+
return `${keptComponents.join(' ')} ${keptUtilities.join(' ')}`
|
|
1248
|
+
}
|