diff --git a/examples/basic/src/App.tsx b/examples/basic/src/App.tsx
index a600ef7..d6d6abb 100644
--- a/examples/basic/src/App.tsx
+++ b/examples/basic/src/App.tsx
@@ -53,7 +53,7 @@ const App: React.FC = () => {
-
Middle Truncate
+ Middle Truncate (Chinese)
diff --git a/package.json b/package.json
index e56c4ac..68a01da 100644
--- a/package.json
+++ b/package.json
@@ -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 ",
"license": "MIT",
diff --git a/src/Truncate/Truncate.tsx b/src/Truncate/Truncate.tsx
index 209f4f0..3e6102a 100644
--- a/src/Truncate/Truncate.tsx
+++ b/src/Truncate/Truncate.tsx
@@ -103,6 +103,10 @@ export const Truncate: React.FC = ({
return middle ? 1 : defaultLines
}, [defaultLines, middle])
+ const endPos = useMemo(() => {
+ return Math.floor(end <= 0 ? end : -end)
+ }, [end])
+
const getLines = useCallback(() => {
const resultLines: Array = []
const textLine = innerText(textRef.current, separator)
@@ -140,11 +144,17 @@ export const Truncate: React.FC = ({
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
@@ -166,12 +176,9 @@ export const Truncate: React.FC = ({
}
if (middle) {
- const endPos = end <= 0 ? end : -end
- const startFragment = lastLineText.slice(0, endPos)
- const endFragment = lastLineText.slice(endPos)
resultLine = (
- {startFragment}
+ {lastLineText}
{ellipsis}
{endFragment}
@@ -224,9 +231,9 @@ export const Truncate: React.FC = ({
lines,
measureWidth,
targetWidth,
- trimWhitespace,
middle,
- end,
+ endPos,
+ trimWhitespace,
ellipsis,
])