Skip to content

Commit

Permalink
Minify rgb with only 0 or 100%.
Browse files Browse the repository at this point in the history
  • Loading branch information
johnkenny54 committed Oct 15, 2024
1 parent ed9b53c commit 4b81f64
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 17 additions & 1 deletion lib/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ class RGBColor extends ColorValue {
#rgb;

/**
* @param {string} fn
* @param {string|undefined} fn
* @param {[number,number,number]} rgb
*/
constructor(fn, rgb) {
Expand Down Expand Up @@ -246,6 +246,22 @@ class RGBPctColor extends ColorValue {
* @returns {ColorValue}
*/
getMinifiedValue() {
/** @type {number[]} */
const rgb = [];
// If all percentages are 0 or 100, convert to regular rgb.
for (const pct of this.#rgb) {
if (pct === 0) {
rgb.push(0);
} else if (pct === 100) {
rgb.push(255);
} else {
break;
}
}
if (rgb.length === 3) {
// @ts-ignore
return new RGBColor(undefined, rgb).getMinifiedValue();
}
return new ColorValue(`rgb(${this.#rgb.map((n) => n + '%').join(',')})`);
}
}
2 changes: 2 additions & 0 deletions test/lib/colors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ describe('test parsing and minifying', () => {
{ in: 'rgb( 49.5%, 33.49% ,22.5% )', minified: 'rgb(49.5%,33.49%,22.5%)' },
{ in: 'rgb(165,42,42)', minified: 'brown' },
{ in: 'rgb( 50 100 150 /.1)', minified: 'rgb( 50 100 150 /.1)' },
{ in: 'rgb(100%,0%,0%)', minified: 'red' },
{ in: 'rgb(100%,100%,100%)', minified: '#fff' },
];
for (const testCase of testCases) {
it(`${testCase.in}`, () => {
Expand Down

0 comments on commit 4b81f64

Please sign in to comment.