-
-
Notifications
You must be signed in to change notification settings - Fork 967
Expand file tree
/
Copy pathcolor-validator.ts
More file actions
57 lines (54 loc) · 1.71 KB
/
color-validator.ts
File metadata and controls
57 lines (54 loc) · 1.71 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
const HexColorRegex = /^#([\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
const FunctionalColorRegex = /^([a-z-]+)\(/i;
const NamedColorRegex = /^[a-z]+$/i;
function isValidCssColor(color: string): boolean {
if (typeof CSS != "undefined" && typeof CSS.supports == "function") {
return CSS.supports("color", color);
}
if (typeof document == "undefined") {
return false;
}
const temp = document.createElement("div");
temp.style.color = "";
temp.style.color = color;
return temp.style.color != "";
}
function getCssColorType(color: string): string {
const normalizedColor = color.toLowerCase();
if (HexColorRegex.test(normalizedColor)) {
if (normalizedColor.length === 4) {
return "hex3";
}
if (normalizedColor.length === 5) {
return "hex4";
}
if (normalizedColor.length === 9) {
return "hex8";
}
return "hex";
}
if (normalizedColor === "transparent") {
return "transparent";
}
if (normalizedColor === "currentcolor") {
return "currentcolor";
}
const functionMatch = normalizedColor.match(FunctionalColorRegex);
if (functionMatch) {
return functionMatch[1];
}
if (NamedColorRegex.test(normalizedColor)) {
return "keyword";
}
return "color";
}
export function validateCssColor(color: string): string {
if (typeof color != "string") {
throw new Error(`Invalid CSS color: ${String(color)}`);
}
const normalizedColor = color.trim();
if (normalizedColor == "" || !isValidCssColor(normalizedColor)) {
throw new Error(`Invalid CSS color: ${color}`);
}
return getCssColorType(normalizedColor);
}