-
-
Notifications
You must be signed in to change notification settings - Fork 400
Expand file tree
/
Copy pathuno-preset-a11y.ts
More file actions
77 lines (70 loc) · 2.19 KB
/
uno-preset-a11y.ts
File metadata and controls
77 lines (70 loc) · 2.19 KB
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
import type { Preset } from 'unocss'
type CollectorChecker = (warning: string, rule: string) => void
// Track warnings to avoid duplicates
const warnedClasses = new Set<string>()
function warnOnce(message: string, key: string) {
if (!warnedClasses.has(key)) {
warnedClasses.add(key)
// oxlint-disable-next-line no-console -- warn logging
console.warn(message)
}
}
/** Reset warning state (for testing) */
export function resetA11yWarnings() {
warnedClasses.clear()
}
const textPxToClass: Record<number, string> = {
11: 'text-2xs',
10: 'text-3xs',
9: 'text-4xs',
8: 'text-5xs',
}
function reportTextSizeWarning(match: string, suggestion: string, checker?: CollectorChecker) {
const message = `[a11y] Avoid using '${match}', ${suggestion}.`
if (checker) {
checker(message, match)
} else {
warnOnce(message, match)
}
}
export function presetA11y(checker?: CollectorChecker): Preset {
return {
name: 'a11y-preset',
// text-[N] (arbitrary where N is a size in px or em): recommend text-2xs/text-3xs/text-4xs/text-5xs or "use classes"
rules: [
[
/^text-\[(\d+(\.\d+)?)(px)?\]$/,
([match, numStr], context) => {
const num = Number(numStr)
const fullClass = context.rawSelector || match
const suggestedClass = textPxToClass[num]
if (suggestedClass) {
reportTextSizeWarning(fullClass, `use '${suggestedClass}' instead`, checker)
} else {
reportTextSizeWarning(
fullClass,
'use text-<size> classes or rem values instead of custom values',
checker,
)
}
return [['font-size', `${num}px`]]
},
{ autocomplete: 'text-[<num>]' },
],
[
/^text-\[(\d+(\.\d+)?)em\]$/,
([match, numStr], context) => {
const num = Number(numStr)
const fullClass = context.rawSelector || match
reportTextSizeWarning(
fullClass,
'use text-<size> classes or rem values instead of custom values',
checker,
)
return [['font-size', `${num}em`]]
},
{ autocomplete: 'text-[<num>]em' },
],
],
}
}