Skip to content

Commit

Permalink
fix: Add support for non-breaking space (#359)
Browse files Browse the repository at this point in the history
fixes #293.

---------

Co-authored-by: Shu Ding <[email protected]>
  • Loading branch information
sahithyandev and shuding authored Apr 17, 2023
1 parent 61dfc3b commit 44f4a6b
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,35 @@ export function segment(
})
}

return granularity === 'word'
? [...wordSegmenter.segment(content)].map((seg) => seg.segment)
: [...graphemeSegmenter.segment(content)].map((seg) => seg.segment)
if (granularity === 'grapheme') {
return [...graphemeSegmenter.segment(content)].map((seg) => seg.segment)
} else {
const segmented = [...wordSegmenter.segment(content)].map(
(seg) => seg.segment
) as string[]

const output = []

let i = 0
// When there is a non-breaking space, join the previous and next words together.
// This change causes them to be treated as a single segment.
while (i < segmented.length) {
const s = segmented[i]

if (s == '\u00a0') {
const previousWord = i === 0 ? '' : output.pop()
const nextWord = i === segmented.length - 1 ? '' : segmented[i + 1]

output.push(previousWord + '\u00a0' + nextWord)
i += 2
} else {
output.push(s)
i++
}
}

return output
}
}

export function buildXMLString(
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions test/word-break.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,31 @@ describe('word-break', () => {
})
})

it('should support non-breaking space', async () => {
const text = `She weighs around blah 50\u00a0kg`
const svg = await satori(
<div
style={{
color: 'red',
display: 'flex',
flexDirection: 'column',
width: '100%',
wordBreak: 'normal',
}}
>
<span>{text}</span>
<span>{text.replaceAll('\u00A0', ' ')}</span>
</div>,
{
width: 200,
height: 100,
fonts,
}
)

expect(toImage(svg, 200)).toMatchImageSnapshot()
})

describe('break-all', () => {
it('should always break words eagerly', async () => {
const svg = await satori(
Expand Down

1 comment on commit 44f4a6b

@vercel
Copy link

@vercel vercel bot commented on 44f4a6b Apr 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.