From ff5c3927271caaeecd1066424241cf9c55ba66d4 Mon Sep 17 00:00:00 2001 From: Vitaly Rtishchev Date: Thu, 21 Dec 2023 11:08:26 +0400 Subject: [PATCH] Add % units support to alpha, lighten and darken functions --- .npmignore | 1 + src/postcss-color-mix.ts | 5 ++++- src/tests/__snapshots__/color-mix.test.ts.snap | 9 +++++++++ src/tests/color-mix.test.ts | 12 ++++++++++++ 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/.npmignore b/.npmignore index c77d827..b243a65 100644 --- a/.npmignore +++ b/.npmignore @@ -5,6 +5,7 @@ tsconfig.json yarn.lock src tests +scripts node_modules test.ts .DS_Store \ No newline at end of file diff --git a/src/postcss-color-mix.ts b/src/postcss-color-mix.ts index 5a2c731..63da628 100644 --- a/src/postcss-color-mix.ts +++ b/src/postcss-color-mix.ts @@ -23,7 +23,10 @@ function getParsedColor(input: unknown) { return null; } - const payload = Number(color.slice(lastCommaIndex + 1)); + const rawPayload = color.slice(lastCommaIndex + 1).trim(); + const payload = rawPayload.endsWith('%') + ? Number(rawPayload.slice(0, -1)) / 100 + : Number(color.slice(lastCommaIndex + 1)); if (Number.isNaN(payload)) { return null; diff --git a/src/tests/__snapshots__/color-mix.test.ts.snap b/src/tests/__snapshots__/color-mix.test.ts.snap index fc98cdd..d152f40 100644 --- a/src/tests/__snapshots__/color-mix.test.ts.snap +++ b/src/tests/__snapshots__/color-mix.test.ts.snap @@ -26,3 +26,12 @@ exports[`color-mix correctly replaces lighten function 1`] = ` } " `; + +exports[`color-mix correctly replaces percentage values 1`] = ` +" +.demo { + background: color-mix(in srgb, #f00, white 50%); + border: calc(0.0625rem * var(--mantine-scale)) solid color-mix(in srgb, var(--mantine-color-gray-4), transparent 90%); +} +" +`; diff --git a/src/tests/color-mix.test.ts b/src/tests/color-mix.test.ts index 2547f37..ca0d1bb 100644 --- a/src/tests/color-mix.test.ts +++ b/src/tests/color-mix.test.ts @@ -21,6 +21,13 @@ const darkenInput = ` } `; +const percentageInput = ` +.demo { + background: lighten(#f00, 50%); + border: rem(1px) solid alpha(var(--mantine-color-gray-4), 10%); +} +`; + describe('color-mix', () => { it('correctly replaces alpha function', async () => { const res = await testTransform(alphaInput); @@ -36,4 +43,9 @@ describe('color-mix', () => { const res = await testTransform(darkenInput); expect(res.css).toMatchSnapshot(); }); + + it('correctly replaces percentage values', async () => { + const res = await testTransform(percentageInput); + expect(res.css).toMatchSnapshot(); + }); });