Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smart-maps-pay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/textkit': patch
---

Improve text line slicing performance for long paragraphs.
10 changes: 6 additions & 4 deletions packages/textkit/src/engines/linebreaker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@ const breakLines = (
let start = 0;
let end = null;

const lines: AttributedString[] = breaks.reduce((acc, breakPoint) => {
const lines: AttributedString[] = [];

for (const breakPoint of breaks) {
const node = nodes[breakPoint];
const prevNode = nodes[breakPoint - 1];

// Last breakpoint corresponds to K&P mandatory final glue
if (breakPoint === nodes.length - 1) return acc;
if (breakPoint === nodes.length - 1) continue;

let line: AttributedString;
if (node.type === 'penalty') {
Expand All @@ -54,8 +56,8 @@ const breakLines = (

start = end;

return [...acc, line];
}, []);
lines.push(line);
}

lines.push(slice(start, attributedString.string.length, attributedString));

Expand Down
14 changes: 10 additions & 4 deletions packages/textkit/src/run/glyphIndexAt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,18 @@ const glyphIndexAt = (index: number, run: Run) => {
return glyphIndices.length;
}

let low = 0;
let high = glyphIndices.length - 1;
let result = index;

for (let i = glyphIndices.length - 1; i >= 0; i -= 1) {
if (glyphIndices[i] <= index) {
result = i;
break;
while (low <= high) {
const mid = (low + high) >> 1;

if (glyphIndices[mid] <= index) {
result = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}

Expand Down
10 changes: 9 additions & 1 deletion packages/textkit/src/run/offset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@ const offset = (index: number, run: Run) => {
const stringIndices = run.stringIndices || [];
const value = stringIndices[index];

return stringIndices.slice(0, index).filter((i) => i === value).length;
if (value === undefined) return 0;

let result = 0;

for (let i = index - 1; i >= 0 && stringIndices[i] === value; i -= 1) {
result += 1;
}

return result;
};

export default offset;
Loading