Fix: cleaner validateRGB
This commit is contained in:
parent
fe337702bd
commit
28032d25b2
|
@ -47,12 +47,20 @@ const colorConverter = (() => {
|
||||||
return /^#[a-f\d]+$/i.test(color) && [4, 5, 7, 9].some(n => color.length === n));
|
return /^#[a-f\d]+$/i.test(color) && [4, 5, 7, 9].some(n => color.length === n));
|
||||||
}
|
}
|
||||||
|
|
||||||
// % converted before function call
|
function validateRGB(nums) {
|
||||||
function validateRGB(r, g, b) {
|
const isPercentage = nums[0].endsWith('%');
|
||||||
return [r, g, b].every(n => {
|
const valid = isPercentage ? validatePercentage : validateNum;
|
||||||
const num = parseFloat(n);
|
return nums.every(valid);
|
||||||
return Number.isInteger(num) && num >= 0 && num <= 255;
|
}
|
||||||
});
|
|
||||||
|
function validatePercentage(s) {
|
||||||
|
// FIXME: what about float?
|
||||||
|
const match = s.match(/^(\d+)%$/);
|
||||||
|
return match && Number(match[1]) >= 0 && Number(match[1]) <= 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateNum(s) {
|
||||||
|
return Number(s) >= 0 && Number(s) <= 255;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mod 360 applied to h before function call
|
// Mod 360 applied to h before function call
|
||||||
|
@ -123,15 +131,12 @@ const colorConverter = (() => {
|
||||||
|
|
||||||
const first = num[0];
|
const first = num[0];
|
||||||
if (/rgb/i.test(type)) {
|
if (/rgb/i.test(type)) {
|
||||||
const isPercent = first.endsWith('%');
|
if (!validateRGB(num)) {
|
||||||
const k = isPercent ? 2.55 : 1;
|
return null;
|
||||||
const parser = isPercent ? parsePercentage : parseNumber;
|
}
|
||||||
const [r, g, b] = num.map(s => {
|
const k = first.endsWith('%') ? 2.55 : 1;
|
||||||
const val = parser(s) * k;
|
const [r, g, b] = num.map(s => Math.round(parseFloat(s) * k));
|
||||||
// Round the values when converting % to byte value or validation fails
|
return {type: 'rgb', r, g, b, a} : null;
|
||||||
return isPercent ? Math.round(val) : val;
|
|
||||||
});
|
|
||||||
return validateRGB(r, g, b) ? {type: 'rgb', r, g, b, a} : null;
|
|
||||||
} else {
|
} else {
|
||||||
const h = parseHue(first);
|
const h = parseHue(first);
|
||||||
const s = parsePercentage(num[1]);
|
const s = parsePercentage(num[1]);
|
||||||
|
|
Loading…
Reference in New Issue
Block a user