0
# Core Processing
1
2
The Processor class is the heart of WindiCSS, handling CSS generation, configuration management, and utility processing. It provides methods for extracting styles, testing utilities, interpreting class names, and generating CSS output.
3
4
## Capabilities
5
6
### Processor Constructor
7
8
Creates a new WindiCSS processor instance with optional configuration.
9
10
```typescript { .api }
11
/**
12
* Creates a new WindiCSS processor instance
13
* @param config - Optional configuration object
14
*/
15
constructor(config?: Config);
16
```
17
18
**Usage Example:**
19
20
```typescript
21
import Processor from "windicss";
22
23
// Basic processor
24
const processor = new Processor();
25
26
// Processor with custom configuration
27
const processor = new Processor({
28
theme: {
29
extend: {
30
colors: {
31
primary: "#3b82f6"
32
}
33
}
34
},
35
plugins: [
36
// custom plugins
37
]
38
});
39
```
40
41
### Style Extraction
42
43
Extracts CSS styles for a given class name, returning Style objects that can be converted to CSS.
44
45
```typescript { .api }
46
/**
47
* Extracts CSS styles for a given class name
48
* @param className - The utility class name to extract styles for
49
* @param addComment - Whether to add comments to the generated styles
50
* @param prefix - Optional prefix to remove from class name
51
* @returns Style object(s) or undefined if class is not valid
52
*/
53
extract(className: string, addComment?: boolean, prefix?: string): Style | Style[] | undefined;
54
```
55
56
**Usage Examples:**
57
58
```typescript
59
// Extract styles for a utility class
60
const styles = processor.extract("bg-blue-500");
61
if (styles) {
62
console.log(styles.build()); // ".bg-blue-500 { background-color: #3b82f6; }"
63
}
64
65
// Extract styles with comments
66
const stylesWithComments = processor.extract("p-4", true);
67
68
// Extract with custom prefix handling
69
const prefixedStyles = processor.extract("tw-m-2", false, "tw-");
70
```
71
72
### Class Testing
73
74
Tests if a class name is a valid WindiCSS utility without generating styles.
75
76
```typescript { .api }
77
/**
78
* Tests if a class name is a valid WindiCSS utility
79
* @param className - The class name to test
80
* @param prefix - Optional prefix to remove from class name
81
* @returns True if the class is valid, false otherwise
82
*/
83
test(className: string, prefix?: string): boolean;
84
```
85
86
**Usage Example:**
87
88
```typescript
89
// Test standard utilities
90
console.log(processor.test("bg-red-500")); // true
91
console.log(processor.test("invalid-class")); // false
92
93
// Test with prefix
94
console.log(processor.test("tw-p-4", "tw-")); // true
95
```
96
97
### Class Interpretation
98
99
Processes a string of class names into CSS styles, tracking successful and ignored classes.
100
101
```typescript { .api }
102
/**
103
* Processes class names into CSS styles with detailed results
104
* @param classNames - Space-separated string of class names
105
* @param ignoreProcessed - Whether to skip already processed classes
106
* @param handleIgnored - Optional function to handle ignored classes
107
* @returns Object with success/ignored arrays and generated StyleSheet
108
*/
109
interpret(
110
classNames: string,
111
ignoreProcessed?: boolean,
112
handleIgnored?: (ignored: string) => Style | Style[] | undefined
113
): InterpretResult;
114
115
interface InterpretResult {
116
success: string[];
117
ignored: string[];
118
styleSheet: StyleSheet;
119
}
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
// Basic interpretation
126
const result = processor.interpret("bg-blue-500 text-white p-4 hover:bg-blue-600");
127
console.log(result.success); // ["bg-blue-500", "text-white", "p-4", "hover:bg-blue-600"]
128
console.log(result.ignored); // []
129
console.log(result.styleSheet.build()); // Generated CSS
130
131
// Handle ignored classes
132
const resultWithHandler = processor.interpret(
133
"bg-blue-500 custom-class p-4",
134
false,
135
(ignored) => {
136
console.log(`Ignored class: ${ignored}`);
137
return undefined; // or return custom styles
138
}
139
);
140
141
// Skip processed classes for performance
142
const resultOptimized = processor.interpret("bg-red-500 text-black", true);
143
```
144
145
### Class Compilation
146
147
Compiles multiple class names into a single CSS class with a generated name, useful for atomic CSS approaches.
148
149
```typescript { .api }
150
/**
151
* Compiles multiple class names into a single CSS class
152
* @param classNames - Space-separated string of class names
153
* @param prefix - Prefix for generated class name (default: 'windi-')
154
* @param showComment - Whether to add comments to generated styles
155
* @param ignoreGenerated - Whether to skip if already generated
156
* @param handleIgnored - Optional function to handle ignored classes
157
* @param outputClassName - Custom output class name
158
* @returns Object with results and generated class name
159
*/
160
compile(
161
classNames: string,
162
prefix?: string,
163
showComment?: boolean,
164
ignoreGenerated?: boolean,
165
handleIgnored?: (ignored: string) => Style | Style[] | undefined,
166
outputClassName?: string
167
): CompileResult;
168
169
interface CompileResult {
170
success: string[];
171
ignored: string[];
172
className?: string;
173
styleSheet: StyleSheet;
174
}
175
```
176
177
**Usage Examples:**
178
179
```typescript
180
// Basic compilation
181
const result = processor.compile("bg-blue-500 text-white p-4 rounded-lg");
182
console.log(result.className); // "windi-abc123"
183
console.log(result.styleSheet.build()); // CSS with .windi-abc123 selector
184
185
// Custom prefix and class name
186
const customResult = processor.compile(
187
"flex items-center justify-between",
188
"my-prefix-",
189
false,
190
false,
191
undefined,
192
"navigation-bar"
193
);
194
console.log(customResult.className); // "navigation-bar"
195
```
196
197
### Preflight Generation
198
199
Generates preflight/base styles for CSS reset and normalization.
200
201
```typescript { .api }
202
/**
203
* Generates preflight/base styles for CSS reset
204
* @param html - HTML content to analyze for used classes
205
* @param includeBase - Whether to include base styles
206
* @param includeGlobal - Whether to include global styles
207
* @param includePlugins - Whether to include plugin-provided base styles
208
* @param ignoreProcessed - Whether to skip if already processed
209
* @returns StyleSheet with preflight styles
210
*/
211
preflight(
212
html?: string,
213
includeBase?: boolean,
214
includeGlobal?: boolean,
215
includePlugins?: boolean,
216
ignoreProcessed?: boolean
217
): StyleSheet;
218
```
219
220
**Usage Examples:**
221
222
```typescript
223
// Generate full preflight
224
const preflightStyles = processor.preflight();
225
console.log(preflightStyles.build());
226
227
// Generate preflight for specific HTML
228
const htmlContent = '<div class="container mx-auto p-4">Content</div>';
229
const contextualPreflight = processor.preflight(htmlContent, true, true, true);
230
231
// Generate only base styles
232
const baseOnly = processor.preflight(undefined, true, false, false);
233
```
234
235
### Attributify Processing
236
237
Processes attributify syntax from HTML attributes into CSS styles.
238
239
```typescript { .api }
240
/**
241
* Processes attributify syntax from HTML attributes
242
* @param attrs - Object with attribute names as keys and values as strings or arrays
243
* @param ignoreProcessed - Whether to skip already processed attributes
244
* @returns Object with success/ignored arrays and generated StyleSheet
245
*/
246
attributify(
247
attrs: Record<string, string | string[]>,
248
ignoreProcessed?: boolean
249
): AttributifyResult;
250
251
interface AttributifyResult {
252
success: string[];
253
ignored: string[];
254
styleSheet: StyleSheet;
255
}
256
```
257
258
**Usage Example:**
259
260
```typescript
261
// Process attributify attributes
262
const attrs = {
263
"bg": "blue-500",
264
"text": "white",
265
"p": "4",
266
"hover:bg": "blue-600"
267
};
268
269
const result = processor.attributify(attrs);
270
console.log(result.success); // Attribute selectors that were processed
271
console.log(result.styleSheet.build()); // Generated CSS with attribute selectors
272
```
273
274
### Validation
275
276
Validates class names and returns detailed information about each class.
277
278
```typescript { .api }
279
/**
280
* Validates class names and returns detailed results
281
* @param classNames - Space-separated string of class names to validate
282
* @returns Object with arrays of successful and ignored validations with details
283
*/
284
validate(classNames: string): ValidationResult;
285
286
interface ValidationResult {
287
success: Validata[];
288
ignored: Validata[];
289
}
290
291
interface Validata {
292
className: string;
293
type: 'utility' | 'group' | 'alias';
294
variants: string[];
295
content: string | string[];
296
raw: string;
297
important: boolean;
298
parent?: Element;
299
}
300
```
301
302
**Usage Example:**
303
304
```typescript
305
const validation = processor.validate("bg-blue-500 hover:text-white invalid-class");
306
console.log(validation.success); // Detailed info about valid classes
307
console.log(validation.ignored); // Detailed info about invalid classes
308
309
validation.success.forEach(item => {
310
console.log(`Valid: ${item.className}, Type: ${item.type}, Variants: ${item.variants.join(':')}`);
311
});
312
```
313
314
### Configuration Methods
315
316
Methods for accessing and managing processor configuration.
317
318
```typescript { .api }
319
/**
320
* Gets configuration value by path
321
* @param path - Dot-separated path to configuration value
322
* @param defaultValue - Default value if path doesn't exist
323
* @returns Configuration value or default
324
*/
325
config(path: string, defaultValue?: any): any;
326
327
/**
328
* Gets theme value by path
329
* @param path - Dot-separated path to theme value
330
* @param defaultValue - Default value if path doesn't exist
331
* @returns Theme value or default
332
*/
333
theme(path: string, defaultValue?: any): any;
334
335
/**
336
* Loads new configuration into the processor
337
* @param config - Configuration object to load
338
* @returns Resolved configuration
339
*/
340
loadConfig(config?: Config): Config;
341
342
/**
343
* Resolves configuration with presets
344
* @param config - User configuration
345
* @param presets - Preset configurations
346
* @returns Resolved configuration
347
*/
348
resolveConfig(config: Config | undefined, presets: Config): Config;
349
```
350
351
**Usage Examples:**
352
353
```typescript
354
// Access configuration values
355
const separator = processor.config('separator', ':');
356
const primaryColor = processor.theme('colors.primary', '#000000');
357
358
// Load new configuration
359
processor.loadConfig({
360
theme: {
361
extend: {
362
spacing: {
363
'72': '18rem',
364
'84': '21rem',
365
'96': '24rem',
366
}
367
}
368
}
369
});
370
```
371
372
### Getters
373
374
Readonly properties for accessing processed configuration and variants.
375
376
```typescript { .api }
377
/**
378
* Complete resolved configuration object
379
*/
380
get allConfig(): Config;
381
382
/**
383
* Complete resolved theme object
384
*/
385
get allTheme(): Theme;
386
387
/**
388
* Array of all available variant names
389
*/
390
get allVariant(): string[];
391
```
392
393
**Usage Example:**
394
395
```typescript
396
const config = processor.allConfig;
397
const theme = processor.allTheme;
398
const availableVariants = processor.allVariant;
399
400
console.log('Available variants:', availableVariants);
401
```
402
403
### Configuration Management
404
405
Advanced configuration loading and resolution methods.
406
407
```typescript { .api }
408
/**
409
* Loads new configuration into the processor
410
* @param config - Configuration object to load
411
* @returns Loaded configuration
412
*/
413
loadConfig(config?: Config): Config;
414
415
/**
416
* Resolves configuration with presets and inheritance
417
* @param config - User configuration
418
* @param presets - Base preset configuration
419
* @returns Resolved configuration
420
*/
421
resolveConfig(config: Config | undefined, presets: Config): Config;
422
```
423
424
### Validation and Testing
425
426
Methods for validating and testing class names and configuration.
427
428
```typescript { .api }
429
/**
430
* Validates class names and returns detailed validation results
431
* @param classNames - Space-separated class names to validate
432
* @returns Validation results with success and error details
433
*/
434
validate(classNames: string): ValidationResult;
435
436
/**
437
* Tests if a class name is valid
438
* @param className - Single class name to test
439
* @param prefix - Optional prefix to consider
440
* @returns True if class name is valid
441
*/
442
test(className: string, prefix?: string): boolean;
443
444
/**
445
* Checks if a core plugin is enabled
446
* @param path - Plugin path to check
447
* @returns True if plugin is enabled
448
*/
449
corePlugins(path: string): boolean;
450
451
/**
452
* Gets variants for a specific utility
453
* @param path - Utility path
454
* @param defaultValue - Default variants if none found
455
* @returns Array of variant names
456
*/
457
variants(path: string, defaultValue?: string[]): string[];
458
459
interface ValidationResult {
460
success: Validata[];
461
ignored: Validata[];
462
}
463
464
interface Validata {
465
className: string;
466
raw: string;
467
start: number;
468
end: number;
469
variants: string[];
470
content?: Element[] | string;
471
func?: string;
472
type: 'group' | 'func' | 'utility' | 'alias';
473
important: boolean;
474
parent?: Element;
475
}
476
```
477
478
### Utility Methods
479
480
Helper methods for string manipulation and style processing.
481
482
```typescript { .api }
483
/**
484
* Removes configured prefix from class name
485
* @param className - Class name to process
486
* @returns Class name without prefix
487
*/
488
removePrefix(className: string): string;
489
490
/**
491
* Marks a style as important based on configuration
492
* @param style - Style object to mark
493
* @param force - Force importance (boolean or selector string)
494
* @returns Modified style object
495
*/
496
markAsImportant(style: Style, force?: boolean | string): Style;
497
498
/**
499
* Wraps styles with variant conditions
500
* @param variants - Array of variant names to apply
501
* @param styles - Style or array of styles to wrap
502
* @returns Array of wrapped styles
503
*/
504
wrapWithVariants(variants: string[], styles: Style | Style[]): Style[] | undefined;
505
506
/**
507
* Escapes CSS selector characters
508
* @param selector - Selector string to escape
509
* @returns Escaped selector
510
*/
511
e(selector: string): string;
512
513
/**
514
* Adds configured prefix to selector
515
* @param selector - Selector to prefix
516
* @returns Prefixed selector
517
*/
518
prefix(selector: string): string;
519
520
/**
521
* Serializes current configuration to string
522
* @returns Configuration as executable JavaScript string
523
*/
524
dumpConfig(): string;
525
```
526
527
### Plugin Utilities
528
529
Access to plugin utilities for advanced usage.
530
531
```typescript { .api }
532
/**
533
* Plugin utilities instance for programmatic plugin development
534
*/
535
readonly pluginUtils: PluginUtils;
536
537
/**
538
* Variant utilities instance for custom variant creation
539
*/
540
readonly variantUtils: VariantUtils;
541
542
interface PluginUtils {
543
addDynamic(key: string, generator: UtilityGenerator, options?: PluginUtilOptions): UtilityGenerator;
544
addUtilities(utilities: Record<string, any>, options?: PluginUtilOptions): Style[];
545
addComponents(components: Record<string, any>, options?: PluginUtilOptions): Style[];
546
addBase(baseStyles: Record<string, any>): Style[];
547
addVariant(name: string, generator: VariantGenerator): Style | Style[];
548
e(selector: string): string;
549
prefix(selector: string): string;
550
config(path: string, defaultValue?: any): any;
551
theme(path: string, defaultValue?: any): any;
552
variants(path: string, defaultValue?: string[]): string[];
553
}
554
555
interface VariantUtils {
556
modifySelectors(modifier: (args: { className: string }) => string): Style;
557
atRule(name: string): Style;
558
pseudoClass(name: string): Style;
559
pseudoElement(name: string): Style;
560
parent(name: string): Style;
561
child(name: string): Style;
562
}
563
```
564
565
**Usage Examples:**
566
567
```typescript
568
// Advanced validation
569
const validation = processor.validate("hover:bg-blue-500 invalid-class md:text-lg");
570
console.log(validation.success); // Valid classes with metadata
571
console.log(validation.ignored); // Invalid classes with reasons
572
573
// Configuration management
574
const newConfig = processor.loadConfig({
575
theme: { extend: { colors: { custom: '#123456' } } }
576
});
577
578
// Plugin utilities access
579
processor.pluginUtils.addUtilities({
580
'.custom-utility': { color: 'red' }
581
});
582
583
// Variant wrapping
584
const baseStyle = new Style('.test', new Property('color', 'blue'));
585
const wrappedStyles = processor.wrapWithVariants(['hover', 'md'], baseStyle);
586
587
// Configuration serialization
588
const configString = processor.dumpConfig();
589
console.log(configString); // JavaScript configuration export
590
```