import validateColor from "validate-color"; import { isNil } from "@applicaster/zapp-react-native-utils/utils"; import { isString } from "@applicaster/zapp-react-native-utils/stringUtils"; const normalizeRgbaAlpha = (color: string): string => { return color.replace( /^rgba\(([^)]+),\s*(\d+(?:\.\d+)?)\s*\)$/i, (_, rgb, alpha) => { const alphaValue = parseFloat(alpha); if (!Number.isFinite(alphaValue) || !Number.isInteger(alphaValue)) { return color; } return `rgba(${rgb},${alphaValue})`; } ); }; export const isValidColor = (color: string): boolean => { if (isNil(color) || !isString(color)) { return false; } if (validateColor(color)) { return true; } // validate-color rejects integer alpha values written as floats (e.g. 1.0) // https://github.com/dreamyguy/validate-color/issues/44 const normalizedColor = normalizeRgbaAlpha(color); return normalizedColor !== color && validateColor(normalizedColor); }; function isRgbaAlphaZero(color: string): boolean { const layers = color .replace("rgba(", "") .replace(")", "") .split(",") .map((layer) => layer.trim()); return Number(layers[3]) === 0; } export const isTransparentColor = (color: string): boolean => { return ( isValidColor(color) && (color === "transparent" || isRgbaAlphaZero(color)) ); };