color: accept #rgb/#rgba and #rrggbbaa in contrastTextColor; stop rgbToHex throwing

contrastTextColor matched only #rrggbb and silently returned the dark
fallback for every other form — #000 and #369 produced a black label on a
near-black fill. colorLuminance in the same file already expanded short
hex, so this was an inconsistency, not a contract.

rgbToHex threw a TypeError on non-matching input (matches.length on null)
and rejected rgba() and whitespace-free rgb strings; it now returns  and
ignores the alpha channel.
This commit is contained in:
pk committed 2026-11-15 18:36:49 +01:00
1 parent b9adc87306
commit 5978a33283
2 files changed
+43 -13

No files matched your search

+42 -12
View File
@@ -25,6 +25,32 @@ export const colorLuminance = (hex, lum) => {
return rgb; return rgb;
} }
/**
* Expand a hex color to six digits, ignoring an alpha byte.
* Accepts #rgb, #rgba, #rrggbb and #rrggbbaa — the '#' is optional.
*
* @param {String} hex Color hex string.
* @return {String} Six-digit lower-case hex without the '#', or '' when unparsable.
*/
const expandHex = hex => {
let value = String(hex == null ? '' : hex).trim().replace(/^#/, '');
if (!/^[0-9a-f]+$/i.test(value)) {
return '';
}
if (value.length === 3 || value.length === 4) {
// #rgb / #rgba: every digit is doubled (#369 → #336699).
value = value.slice(0, 3).split('').map(c => c + c).join('');
} else if (value.length === 6 || value.length === 8) {
value = value.slice(0, 6);
} else {
return '';
}
return value.toLowerCase();
}
/** /**
* Calculate an appropriate contrast color. * Calculate an appropriate contrast color.
* *
@@ -36,13 +62,15 @@ export const colorLuminance = (hex, lum) => {
export const contrastTextColor = (hex, dark, light) => { export const contrastTextColor = (hex, dark, light) => {
dark = dark || '#000000'; dark = dark || '#000000';
light = light || '#ffffff'; light = light || '#ffffff';
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); // Hex may be #rgb, #rgba, #rrggbb or #rrggbbaa; the alpha byte is ignored.
if (!result) { // Anything unparsable keeps the historical dark fallback.
const value = expandHex(hex);
if (!value) {
return dark; return dark;
} }
const red = parseInt(result[1], 16); const red = parseInt(value.substr(0, 2), 16);
const green = parseInt(result[2], 16); const green = parseInt(value.substr(2, 2), 16);
const blue = parseInt(result[3], 16); const blue = parseInt(value.substr(4, 2), 16);
let brightness; let brightness;
brightness = (red * 299) + (green * 587) + (blue * 114); brightness = (red * 299) + (green * 587) + (blue * 114);
brightness /= 255000; brightness /= 255000;
@@ -62,14 +90,16 @@ export const contrastTextColor = (hex, dark, light) => {
* @return {String} The hex string. * @return {String} The hex string.
*/ */
export const rgbToHex = rgb => { export const rgbToHex = rgb => {
const matches = rgb.match(/rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)/); const matches = /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)/.exec(String(rgb == null ? '' : rgb));
if (matches.length !== 4) { if (!matches) {
return ''; return '';
} }
// From https://gist.github.com/lrvick/2080648. // Channels are clamped, so out-of-range input cannot overflow the hex.
const bin = matches[1] << 16 | matches[2] << 8 | matches[3]; // An alpha channel is ignored — this returns an opaque hex.
return (function(h) { const value = [matches[1], matches[2], matches[3]]
return '#' + new Array(7 - h.length).join('0') + h; .map(c => Math.min(255, Number(c)).toString(16).padStart(2, '0'))
})(bin.toString(16).toLowerCase()); .join('');
return `#${value}`;
} }
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@tp/helpers", "name": "@tp/helpers",
"version": "2.14.0", "version": "2.15.0",
"description": "", "description": "",
"main": "closest.js", "main": "closest.js",
"scripts": { "scripts": {