|
| 1 | +const HexColorRegex = /^#([\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i; |
| 2 | +const FunctionalColorRegex = /^([a-z-]+)\(/i; |
| 3 | +const NamedColorRegex = /^[a-z]+$/i; |
| 4 | + |
| 5 | +function isValidCssColor(color: string): boolean { |
| 6 | + if (typeof CSS != "undefined" && typeof CSS.supports == "function") { |
| 7 | + return CSS.supports("color", color); |
| 8 | + } |
| 9 | + if (typeof document == "undefined") { |
| 10 | + return false; |
| 11 | + } |
| 12 | + const temp = document.createElement("div"); |
| 13 | + temp.style.color = ""; |
| 14 | + temp.style.color = color; |
| 15 | + return temp.style.color != ""; |
| 16 | +} |
| 17 | + |
| 18 | +function getCssColorType(color: string): string { |
| 19 | + const normalizedColor = color.toLowerCase(); |
| 20 | + if (HexColorRegex.test(normalizedColor)) { |
| 21 | + if (normalizedColor.length === 4) { |
| 22 | + return "hex3"; |
| 23 | + } |
| 24 | + if (normalizedColor.length === 5) { |
| 25 | + return "hex4"; |
| 26 | + } |
| 27 | + if (normalizedColor.length === 9) { |
| 28 | + return "hex8"; |
| 29 | + } |
| 30 | + return "hex"; |
| 31 | + } |
| 32 | + if (normalizedColor === "transparent") { |
| 33 | + return "transparent"; |
| 34 | + } |
| 35 | + if (normalizedColor === "currentcolor") { |
| 36 | + return "currentcolor"; |
| 37 | + } |
| 38 | + const functionMatch = normalizedColor.match(FunctionalColorRegex); |
| 39 | + if (functionMatch) { |
| 40 | + return functionMatch[1]; |
| 41 | + } |
| 42 | + if (NamedColorRegex.test(normalizedColor)) { |
| 43 | + return "keyword"; |
| 44 | + } |
| 45 | + return "color"; |
| 46 | +} |
| 47 | + |
| 48 | +export function validateCssColor(color: string): string { |
| 49 | + if (typeof color != "string") { |
| 50 | + throw new Error(`Invalid CSS color: ${String(color)}`); |
| 51 | + } |
| 52 | + const normalizedColor = color.trim(); |
| 53 | + if (normalizedColor == "" || !isValidCssColor(normalizedColor)) { |
| 54 | + throw new Error(`Invalid CSS color: ${color}`); |
| 55 | + } |
| 56 | + return getCssColorType(normalizedColor); |
| 57 | +} |
0 commit comments