forked from home-assistant/frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompute-color.ts
More file actions
71 lines (65 loc) · 1.4 KB
/
compute-color.ts
File metadata and controls
71 lines (65 loc) · 1.4 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
export const THEME_COLORS = new Set([
"primary",
"accent",
"red",
"pink",
"purple",
"deep-purple",
"indigo",
"blue",
"light-blue",
"cyan",
"teal",
"green",
"light-green",
"lime",
"yellow",
"amber",
"orange",
"deep-orange",
"brown",
"light-grey",
"grey",
"dark-grey",
"blue-grey",
"black",
"white",
]);
const YAML_ONLY_THEMES_COLORS = new Set([
"primary-text",
"secondary-text",
"disabled",
]);
export function computeCssColor(color: string): string {
if (THEME_COLORS.has(color) || YAML_ONLY_THEMES_COLORS.has(color)) {
return `var(--${color}-color)`;
}
return color;
}
/**
* Validates if a string is a valid color.
* Accepts: hex colors (#xxx, #xxxxxx), theme colors, and valid CSS color names.
*/
export function isValidColorString(color: string | undefined): boolean {
if (!color || typeof color !== "string") {
return false;
}
// Check if it's a theme color
if (THEME_COLORS.has(color)) {
return true;
}
// Check if it's a hex color
if (/^#([0-9A-Fa-f]{3}){1,2}$/.test(color)) {
return true;
}
// Check if it's a valid CSS color name by trying to parse it
// Use CSS.supports() for a more efficient test without DOM manipulation
// This checks if the browser recognizes the color value
try {
const style = new Option().style;
style.color = color;
return style.color !== "";
} catch {
return false;
}
}