/
types.ts
636 lines (555 loc) · 15.3 KB
/
types.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import type { LoadConfigResult } from 'unconfig'
import type MagicString from 'magic-string'
import type { UnoGenerator } from './generator'
import type { BetterMap } from './utils'
/* eslint-disable no-use-before-define */
export type Awaitable<T> = T | Promise<T>
export type Arrayable<T> = T | T[]
export type ArgumentType<T> = T extends ((...args: infer A) => any) ? A : never
export type Shift<T> = T extends [_: any, ...args: infer A] ? A : never
export type RestArgs<T> = Shift<ArgumentType<T>>
export type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]> }
export type FlatObjectTuple<T> = { [K in keyof T]: T[K] }
export type PartialByKeys<T, K extends keyof T = keyof T> = FlatObjectTuple<Partial<Pick<T, Extract<keyof T, K>>> & Omit<T, K>>
export type RequiredByKey<T, K extends keyof T = keyof T> = FlatObjectTuple<Required<Pick<T, Extract<keyof T, K>>> & Omit<T, K>>
export type CSSObject = Record<string, string | number | undefined>
export type CSSEntries = [string, string | number | undefined][]
export interface CSSColorValue {
type: string
components: (string | number)[]
alpha: string | number | undefined
}
export type RGBAColorValue = [number, number, number, number] | [number, number, number]
export interface ParsedColorValue {
/**
* Parsed color value.
*/
color?: string
/**
* Parsed opacity value.
*/
opacity: string
/**
* Color name.
*/
name: string
/**
* Color scale, preferrably 000 - 999.
*/
no: string
/**
* {@link CSSColorValue}
*/
cssColor: CSSColorValue | undefined
/**
* Parsed alpha value from opacity
*/
alpha: string | number | undefined
}
export type PresetOptions = Record<string, any>
export interface RuleContext<Theme extends {} = {}> {
/**
* Unprocessed selector from user input.
* Useful for generating CSS rule.
*/
rawSelector: string
/**
* Current selector for rule matching
*/
currentSelector: string
/**
* UnoCSS generator instance
*/
generator: UnoGenerator
/**
* The theme object
*/
theme: Theme
/**
* Matched variants handlers for this rule.
*/
variantHandlers: VariantHandler[]
/**
* The result of variant matching.
*/
variantMatch: VariantMatchedResult
/**
* Constrcut a custom CSS rule.
* Variants and selector escaping will be handled automatically.
*/
constructCSS: (body: CSSEntries | CSSObject, overrideSelector?: string) => string
/**
* Available only when `details` option is enabled.
*/
rules?: Rule[]
/**
* Available only when `details` option is enabled.
*/
shortcuts?: Shortcut[]
/**
* Available only when `details` option is enabled.
*/
variants?: Variant[]
}
export interface VariantContext<Theme extends {} = {}> {
/**
* Unprocessed selector from user input.
*/
rawSelector: string
/**
* UnoCSS generator instance
*/
generator: UnoGenerator
/**
* The theme object
*/
theme: Theme
}
export interface ExtractorContext {
readonly original: string
code: string
id?: string
}
export interface PreflightContext<Theme extends {} = {}> {
/**
* UnoCSS generator instance
*/
generator: UnoGenerator
/**
* The theme object
*/
theme: Theme
}
export interface Extractor {
name: string
extract(ctx: ExtractorContext): Awaitable<Set<string> | undefined>
order?: number
}
export interface RuleMeta {
/**
* The layer name of this rule.
* @default 'default'
*/
layer?: string
/**
* Option to not merge this selector even if the body are the same.
* @default false
*/
noMerge?: boolean
/**
* Fine tune sort
*/
sort?: number
/**
* Templates to provide autocomplete suggestions
*/
autocomplete?: Arrayable<AutoCompleteTemplate>
/**
* Internal rules will only be matched for shortcuts but not the user code.
* @default false
*/
internal?: boolean
}
export type CSSValues = CSSObject | CSSEntries | (CSSObject | CSSEntries)[]
export type DynamicMatcher<Theme extends {} = {}> = ((match: RegExpMatchArray, context: Readonly<RuleContext<Theme>>) => Awaitable<CSSValues | string | undefined>)
export type DynamicRule<Theme extends {} = {}> = [RegExp, DynamicMatcher<Theme>] | [RegExp, DynamicMatcher<Theme>, RuleMeta]
export type StaticRule = [string, CSSObject | CSSEntries] | [string, CSSObject | CSSEntries, RuleMeta]
export type Rule<Theme extends {} = {}> = DynamicRule<Theme> | StaticRule
export type DynamicShortcutMatcher<Theme extends {} = {}> = ((match: RegExpMatchArray, context: Readonly<RuleContext<Theme>>) => (string | string [] | undefined))
export type StaticShortcut = [string, string | string[]] | [string, string | string[], RuleMeta]
export type StaticShortcutMap = Record<string, string | string[]>
export type DynamicShortcut<Theme extends {} = {}> = [RegExp, DynamicShortcutMatcher<Theme>] | [RegExp, DynamicShortcutMatcher<Theme>, RuleMeta]
export type UserShortcuts<Theme extends {} = {}> = StaticShortcutMap | (StaticShortcut | DynamicShortcut<Theme> | StaticShortcutMap)[]
export type Shortcut<Theme extends {} = {}> = StaticShortcut | DynamicShortcut<Theme>
export type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null
export interface Preflight<Theme extends {} = {}> {
getCSS: (context: PreflightContext<Theme>) => Promise<string | undefined> | string | undefined
layer?: string
}
export type BlocklistRule = string | RegExp
export interface VariantHandler {
/**
* The result rewritten selector for the next round of matching
*/
matcher: string
/**
* Rewrite the output selector. Often be used to append pesudo classes or parents.
*/
selector?: (input: string, body: CSSEntries) => string | undefined
/**
* Rewrite the output css body. The input come in [key,value][] pairs.
*/
body?: (body: CSSEntries) => CSSEntries | undefined
/**
* Provide a parent selector(e.g. media query) to the output css.
*/
parent?: string | [string, number] | undefined
/**
* Order in which the variant is applied to selector.
*/
order?: number
/**
* Order in which the variant is sorted within single rule.
*/
sort?: number
/**
* Override layer to the output css.
*/
layer?: string | undefined
}
export type VariantFunction<Theme extends {} = {}> = (matcher: string, context: Readonly<VariantContext<Theme>>) => string | VariantHandler | undefined
export interface VariantObject<Theme extends {} = {}> {
/**
* The name of the variant.
*/
name?: string
/**
* The entry function to match and rewrite the selector for futher processing.
*/
match: VariantFunction<Theme>
/**
* Allows this variant to be used more than once in matching a single rule
*
* @default false
*/
multiPass?: boolean
/**
* Custom function for auto complete
*/
autocomplete?: Arrayable<AutoCompleteFunction | AutoCompleteTemplate>
}
export type Variant<Theme extends {} = {}> = VariantFunction<Theme> | VariantObject<Theme>
export type Preprocessor = (matcher: string) => string | undefined
export type Postprocessor = (util: UtilObject) => void
export type ThemeExtender<T> = (theme: T) => void
export interface ConfigBase<Theme extends {} = {}> {
/**
* Rules to generate CSS utilities
*/
rules?: Rule<Theme>[]
/**
* Variants that preprocess the selectors,
* having the ability to rewrite the CSS object.
*/
variants?: Variant<Theme>[]
/**
* Similar to Windi CSS's shortcuts,
* allows you have create new utilities by combining existing ones.
*/
shortcuts?: UserShortcuts<Theme>
/**
* Rules to exclude the selectors for your design system (to narrow down the possibilities).
* Combining `warnExcluded` options it can also helps you identify wrong usages.
*/
blocklist?: BlocklistRule[]
/**
* Utilities that always been included
*/
safelist?: string[]
/**
* Extractors to handle the source file and outputs possible classes/selectors
* Can be language-aware.
*/
extractors?: Extractor[]
/**
* Raw CSS injections.
*/
preflights?: Preflight<Theme>[]
/**
* Theme object for shared configuration between rules
*/
theme?: Theme
/**
* Layer orders. Default to 0.
*/
layers?: Record<string, number>
/**
* Custom function to sort layers.
*/
sortLayers?: (layers: string[]) => string[]
/**
* Preprocess the incoming utilities, return falsy value to exclude
*/
preprocess?: Arrayable<Preprocessor>
/**
* Process the generate utils object
*/
postprocess?: Arrayable<Postprocessor>
/**
* Custom functions to extend the theme object
*/
extendTheme?: Arrayable<ThemeExtender<Theme>>
/**
* Additional options for auto complete
*/
autocomplete?: {
/**
* Custom functions / templates to provide autocomplete suggestions
*/
templates?: Arrayable<AutoCompleteFunction | AutoCompleteTemplate>
/**
* Custom extractors to pickup possible classes and
* transform class-name style suggestions to the correct format
*/
extractors?: Arrayable<AutoCompleteExtractor>
}
/**
* Expose internal details for debugging / inspecting
*
* Added `rules`, `shortcuts`, `variants` to the context and expose the context object in `StringifiedUtil`
*
* You don't usually need to set this.
*
* @default false
*/
details?: boolean
}
export type AutoCompleteTemplate = string
export type AutoCompleteFunction = (input: string) => Awaitable<string[]>
export interface AutoCompleteExtractorContext {
content: string
cursor: number
}
export interface Replacement {
/**
* The range of the original text
*/
start: number
end: number
/**
* The text used to replace
*/
replacement: string
}
export interface SuggestResult {
/**
* The generated suggestions
*
* `[original, formatted]`
*/
suggestions: [string, string][]
/**
* The function to convert the selected suggestion back.
* Needs to pass in the original one.
*/
resolveReplacement: (suggestion: string) => Replacement
}
export interface AutoCompleteExtractorResult {
/**
* The extracted string
*/
extracted: string
/**
* The function to convert the selected suggestion back
*/
resolveReplacement: (suggestion: string) => Replacement
/**
* The function to format suggestions
*/
transformSuggestions?: (suggestions: string[]) => string[]
}
export interface AutoCompleteExtractor {
name: string
extract: (context: AutoCompleteExtractorContext) => Awaitable<AutoCompleteExtractorResult | null>
order?: number
}
export interface Preset<Theme extends {} = {}> extends ConfigBase<Theme> {
name: string
enforce?: 'pre' | 'post'
/**
* Preset options for other tools like IDE to consume
*/
options?: PresetOptions
}
export interface GeneratorOptions {
/**
* Merge utilities with the exact same body to save the file size
*
* @default true
*/
mergeSelectors?: boolean
/**
* Emit warning when matched selectors are presented in blocklist
*
* @default true
*/
warn?: boolean
}
export interface UserOnlyOptions<Theme extends {} = {}> {
/**
* The theme object, will be merged with the theme provides by presets
*/
theme?: Theme
/**
* Layout name of shortcuts
*
* @default 'shortcuts'
*/
shortcutsLayer?: string
/**
* Presets
*/
presets?: (Preset | Preset[])[]
/**
* Environment mode
*
* @default 'build'
*/
envMode?: 'dev' | 'build'
}
export interface UnocssPluginContext<Config extends UserConfig = UserConfig> {
ready: Promise<LoadConfigResult<Config>>
uno: UnoGenerator
tokens: Set<string>
modules: BetterMap<string, string>
filter: (code: string, id: string) => boolean
extract: (code: string, id?: string) => Promise<void>
reloadConfig: () => Promise<LoadConfigResult<Config>>
getConfig: () => Promise<Config>
invalidate: () => void
onInvalidate: (fn: () => void) => void
root: string
updateRoot: (root: string) => Promise<LoadConfigResult<Config>>
}
export interface SourceMap {
file?: string
mappings?: string
names?: string[]
sources?: string[]
sourcesContent?: string[]
version?: number
}
export interface TransformResult {
code: string
map?: SourceMap | null
etag?: string
deps?: string[]
dynamicDeps?: string[]
}
export interface SourceCodeTransformer {
name: string
/**
* The order of transformer
*/
enforce?: 'pre' | 'post'
/**
* Custom id filter, if not provided, the extraction filter will be applied
*/
idFilter?: (id: string) => boolean
/**
* The transform function
*/
transform: (code: MagicString, id: string, ctx: UnocssPluginContext) => Awaitable<void>
}
/**
* For other modules to aggregate the options
*/
export interface PluginOptions {
/**
* Load from configs files
*
* set `false` to disable
*/
configFile?: string | false
/**
* List of files that will also triggers config reloads
*/
configDeps?: string[]
/**
* Patterns that filter the files being extracted.
*/
include?: FilterPattern
/**
* Patterns that filter the files NOT being extracted.
*/
exclude?: FilterPattern
/**
* Custom transformers to the source code
*
* Currently only supported in Vite
*/
transformers?: SourceCodeTransformer[]
}
export interface UserConfig<Theme extends {} = {}> extends ConfigBase<Theme>, UserOnlyOptions<Theme>, GeneratorOptions, PluginOptions {}
export interface UserConfigDefaults<Theme extends {} = {}> extends ConfigBase<Theme>, UserOnlyOptions<Theme> {}
export interface ResolvedConfig extends Omit<
RequiredByKey<UserConfig, 'mergeSelectors' | 'theme' | 'rules' | 'variants' | 'layers' | 'extractors' | 'blocklist' | 'safelist' | 'preflights' | 'sortLayers'>,
'rules' | 'shortcuts' | 'autocomplete'
> {
shortcuts: Shortcut[]
variants: VariantObject[]
preprocess: Preprocessor[]
postprocess: Postprocessor[]
rulesSize: number
rulesDynamic: (DynamicRule | undefined)[]
rulesStaticMap: Record<string, [number, CSSObject | CSSEntries, RuleMeta | undefined, Rule] | undefined>
autocomplete: {
templates: (AutoCompleteFunction | AutoCompleteTemplate)[]
extractors: AutoCompleteExtractor[]
}
}
export interface GenerateResult {
css: string
layers: string[]
getLayer(name?: string): string | undefined
getLayers(includes?: string[], excludes?: string[]): string
matched: Set<string>
}
export type VariantMatchedResult = readonly [
raw: string,
current: string,
variantHandlers: VariantHandler[],
variants: Set<Variant>,
]
export type ParsedUtil = readonly [
index: number,
raw: string,
entries: CSSEntries,
meta: RuleMeta | undefined,
variantHandlers: VariantHandler[],
]
export type RawUtil = readonly [
index: number,
rawCSS: string,
meta: RuleMeta | undefined,
]
export type StringifiedUtil = readonly [
index: number,
selector: string | undefined,
body: string,
parent: string | undefined,
meta: RuleMeta | undefined,
context: RuleContext | undefined,
]
export interface UtilObject {
selector: string
entries: CSSEntries
parent: string | undefined
layer: string | undefined
sort: number | undefined
}
export interface GenerateOptions {
/**
* Filepath of the file being processed.
*/
id?: string
/**
* Generate preflights (if defined)
*
* @default true
*/
preflights?: boolean
/**
* Includes safelist
*/
safelist?: boolean
/**
* Genreate minified CSS
* @default false
*/
minify?: boolean
/**
* @expiremental
*/
scope?: string
}