onboardsync-react-native
Version:
Expo SDK for OnboardSync - Remote onboarding configuration platform with A/B testing
40 lines (33 loc) • 1.04 kB
text/typescript
export class ColorUtils {
static hexToRgb(hex: string): { r: number; g: number; b: number } | null {
// Remove # if present
const cleanHex = hex.replace('#', '');
// Validate hex string
if (!/^[0-9A-Fa-f]{6}$/.test(cleanHex)) {
return null;
}
const bigint = parseInt(cleanHex, 16);
return {
r: (bigint >> 16) & 255,
g: (bigint >> 8) & 255,
b: bigint & 255,
};
}
static isColorDark(hex: string): boolean {
const rgb = this.hexToRgb(hex);
if (!rgb) {
// Default to light if invalid color
return false;
}
// Calculate relative luminance using WCAG formula
const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
// Consider dark if luminance is less than 0.5
return luminance < 0.5;
}
static isDarkColor(hex: string): boolean {
return this.isColorDark(hex);
}
static getContrastColor(backgroundColor: string): string {
return this.isColorDark(backgroundColor) ? '#FFFFFF' : '#000000';
}
}