Skip to content

Don't split a character outside the BMP when wrapping a long word - #1872

Open
SwastikTripathi wants to merge 1 commit into
foliojs:masterfrom
SwastikTripathi:fix/line-wrapper-surrogate-pairs
Open

SwastikTripathi wants to merge 1 commit into
foliojs:masterfrom
SwastikTripathi:fix/line-wrapper-surrogate-pairs

Conversation

@SwastikTripathi

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Bug fix. When a word is too wide for the line, LineWrapper cuts it where the space runs out, counting in UTF-16 code units. A character outside the BMP (an emoji, a CJK extension character, a math letter like 𝕆) is two code units, so the cut can fall between them:

doc.font('DejaVuSans.ttf').text('𝔸𝔹ℂ𝔻𝔼𝔽𝔾ℍ𝕀𝕁𝕂𝕃𝕄ℕ𝕆ℙℚℝ𝕊𝕋𝕌𝕍𝕎𝕏𝕐ℤ', { width: 60 });
// lines: "𝔸𝔹ℂ𝔻𝔼𝔽\ud835", "\udd3eℍ𝕀𝕁𝕂𝕃𝕄", ...

Each half is then encoded and drawn on its own, so the character turns into two broken glyphs, one at the end of a line and one at the start of the next. The ellipsis code has the same problem: it trims one code unit at a time until the … fits, which can leave the first half of a pair before it.

After the shrink/grow search, the split point now steps back one unit if it falls inside a surrogate pair. When not even one character fits on an empty line, the whole pair goes on the line instead of half of it. The ellipsis loop drops a whole pair at a time. Breaking by grapheme clusters (the TODO above that loop) would also cover combining marks and emoji sequences; this only makes sure a single code point is never cut in two.

Checklist:

  • Unit Tests
  • Documentation N/A
  • Update CHANGELOG.md
  • Ready to be merged

New LineWrapper tests wrap a long word of double-struck letters at several widths with examples/fonts/DejaVuSans.ttf (it needs a font with the real glyphs: with the standard fonts these have no width, and with .notdef half a pair is as wide as a whole one), and check that no line starts or ends inside a pair and that the lines join back to the word. They also check the text before an ellipsis. 6 of the 9 cases fail on master and all pass with this change. All 676 tests (yarn test) pass, and eslint and prettier are clean.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant