Skip to content

Commit

Permalink
feat: support rem units (#2955)
Browse files Browse the repository at this point in the history
  • Loading branch information
diegomura authored Nov 17, 2024
1 parent eea1d5d commit 425f118
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .changeset/famous-kings-dress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@react-pdf/layout": patch
"@react-pdf/stylesheet": minor
---

feat: support rem units
3 changes: 2 additions & 1 deletion packages/layout/src/steps/resolveStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ export const resolvePageStyles = (page) => {
const width = page.box?.width || page.style.width;
const height = page.box?.height || page.style.height;
const orientation = page.props?.orientation || 'portrait';
const container = { width, height, orientation, dpi };
const remBase = page.style?.fontSize || 18;
const container = { width, height, orientation, dpi, remBase };

return resolveNodeStyles(container)(page);
};
Expand Down
4 changes: 3 additions & 1 deletion packages/stylesheet/src/transform/units.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @returns {Object} parsed value
*/
const parseValue = (value) => {
const match = /^(-?\d*\.?\d+)(in|mm|cm|pt|vh|vw|px)?$/g.exec(value);
const match = /^(-?\d*\.?\d+)(in|mm|cm|pt|vh|vw|px|rem)?$/g.exec(value);

return match
? { value: parseFloat(match[1]), unit: match[2] || 'pt' }
Expand All @@ -27,6 +27,8 @@ const transformUnit = (container, value) => {
const cmFactor = (1 / 2.54) * dpi;

switch (scalar.unit) {
case 'rem':
return scalar.value * (container.remBase || 18);
case 'in':
return scalar.value * dpi;
case 'mm':
Expand Down
12 changes: 12 additions & 0 deletions packages/stylesheet/tests/resolve.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -581,4 +581,16 @@ describe('stylesheet resolve', () => {

expect(styles).toEqual({ fontSize: 10 });
});

test('should resolve rem units correctly', () => {
const styles = resolve({ remBase: 10 }, { fontSize: '2rem' });

expect(styles).toEqual({ fontSize: 20 });
});

test('should resolve rem units when base not specificed', () => {
const styles = resolve({}, { fontSize: '2rem' });

expect(styles).toEqual({ fontSize: 36 });
});
});
2 changes: 1 addition & 1 deletion packages/stylesheet/tests/transform.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, test } from 'vitest';

import _transformStyles from '../src/transform';

const CONTAINER = { width: 200, height: 400 };
const CONTAINER = { width: 200, height: 400, remBase: 10 };

const transformStyles = _transformStyles(CONTAINER);

Expand Down

0 comments on commit 425f118

Please sign in to comment.