Skip to content

Commit

Permalink
fix(Truncate): when the middle option is enabled, the wrong end fragm…
Browse files Browse the repository at this point in the history
…ent is obtained
  • Loading branch information
chengpeiquan committed Jan 20, 2024
1 parent eb4701e commit 0f7d2cf
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
2 changes: 1 addition & 1 deletion examples/basic/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const App: React.FC = () => {
<hr />

<div style={{ width: `${range}%` }}>
<h2>Middle Truncate</h2>
<h2>Middle Truncate (Chinese)</h2>

<MiddleTruncate separator="">
<ChineseRichText />
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@re-dev/react-truncate",
"version": "0.3.1",
"version": "0.3.2",
"description": "Provides `Truncate`, `MiddleTruncate` and `ShowMore` React components for truncating multi-line spans and adding an ellipsis.",
"author": "chengpeiquan <[email protected]>",
"license": "MIT",
Expand Down
21 changes: 14 additions & 7 deletions src/Truncate/Truncate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ export const Truncate: React.FC<TruncateProps> = ({
return middle ? 1 : defaultLines
}, [defaultLines, middle])

const endPos = useMemo(() => {
return Math.floor(end <= 0 ? end : -end)
}, [end])

const getLines = useCallback(() => {
const resultLines: Array<string | JSX.Element> = []
const textLine = innerText(textRef.current, separator)
Expand Down Expand Up @@ -140,11 +144,17 @@ export const Truncate: React.FC<TruncateProps> = ({
let lower = 0
let upper = textRest.length - 1

const endFragment = middle ? textLine.slice(endPos) : ''
const endFragmentWidth = middle ? measureWidth(endFragment) : 0

while (lower <= upper) {
const middle = Math.floor((lower + upper) / 2)
const testLine = textRest.slice(0, middle + 1)

if (measureWidth(testLine) + ellipsisWidth <= targetWidth) {
if (
measureWidth(testLine) + ellipsisWidth + endFragmentWidth <=
targetWidth
) {
lower = middle + 1
} else {
upper = middle - 1
Expand All @@ -166,12 +176,9 @@ export const Truncate: React.FC<TruncateProps> = ({
}

if (middle) {
const endPos = end <= 0 ? end : -end
const startFragment = lastLineText.slice(0, endPos)
const endFragment = lastLineText.slice(endPos)
resultLine = (
<span>
{startFragment}
{lastLineText}
{ellipsis}
{endFragment}
</span>
Expand Down Expand Up @@ -224,9 +231,9 @@ export const Truncate: React.FC<TruncateProps> = ({
lines,
measureWidth,
targetWidth,
trimWhitespace,
middle,
end,
endPos,
trimWhitespace,
ellipsis,
])

Expand Down

0 comments on commit 0f7d2cf

Please sign in to comment.