From 363c6fd18ac47bfca5b30979613b8daef12a6460 Mon Sep 17 00:00:00 2001 From: Shiny Date: Mon, 21 Feb 2022 22:13:11 +0800 Subject: [PATCH] release 0.18.0 --- CHANGELOG.md | 1 + lib/index.js | 18 ++++++++++++------ package.json | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6ca83d..df699f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## Changelog +- 0.18.0 Fix text width not calculate correctly - 0.17.0 Support React 17 - 0.16.0 Change wrapper tag from div to span - 0.15.0 Update dependencies to fix security issues diff --git a/lib/index.js b/lib/index.js index 415908e..07da43d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -164,6 +164,12 @@ return obj; } + var PRECISION = 0.0001; + + var isEqual = function isEqual(n1, n2) { + return Math.abs(n1 - n2) < PRECISION; + }; + var TextTruncate = function (_Component) { _inherits(TextTruncate, _Component); @@ -242,7 +248,7 @@ }, { key: "measureWidth", value: function measureWidth(text) { - return Math.ceil(this.canvas.measureText(text).width); + return this.canvas.measureText(text).width; } }, { key: "getRenderText", @@ -265,10 +271,11 @@ if (scopeWidth === 0) { return null; - } // return if all of text can be displayed + } + var fullTextWidth = this.measureWidth(text); // return if all of text can be displayed - if (scopeWidth >= this.measureWidth(text)) { + if (scopeWidth > fullTextWidth || isEqual(scopeWidth, fullTextWidth)) { this.onToggled(false); return (0, _react.createElement)(textElement, props, text); } @@ -351,7 +358,7 @@ } width = this.measureWidth(truncatedText + ext); - } while (width >= scopeWidth && truncatedText.length > 0); + } while ((width > scopeWidth || isEqual(width, scopeWidth)) && truncatedText.length > 0); startPos += currentPos; break; @@ -406,7 +413,6 @@ fontSize = style.fontSize, fontFamily = style.fontFamily; var renderText = this.scope && line ? this.getRenderText() : (0, _react.createElement)(textElement, props, text); - ; var rootProps = { ref: function ref(el) { _this2.scope = el; @@ -436,7 +442,7 @@ onTruncated: _propTypes2["default"].func, onToggled: _propTypes2["default"].func, text: _propTypes2["default"].string, - textElement: _propTypes2["default"].node, + textElement: _propTypes2["default"].elementType, textTruncateChild: _propTypes2["default"].node, truncateText: _propTypes2["default"].string, maxCalculateTimes: _propTypes2["default"].number diff --git a/package.json b/package.json index 821b5b6..7c37313 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-text-truncate", - "version": "0.17.0", + "version": "0.18.0", "description": "Truncate text for React.js", "main": "lib/index.js", "scripts": {