Skip to content

Commit

Permalink
fix: bestFit breakpoint issue (#1567)
Browse files Browse the repository at this point in the history
Co-authored-by: Dmitry Ivakhnenko <jeetiss@yandex.ru>
  • Loading branch information
hayoung0Lee and jeetiss committed Dec 18, 2021
1 parent 46a4b0c commit 5d2d688
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/seven-buttons-joke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/textkit': patch
---

fixed line breaks for the case when the word in a text is bigger than the given width
18 changes: 16 additions & 2 deletions packages/textkit/src/engines/linebreaker/bestFit.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,21 @@ const getNextBreakpoint = (subnodes, widths, lineNumber) => {
sum.shrink += node.shrink;
}

if (sum.width - sum.shrink > lineLength) break;
if (sum.width - sum.shrink > lineLength) {
if (position === null) {
let j = i === 0 ? i + 1 : i;

while (
j < subnodes.length &&
(subnodes[j].type === 'glue' || subnodes[j].type === 'penalty')
) {
j++;
}

position = j - 1;
}
break;
}

if (node.type === 'penalty' || node.type === 'glue') {
const ratio = calculateRatio(node);
Expand All @@ -61,7 +75,7 @@ const applyBestFit = (nodes, widths) => {
while (subnodes.length > 0) {
const breakpoint = getNextBreakpoint(subnodes, widths, lineNumber);

if (breakpoint) {
if (breakpoint !== null) {
count += breakpoint;
breakpoints.push({ position: count });
subnodes = subnodes.slice(breakpoint + 1, subnodes.length);
Expand Down
72 changes: 72 additions & 0 deletions packages/textkit/tests/engines/linebreaker/bestFit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import applyBestFit from '../../../src/engines/linebreaker/bestFit';

const width = 50;

describe('bestFit', () => {
test('should return at least one breakpoint', () => {
const node = [
{
type: 'box',
width: 25,
},
{
type: 'glue',
width: 0,
stretch: 10000,
shrink: 0,
},
{
type: 'penalty',
width: 0,
penalty: -10000,
},
];

const breakpoints = applyBestFit(node, [width]);
expect(breakpoints.length).toBe(1);
});

test('should break lines when the subnode is bigger than the given widths', () => {
const node = [
{
type: 'box',
width: 55,
},
{
type: 'glue',
width: 5,
stretch: 1,
shrink: 1,
},
{
type: 'box',
width: 55,
},
{
type: 'glue',
width: 5,
stretch: 1,
shrink: 1,
},
{
type: 'box',
width: 25,
},
{
type: 'glue',
width: 0,
stretch: 10000,
shrink: 0,
},
{
type: 'penalty',
width: 0,
penalty: -10000,
},
];

const breakpoints = applyBestFit(node, [width]);

expect(breakpoints.length).toBe(3);
});
});

0 comments on commit 5d2d688

Please sign in to comment.