Skip to content

Commit

Permalink
feat: make nested text inherit background colors (#2504)
Browse files Browse the repository at this point in the history
* feat: make nested text inherit background colors

* chore: add changeset
  • Loading branch information
diegomura authored Jan 17, 2024
1 parent 96ea576 commit e705d98
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/cold-tips-work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/layout': patch
---

feat: nested text inherit background color
16 changes: 14 additions & 2 deletions packages/layout/src/steps/resolveInheritance.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as P from '@react-pdf/primitives';
import { pick, compose } from '@react-pdf/fns';

const INHERITED_PROPERTIES = [
const BASE_INHERITABLE_PROPERTIES = [
'color',
'fontFamily',
'fontSize',
Expand All @@ -17,8 +17,15 @@ const INHERITED_PROPERTIES = [
'wordSpacing',
];

const TEXT_INHERITABLE_PROPERTIES = [
...BASE_INHERITABLE_PROPERTIES,
'backgroundColor',
];

const isSvg = node => node.type === P.Svg;

const isText = node => node.type === P.Text;

// Merge style values
const mergeValues = (styleName, value, inheritedValue) => {
switch (styleName) {
Expand Down Expand Up @@ -67,9 +74,14 @@ const mergeStyles = inheritedStyles => node => {
*/
const resolveInheritance = node => {
if (isSvg(node)) return node;

if (!node.children) return node;

const inheritStyles = pick(INHERITED_PROPERTIES, node.style || {});
const inheritableProperties = isText(node)
? TEXT_INHERITABLE_PROPERTIES
: BASE_INHERITABLE_PROPERTIES;

const inheritStyles = pick(inheritableProperties, node.style || {});

const resolveChild = compose(resolveInheritance, mergeStyles(inheritStyles));

Expand Down
26 changes: 26 additions & 0 deletions packages/layout/tests/steps/resolveInhritance.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,32 @@ describe('layout resolveInheritance', () => {
);
});

test('Should inherit background color for text childs', () => {
const root = {
type: 'DOCUMENT',
children: [
{
type: 'PAGE',
style: {},
children: [
{
type: 'TEXT',
style: { backgroundColor: 'red' },
children: [{ type: 'TEXT' }],
},
],
},
],
};

const result = resolveInheritance(root);
const text1 = result.children[0].children[0];
const text2 = text1.children[0];

expect(text1.style).toHaveProperty('backgroundColor', 'red');
expect(text2.style).toHaveProperty('backgroundColor', 'red');
});

test('Should inherit color value', shouldInherit('color'));
test('Should inherit fontFamily value', shouldInherit('fontFamily'));
test('Should inherit fontSize value', shouldInherit('fontSize'));
Expand Down

0 comments on commit e705d98

Please sign in to comment.