Skip to content

Commit

Permalink
Add space separated values handling to rem/em functions
Browse files Browse the repository at this point in the history
  • Loading branch information
rtivital committed Nov 10, 2023
1 parent 6acfac2 commit 64aefc6
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/postcss-rem-em.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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 });
Expand Down
8 changes: 8 additions & 0 deletions src/tests/__snapshots__/rem-em.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
11 changes: 11 additions & 0 deletions src/tests/rem-em.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const baseInput = `
}
`;

const spaceSeparatedInput = `
.demo {
padding: rem(16px 32px);
}
`;

const mediaInput = `
@media (min-width: em(320px)) {
font-size: rem(32px);
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit 64aefc6

Please sign in to comment.