-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
validators.ts
99 lines (77 loc) · 2.5 KB
/
validators.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
const arbitraryValueRegex = /^\[(?:([a-z-]+):)?(.+)\]$/i
const fractionRegex = /^\d+\/\d+$/
const stringLengths = new Set(['px', 'full', 'screen'])
const tshirtUnitRegex = /^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/
const lengthUnitRegex = /\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh)/
// Shadow always begins with x and y offset separated by underscore
const shadowRegex = /^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/
export function isLength(value: string) {
return (
isNumber(value) ||
stringLengths.has(value) ||
fractionRegex.test(value) ||
isArbitraryLength(value)
)
}
export function isArbitraryLength(value: string) {
return getIsArbitraryValue(value, 'length', isLengthOnly)
}
export function isArbitrarySize(value: string) {
return getIsArbitraryValue(value, 'size', isNever)
}
export function isArbitraryPosition(value: string) {
return getIsArbitraryValue(value, 'position', isNever)
}
export function isArbitraryUrl(value: string) {
return getIsArbitraryValue(value, 'url', isUrl)
}
export function isArbitraryNumber(value: string) {
return getIsArbitraryValue(value, 'number', isNumber)
}
/**
* @deprecated Will be removed in next major version. Use `isArbitraryNumber` instead.
*/
export const isArbitraryWeight = isArbitraryNumber
export function isNumber(value: string) {
return !Number.isNaN(Number(value))
}
export function isInteger(value: string) {
return isIntegerOnly(value) || getIsArbitraryValue(value, 'number', isIntegerOnly)
}
export function isArbitraryValue(value: string) {
return arbitraryValueRegex.test(value)
}
export function isAny() {
return true
}
export function isTshirtSize(value: string) {
return tshirtUnitRegex.test(value)
}
export function isArbitraryShadow(value: string) {
return getIsArbitraryValue(value, '', isShadow)
}
function getIsArbitraryValue(value: string, label: string, testValue: (value: string) => boolean) {
const result = arbitraryValueRegex.exec(value)
if (result) {
if (result[1]) {
return result[1] === label
}
return testValue(result[2]!)
}
return false
}
function isLengthOnly(value: string) {
return lengthUnitRegex.test(value)
}
function isNever() {
return false
}
function isUrl(value: string) {
return value.startsWith('url(')
}
function isIntegerOnly(value: string) {
return Number.isInteger(Number(value))
}
function isShadow(value: string) {
return shadowRegex.test(value)
}