Skip to content

Commit

Permalink
feat(transforms): adds 'px to rem' transform
Browse files Browse the repository at this point in the history
  • Loading branch information
jbarreiros committed Nov 28, 2020
1 parent 369d712 commit 2dd6c5f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
22 changes: 22 additions & 0 deletions __tests__/common/transforms.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,28 @@ describe('common', () => {
});
});

describe('size/pxToRem', () => {
const pxToRemTransformer = transforms["size/pxToRem"].transformer;

it('converts pixel to rem', () => {
expect(pxToRemTransformer({value: '12px'})).toBe('0.75rem');
});
it('converts pixel to rem using custom base font', () => {
expect(pxToRemTransformer({value: '14px'}, {basePxFontSize: 14})).toBe('1rem');
});
it('nonzero rem value not changed', () => {
expect(pxToRemTransformer({value: '2rem'})).toBe('2rem');
});
['0px', '0', '0rem'].forEach((value) => {
it(`zero value "${value}" is returned without a unit`, () => {
expect(pxToRemTransformer({value})).toBe('0');
});
});
it('should throw an error if prop value is Nan', () => {
expect( () => pxToRemTransformer({value: "a"})).toThrow();
});
});

describe('size/rem', () => {
it('should work', () => {
var value = transforms["size/rem"].transformer({
Expand Down
34 changes: 34 additions & 0 deletions lib/common/transforms.js
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,40 @@ module.exports = {
}
},

/**
* Scales the pixel value to rem, and adds 'rem' to the end of non-zero values. If you define a "basePxFontSize" on the platform in your config, it will be used to scale the pixel value, otherwise 16 (default web font size) will be used.
*
* ```js
* // Matches: prop.attributes.category === 'size'
* // Returns:
* 0
* 1rem
* ```
*/
'size/pxToRem': {
type: 'value',
matcher: (prop) => prop.attributes.category === 'size',
transformer: (prop, options) => {
const baseFont = (options && options.basePxFontSize) || 16;
const floatVal = parseFloat(prop.value);

if (isNaN(floatVal)) {
throwSizeError(prop.name, prop.value, 'rem');
}

if (floatVal === 0) {
return '0';
}

if (String(prop.value).indexOf('px') === -1) {
// ignore anything without a "px" unit
return prop.value;
}

return `${floatVal / baseFont}rem`;
}
},

/**
* Takes a unicode point and transforms it into a form CSS can use.
*
Expand Down

0 comments on commit 2dd6c5f

Please sign in to comment.