/
colors.ts
284 lines (239 loc) · 6.99 KB
/
colors.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
import type { CSSColorValue, RGBAColorValue } from '@unocss/core'
/* eslint-disable no-case-declarations */
const cssColorFunctions = ['hsl', 'hsla', 'hwb', 'lab', 'lch', 'oklab', 'oklch', 'rgb', 'rgba']
export function hex2rgba(hex = ''): RGBAColorValue | undefined {
const color = parseHexColor(hex)
if (color != null) {
const { components, alpha } = color
if (alpha == null)
return components as [number, number, number]
return [...components, alpha] as [number, number, number, number]
}
}
export function parseCssColor(str = ''): CSSColorValue | undefined {
const color = parseColor(str)
if (color == null || color === false)
return
const { type: casedType, components, alpha } = color
const type = casedType.toLowerCase()
if (components.length === 0)
return
if (['rgba', 'hsla'].includes(type) && alpha == null)
return
if (cssColorFunctions.includes(type) && ![1, 3].includes(components.length))
return
return { type, components, alpha }
}
export function colorOpacityToString(color: CSSColorValue) {
const alpha = color.alpha ?? 1
return alpha === '%alpha' ? 1 : alpha
}
export function colorToString(color: CSSColorValue | string, alphaOverride?: string | number) {
if (typeof color === 'string')
return color.replace('%alpha', `${alphaOverride ?? 1}`)
const { components } = color
let { alpha, type } = color
alpha = alphaOverride ?? alpha
type = type.toLowerCase()
// Comma separated functions
if (['hsla', 'hsl', 'rgba', 'rgb'].includes(type))
return `${type.replace('a', '')}a(${components.join(',')}${alpha == null ? '' : `,${alpha}`})`
alpha = alpha == null ? '' : ` / ${alpha}`
if (cssColorFunctions.includes(type))
return `${type}(${components.join(' ')}${alpha})`
return `color(${type} ${components.join(' ')}${alpha})`
}
function parseColor(str: string) {
if (!str)
return
let color: CSSColorValue | false | undefined = parseHexColor(str)
if (color != null)
return color
color = cssColorKeyword(str)
if (color != null)
return color
color = parseCssCommaColorFunction(str)
if (color != null)
return color
color = parseCssSpaceColorFunction(str)
if (color != null)
return color
color = parseCssColorFunction(str)
if (color != null)
return color
}
function parseHexColor(str: string): CSSColorValue | undefined {
const [, body] = str.match(/^#([\da-f]+)$/i) || []
if (!body)
return
switch (body.length) {
case 3:
case 4:
const digits = Array.from(body, s => Number.parseInt(s, 16)).map(n => (n << 4) | n)
return {
type: 'rgb',
components: digits.slice(0, 3),
alpha: body.length === 3
? undefined
: Math.round(digits[3] / 255 * 100) / 100,
}
case 6:
case 8:
const value = Number.parseInt(body, 16)
return {
type: 'rgb',
components: body.length === 6
? [(value >> 16) & 0xFF, (value >> 8) & 0xFF, value & 0xFF]
: [(value >> 24) & 0xFF, (value >> 16) & 0xFF, (value >> 8) & 0xFF],
alpha: body.length === 6
? undefined
: Math.round((value & 0xFF) / 255 * 100) / 100,
}
}
}
function cssColorKeyword(str: string): CSSColorValue | undefined {
const color = {
rebeccapurple: [102, 51, 153, 1],
}[str]
if (color != null) {
return {
type: 'rgb',
components: color.slice(0, 3),
alpha: color[3],
}
}
}
function parseCssCommaColorFunction(color: string): CSSColorValue | false | undefined {
const match = color.match(/^(rgb|rgba|hsl|hsla)\((.+)\)$/i)
if (!match)
return
const [, type, componentString] = match
// With min 3 (rgb) and max 4 (rgba), try to get 5 components
const components = getComponents(componentString, ',', 5)
if (components) {
if ([3, 4].includes(components.length)) {
return {
type,
components: components.slice(0, 3),
alpha: components[3],
}
}
else if (components.length !== 1) {
return false
}
}
}
const cssColorFunctionsRe = new RegExp(`^(${cssColorFunctions.join('|')})\\((.+)\\)$`, 'i')
function parseCssSpaceColorFunction(color: string): CSSColorValue | undefined {
const match = color.match(cssColorFunctionsRe)
if (!match)
return
const [, fn, componentString] = match
const parsed = parseCssSpaceColorValues(`${fn} ${componentString}`)
if (parsed) {
const { alpha, components: [type, ...components] } = parsed
return {
type,
components,
alpha,
}
}
}
function parseCssColorFunction(color: string): CSSColorValue | undefined {
const match = color.match(/^color\((.+)\)$/)
if (!match)
return
const parsed = parseCssSpaceColorValues(match[1])
if (parsed) {
const { alpha, components: [type, ...components] } = parsed
return {
type,
components,
alpha,
}
}
}
function parseCssSpaceColorValues(componentString: string) {
const components = getComponents(componentString)
if (!components)
return
let totalComponents = components.length
// (fn 1 2 3 / 4)
if (components[totalComponents - 2] === '/') {
return {
components: components.slice(0, totalComponents - 2),
alpha: components[totalComponents - 1],
}
}
// (fn 1 2 3/ 4) or (fn 1 2 3 /4)
if (components[totalComponents - 2] != null && (components[totalComponents - 2].endsWith('/') || components[totalComponents - 1].startsWith('/'))) {
const removed = components.splice(totalComponents - 2)
components.push(removed.join(' '))
--totalComponents
}
// maybe (fn 1 2 3/4)
const withAlpha = getComponents(components[totalComponents - 1], '/', 3)
if (!withAlpha)
return
// without alpha
if (withAlpha.length === 1 || withAlpha[withAlpha.length - 1] === '')
return { components }
const alpha = withAlpha.pop()
components[totalComponents - 1] = withAlpha.join('/')
return {
components,
alpha,
}
}
function getComponent(str: string, separator: string) {
str = str.trim()
if (str === '')
return
const l = str.length
let parenthesis = 0
for (let i = 0; i < l; i++) {
switch (str[i]) {
case '(':
parenthesis++
break
case ')':
if (--parenthesis < 0)
return
break
case separator:
if (parenthesis === 0) {
const component = str.slice(0, i).trim()
if (component === '')
return
return [
component,
str.slice(i + 1).trim(),
]
}
}
}
return [
str,
'',
]
}
export function getComponents(str: string, separator?: string, limit?: number) {
separator = separator ?? ' '
if (separator.length !== 1)
return
limit = limit ?? 10
const components = []
let i = 0
while (str !== '') {
if (++i > limit)
return
const componentPair = getComponent(str, separator)
if (!componentPair)
return
const [component, rest] = componentPair
components.push(component)
str = rest
}
if (components.length > 0)
return components
}