Ant Design's Typography component provides an ellipsis property to display ellipsis when text overflows. It supports limiting the number of displayed lines through the ellipsis.rows configuration. If it is pure text content, it will be implemented through the CSS -webkit-line-clamp property. Although it has a -webkit- prefix, it has been well supported in modern browsers.
<div
style={{
display:'-webkit-box',
overflow:'hidden',
WebkitBoxOrient:'vertical',
webkitLineClamp:3,
}}
>
{text}
</div>
Some issues with CSS
However, CSS implementation also has limitations, that is, it does not support modifying the ellipsis and supporting additional action buttons (such as copy, edit, expand, etc.):
Operational buttons will be truncated together and cannot be displayed.
Though there are some magic methods to achieve this through styles such as float, this method requires targeted processing in different browsers. In addition, it still cannot solve the problem of custom ellipsis. Therefore, the best implementation method is still through JS.
Using JS
With JS, we can quickly find the truncation position of the text through binary search. As long as the height of the text is inferred based on rows, we can traverse and find the maximum number of characters that can be displayed:
And get the line height by simulating an embedded span:
<div>
{text}
{measuring &&<spanref={measureRef}> </span>}
</div>
But this method also has some problems, for mixed line height scenarios (such as adding images, embedding different sizes of text, etc.). This calculation method often estimates the wrong total height, making the truncation position inaccurate:
Since the height of the image exceeds the line height, the calculation thinks that the image occupies the height of two lines. At the same time, because the image itself cannot be truncated, the final number of ellipsis lines is incorrect (3 lines of ellipsis becomes 2 lines):
Even worse, if the image is on the first line, the entire text will be truncated:
But if you use CSS, there will be no such problem:
Mixed Measurement
To solve this problem, we can use a mixed measurement method. That is, use CSS to measure the total height of the native multi-line ellipsis, and then use JS to perform binary search to ensure that the truncation position of the text does not exceed the total height measured by CSS:
This helps to accurately handle mixed line height scenarios:
Summary
The mixed measurement method allows us to easily use the accuracy of CSS and the flexibility of JS to achieve accurate text truncation even in complex content containing images and other elements with different line heights.
This refactoring has been released in 5.15.0, welcome to experience it.