From 64aefc6b7605cb53a4cab689ab80439774a0f5d4 Mon Sep 17 00:00:00 2001 From: Vitaly Rtishchev Date: Fri, 10 Nov 2023 15:54:46 +0400 Subject: [PATCH] Add space separated values handling to rem/em functions --- src/postcss-rem-em.ts | 25 +++++++++++++++++---- src/tests/__snapshots__/rem-em.test.ts.snap | 8 +++++++ src/tests/rem-em.test.ts | 11 +++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/postcss-rem-em.ts b/src/postcss-rem-em.ts index 60d7adb..21ef27d 100644 --- a/src/postcss-rem-em.ts +++ b/src/postcss-rem-em.ts @@ -4,14 +4,29 @@ function scaleRem(remValue: string) { return `calc(${remValue} * var(--mantine-scale))`; } -function createConverter(units: 'rem' | 'em', { shouldScale = false } = {}) { - return (value: string | number) => { +function createConverter(units: string, { shouldScale = false } = {}) { + function converter(value: unknown): string { + if (value === 0 || value === '0') { + return '0'; + } + if (typeof value === 'number') { const val = `${value / 16}${units}`; return shouldScale ? scaleRem(val) : val; } if (typeof value === 'string') { + if (value.startsWith('calc(') || value.startsWith('var(')) { + return value; + } + + if (value.includes(' ')) { + return value + .split(' ') + .map((val) => converter(val)) + .join(' '); + } + if (value.includes(units)) { return shouldScale ? scaleRem(value) : value; } @@ -23,8 +38,10 @@ function createConverter(units: 'rem' | 'em', { shouldScale = false } = {}) { } } - return value; - }; + return value as string; + } + + return converter; } const rem = createConverter('rem', { shouldScale: true }); diff --git a/src/tests/__snapshots__/rem-em.test.ts.snap b/src/tests/__snapshots__/rem-em.test.ts.snap index dd82563..08e13ee 100644 --- a/src/tests/__snapshots__/rem-em.test.ts.snap +++ b/src/tests/__snapshots__/rem-em.test.ts.snap @@ -20,6 +20,14 @@ exports[`rem-em transforms base case correctly 1`] = ` " `; +exports[`rem-em transforms space separated values correctly 1`] = ` +" +.demo { + padding: calc(1rem * var(--mantine-scale)) calc(2rem * var(--mantine-scale)); +} +" +`; + exports[`rem-em works inside media query 1`] = ` " @media (min-width: 20em) { diff --git a/src/tests/rem-em.test.ts b/src/tests/rem-em.test.ts index 3434393..4ba66c4 100644 --- a/src/tests/rem-em.test.ts +++ b/src/tests/rem-em.test.ts @@ -7,6 +7,12 @@ const baseInput = ` } `; +const spaceSeparatedInput = ` +.demo { + padding: rem(16px 32px); +} +`; + const mediaInput = ` @media (min-width: em(320px)) { font-size: rem(32px); @@ -40,6 +46,11 @@ describe('rem-em', () => { expect(res.css).toMatchSnapshot(); }); + it('transforms space separated values correctly', async () => { + const res = await testTransform(spaceSeparatedInput); + expect(res.css).toMatchSnapshot(); + }); + it('works inside media query', async () => { const res = await testTransform(mediaInput); expect(res.css).toMatchSnapshot();