Skip to content

Commit

Permalink
feat: add rem
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Oct 28, 2023
1 parent 52a31e5 commit 22f6d99
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/rem/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const SIXTEEN_PX = '16px';

function scaleRem(remValue: string, shouldScaleTo: string) {
return `calc(${remValue} * ${shouldScaleTo})`;
}

function createConverter(units: string, shouldScaleTo: string | null = null) {
return (value: number | string) => {
if (value === 0 || value === '0') {
return '0';
}

if (typeof value === 'number') {
const val = `${value / 16}${units}`;
return (shouldScaleTo && shouldScaleTo !== SIXTEEN_PX) ? scaleRem(val, shouldScaleTo) : val;
}

if (value.includes('calc(') || value.includes('var(')) {
return value;
}

if (value.includes(units)) {
return (shouldScaleTo && shouldScaleTo !== SIXTEEN_PX) ? scaleRem(value, shouldScaleTo) : value;
}

const replaced = Number(value.replace('px', ''));
// eslint-disable-next-line no-self-compare -- faster isNaN check
if (replaced === replaced) {
const val = `${replaced / 16}${units}`;
return (shouldScaleTo && shouldScaleTo !== SIXTEEN_PX) ? scaleRem(val, shouldScaleTo) : val;
}

return value;
};
}

export const rem = createConverter('rem', SIXTEEN_PX);
export const mantine_rem = createConverter('rem', 'var(--mantine-scale)');
export const em = createConverter('em');

0 comments on commit 22f6d99

Please sign in to comment.