0
# Utility Functions
1
2
Color parsing, value handling, and CSS generation utilities for advanced use cases, custom rule creation, and integration with the UnoCSS ecosystem.
3
4
## Capabilities
5
6
### Color Parsing
7
8
Advanced color parsing functionality for theme colors, arbitrary colors, and opacity handling.
9
10
```typescript { .api }
11
/**
12
* Parse color string into structured color data
13
* @param body - Color string to be parsed (e.g., 'red-500', 'red-500/20', '[#ff0000]')
14
* @param theme - Theme object containing color definitions
15
* @param key - Optional theme key to search in (colors, backgroundColor, etc.)
16
* @returns Parsed color data or undefined if not parseable
17
*/
18
function parseColor(body: string, theme: Theme, key?: ThemeColorKeys): ParsedColorValue | undefined;
19
20
interface ParsedColorValue {
21
/** Opacity value if specified (e.g., '20' from 'red-500/20') */
22
opacity?: string;
23
/** Base color name (e.g., 'red' from 'red-500') */
24
name: string;
25
/** Color scale number (e.g., '500' from 'red-500') */
26
no: string;
27
/** Resolved color value (e.g., '#ef4444') */
28
color?: string;
29
/** Parsed CSS color object with RGBA components */
30
cssColor?: CSSColorValue;
31
/** Processed alpha/opacity value */
32
alpha?: string;
33
}
34
35
type ThemeColorKeys = 'colors' | 'borderColor' | 'backgroundColor' | 'textColor' | 'shadowColor' | 'accentColor';
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { parseColor } from "@unocss/preset-mini/utils";
42
import { theme } from "@unocss/preset-mini/theme";
43
44
// Parse theme color
45
const redColor = parseColor('red-500', theme);
46
// { opacity: undefined, name: 'red', no: '500', color: '#ef4444', ... }
47
48
// Parse color with opacity
49
const redWithOpacity = parseColor('red-500/20', theme);
50
// { opacity: '20', name: 'red', no: '500', color: '#ef4444', alpha: '0.2', ... }
51
52
// Parse arbitrary color
53
const customColor = parseColor('[#ff6b35]', theme);
54
// { opacity: undefined, name: '#ff6b35', color: '#ff6b35', ... }
55
56
// Parse hex shorthand
57
const hexColor = parseColor('hex-ff6b35', theme);
58
// { opacity: undefined, name: 'hex-ff6b35', color: '#ff6b35', ... }
59
60
// Parse CSS variable
61
const varColor = parseColor('$primary-color', theme);
62
// { opacity: undefined, name: '$primary-color', color: 'var(--primary-color)', ... }
63
```
64
65
### Value Handlers
66
67
Comprehensive value processing system for converting utility values to CSS values.
68
69
```typescript { .api }
70
/** Main value handler function combining all processing capabilities */
71
const handler: ValueHandler;
72
73
/** Alias for handler function */
74
const h: ValueHandler;
75
76
/** Collection of individual value handler functions */
77
const valueHandlers: ValueHandlers;
78
79
interface ValueHandler {
80
/** Process bracket notation values [value] */
81
bracket: (str: string) => string | undefined;
82
/** Process color bracket values [color] */
83
bracketOfColor: (str: string) => string | undefined;
84
/** Process length bracket values [length] */
85
bracketOfLength: (str: string) => string | undefined;
86
/** Process position bracket values [position] */
87
bracketOfPosition: (str: string) => string | undefined;
88
/** Process CSS variable syntax $variable */
89
cssvar: (str: string) => string | undefined;
90
/** Process number values */
91
number: (str: string) => string | undefined;
92
/** Process number with unit values */
93
numberWithUnit: (str: string) => string | undefined;
94
/** Process auto values */
95
auto: (str: string) => string | undefined;
96
/** Process rem values with 1/4 scale */
97
rem: (str: string) => string | undefined;
98
/** Process px values */
99
px: (str: string) => string | undefined;
100
/** Process percentage values */
101
percent: (str: string) => string | undefined;
102
/** Process fraction values (1/2, 3/4, etc.) */
103
fraction: (str: string) => string | undefined;
104
/** Process global CSS keywords */
105
global: (str: string) => string | undefined;
106
/** Process time values (s, ms) */
107
time: (str: string) => string | undefined;
108
/** Process degree values (deg, rad, turn) */
109
degree: (str: string) => string | undefined;
110
/** Process CSS property names */
111
properties: (str: string) => string | undefined;
112
/** Process position keywords */
113
position: (str: string) => string | undefined;
114
}
115
```
116
117
**Usage Examples:**
118
119
```typescript
120
import { h, handler } from "@unocss/preset-mini/utils";
121
122
// Process various value types
123
const pixelValue = h.px('16'); // '16px'
124
const remValue = h.rem('4'); // '1rem' (4 * 0.25rem)
125
const fractionValue = h.fraction('1/2'); // '50%'
126
const bracketValue = h.bracket('[calc(100vw-2rem)]'); // 'calc(100vw - 2rem)'
127
const autoValue = h.auto('auto'); // 'auto'
128
129
// Chain multiple handlers
130
const complexValue = h.bracket.cssvar.global.auto.fraction.rem('4');
131
// Tries bracket, then cssvar, then global, then auto, then fraction, then rem
132
```
133
134
### Direction and Mapping Utilities
135
136
Mapping objects and utilities for handling directional CSS properties and coordinate systems.
137
138
```typescript { .api }
139
/** Direction mapping for CSS properties (left, right, top, bottom, etc.) */
140
const directionMap: Record<string, string[]>;
141
142
/** Inset positioning mappings */
143
const insetMap: Record<string, string[]>;
144
145
/** Corner/border radius mappings */
146
const cornerMap: Record<string, string[]>;
147
148
/** Transform coordinate mappings (x, y, z) */
149
const xyzMap: Record<string, string[]>;
150
151
/** Transform coordinate array */
152
const xyzArray: string[];
153
154
/** Background/object position mappings */
155
const positionMap: Record<string, string>;
156
157
/** CSS global keywords */
158
const globalKeywords: string[];
159
160
/** CSS math function regex */
161
const cssMathFnRE: RegExp;
162
163
/** CSS variable function regex */
164
const cssVarFnRE: RegExp;
165
```
166
167
**Usage Examples:**
168
169
```typescript
170
import { directionMap, xyzMap, globalKeywords } from "@unocss/preset-mini/utils";
171
172
// Direction mapping usage
173
console.log(directionMap['x']); // ['-left', '-right']
174
console.log(directionMap['t']); // ['-top']
175
176
// Transform coordinate mapping
177
console.log(xyzMap['x']); // ['-x']
178
console.log(xyzMap['']); // ['-x', '-y'] (default x and y)
179
180
// Check for global keywords
181
console.log(globalKeywords.includes('inherit')); // true
182
```
183
184
### Advanced Utility Functions
185
186
Specialized utility functions for complex CSS generation scenarios.
187
188
```typescript { .api }
189
/**
190
* Create direction-based size utility matcher
191
* @param propertyPrefix - CSS property prefix (e.g., 'margin', 'padding')
192
* @returns Dynamic matcher function for directional sizing
193
*/
194
function directionSize(propertyPrefix: string): DynamicMatcher;
195
196
/**
197
* Create color resolver for CSS properties
198
* @param property - CSS property name (e.g., 'background-color')
199
* @param varName - Base name for opacity variable (e.g., 'bg')
200
* @param key - Optional theme key to search in
201
* @param shouldPass - Optional validation function
202
* @returns Dynamic matcher for color values
203
*/
204
function colorResolver(
205
property: string,
206
varName: string,
207
key?: ThemeColorKeys,
208
shouldPass?: (css: CSSObject) => boolean
209
): DynamicMatcher;
210
211
/**
212
* Apply color variables to shadow values
213
* @param shadows - Shadow value(s) to process
214
* @param colorVar - CSS variable name for color
215
* @returns Processed shadow values with color variables
216
*/
217
function colorableShadows(shadows: string | string[], colorVar: string): string[];
218
219
/**
220
* Check if color string is parseable
221
* @param color - Color string to check
222
* @param theme - Theme object
223
* @param key - Theme key to search in
224
* @returns Whether color can be parsed
225
*/
226
function hasParseableColor(color: string | undefined, theme: Theme, key: ThemeColorKeys): boolean;
227
228
/**
229
* Resolve breakpoints from theme/config
230
* @param context - Variant context with theme and generator
231
* @param key - Breakpoint key ('breakpoints' or 'verticalBreakpoints')
232
* @returns Resolved and sorted breakpoint array
233
*/
234
function resolveBreakpoints(
235
context: Readonly<VariantContext<Theme>>,
236
key?: 'breakpoints' | 'verticalBreakpoints'
237
): { point: string, size: string }[] | undefined;
238
239
/**
240
* Resolve vertical breakpoints specifically
241
* @param context - Variant context
242
* @returns Resolved vertical breakpoints
243
*/
244
function resolveVerticalBreakpoints(context: Readonly<VariantContext<Theme>>): { point: string, size: string }[] | undefined;
245
246
/**
247
* Create global static rules for CSS keywords
248
* @param prefix - Utility prefix
249
* @param property - CSS property name (defaults to prefix)
250
* @returns Array of static rules
251
*/
252
function makeGlobalStaticRules(prefix: string, property?: string): StaticRule[];
253
254
/**
255
* Check if value is a CSS math function
256
* @param value - Value to check
257
* @returns Whether value is a CSS math function (calc, min, max, clamp)
258
*/
259
function isCSSMathFn(value: string | undefined): boolean;
260
261
/**
262
* Check if string represents a size value
263
* @param str - String to check
264
* @returns Whether string is a valid size value
265
*/
266
function isSize(str: string): boolean;
267
268
/**
269
* Transform XYZ coordinate values
270
* @param d - Direction (x, y, z, or empty)
271
* @param v - Value to transform
272
* @param name - CSS variable base name
273
* @returns Array of CSS variable entries
274
*/
275
function transformXYZ(d: string, v: string, name: string): [string, string][];
276
277
/**
278
* Split utility shorthand delimited by / or :
279
* @param body - Shorthand string to split
280
* @param type - Expected type for validation
281
* @returns Split parts or undefined if invalid
282
*/
283
function splitShorthand(body: string, type: string): [string, string] | undefined;
284
285
/** Control flag for disabling negative values */
286
const CONTROL_MINI_NO_NEGATIVE: string;
287
```
288
289
**Usage Examples:**
290
291
```typescript
292
import {
293
directionSize,
294
colorResolver,
295
isCSSMathFn,
296
transformXYZ,
297
makeGlobalStaticRules
298
} from "@unocss/preset-mini/utils";
299
300
// Create margin utility matcher
301
const marginMatcher = directionSize('margin');
302
// Usage in rule: ['m', marginMatcher] matches m-4, mx-2, mt-auto, etc.
303
304
// Create background color resolver
305
const bgColorResolver = colorResolver('background-color', 'bg');
306
// Usage in rule: ['bg', bgColorResolver] matches bg-red-500, bg-blue/50, etc.
307
308
// Check for CSS math functions
309
console.log(isCSSMathFn('calc(100% - 2rem)')); // true
310
console.log(isCSSMathFn('16px')); // false
311
312
// Transform coordinate values
313
const scaleValues = transformXYZ('', '1.5', 'scale');
314
// Returns: [['--un-scale-x', '1.5'], ['--un-scale-y', '1.5']]
315
316
// Create global static rules
317
const displayRules = makeGlobalStaticRules('display');
318
// Returns rules for display-inherit, display-initial, display-unset, etc.
319
```
320
321
## Re-exported Rule Utils
322
323
All utilities from `@unocss/rule-utils` are re-exported for convenient access to advanced rule creation functionality:
324
325
```typescript { .api }
326
// Re-exported from @unocss/rule-utils
327
export * from '@unocss/rule-utils';
328
```
329
330
This includes functions like:
331
- `createValueHandler`
332
- `colorToString`
333
- `colorOpacityToString`
334
- `parseCssColor`
335
- `getStringComponent`
336
- `getStringComponents`
337
- And many more advanced rule utilities
338
339
## Integration with Rules
340
341
These utility functions are extensively used throughout the preset's rule definitions:
342
343
```typescript
344
// Example rule using utilities
345
[
346
'bg',
347
colorResolver('background-color', 'bg', 'backgroundColor')
348
]
349
350
// Direction-based spacing rule
351
[
352
'm',
353
directionSize('margin')
354
]
355
```
356
357
The utilities provide the foundation for the preset's comprehensive CSS generation capabilities, enabling flexible value processing, theme integration, and advanced CSS property handling.
358
359
## Types
360
361
```typescript { .api }
362
// Core UnoCSS types for utility functions
363
interface DynamicMatcher {
364
(match: string[], context: RuleContext<Theme>): CSSObject | string | undefined;
365
}
366
367
interface StaticRule {
368
0: string;
369
1: CSSObject;
370
meta?: any;
371
}
372
373
interface RuleContext<T = any> {
374
theme: T;
375
rawSelector: string;
376
currentSelector: string;
377
variantHandlers: VariantHandler[];
378
constructCSS: ConstructCSSFunction;
379
generator: UnoGenerator;
380
}
381
382
interface VariantContext<T = any> {
383
theme: T;
384
generator: UnoGenerator;
385
}
386
387
interface CSSObject {
388
[key: string]: string | number | CSSObject | undefined;
389
}
390
391
interface VariantHandler {
392
matcher: string;
393
selector?: string | ((input: string) => string);
394
parent?: string | [string, number];
395
layer?: string;
396
sort?: number;
397
}
398
399
type ConstructCSSFunction = (selector: string, css: CSSObject | string) => string;
400
401
interface UnoGenerator {
402
config: any;
403
userConfig: any;
404
}
405
```