1
1
import React , { useState , useEffect , useRef } from 'react' ;
2
2
3
+ /**
4
+ * Props for the `TruncatedText` component.
5
+ *
6
+ * Includes the text to be displayed and an optional maximum width override.
7
+ */
3
8
interface InterfaceTruncatedTextProps {
9
+ /** The full text to display. It may be truncated if it exceeds the maximum width. */
4
10
text : string ;
11
+ /** Optional: Override the maximum width for truncation. */
5
12
maxWidthOverride ?: number ;
6
13
}
7
14
15
+ /**
16
+ * A React functional component that displays text and truncates it with an ellipsis (`...`)
17
+ * if the text exceeds the available width or the `maxWidthOverride` value.
18
+ *
19
+ * The component adjusts the truncation dynamically based on the available space
20
+ * or the `maxWidthOverride` value. It also listens for window resize events to reapply truncation.
21
+ *
22
+ * @param props - The props for the component.
23
+ * @returns A heading element (`<h6>`) containing the truncated or full text.
24
+ *
25
+ * @example
26
+ * ```tsx
27
+ * <TruncatedText text="This is a very long text" maxWidthOverride={150} />
28
+ * ```
29
+ */
8
30
const TruncatedText : React . FC < InterfaceTruncatedTextProps > = ( {
9
31
text,
10
32
maxWidthOverride,
11
33
} ) => {
12
- const [ truncatedText , setTruncatedText ] = useState < string > ( '' ) ;
13
- const textRef = useRef < HTMLHeadingElement > ( null ) ;
34
+ const [ truncatedText , setTruncatedText ] = useState < string > ( '' ) ; // State to store the truncated text
35
+ const textRef = useRef < HTMLHeadingElement > ( null ) ; // Ref to measure the width of the text container
14
36
15
37
useEffect ( ( ) => {
38
+ /**
39
+ * Truncate the text based on the available width or the `maxWidthOverride` value.
40
+ */
16
41
const truncateText = ( ) : void => {
17
42
const element = textRef . current ;
18
43
if ( element ) {
@@ -21,7 +46,7 @@ const TruncatedText: React.FC<InterfaceTruncatedTextProps> = ({
21
46
22
47
const computedStyle = getComputedStyle ( element ) ;
23
48
const fontSize = parseFloat ( computedStyle . fontSize ) ;
24
- const charPerPx = 0.065 + fontSize * 0.002 ; // Adjust value for truncation according to our needs
49
+ const charPerPx = 0.065 + fontSize * 0.002 ;
25
50
const maxChars = Math . floor ( maxWidth * charPerPx ) ;
26
51
27
52
setTruncatedText (
@@ -34,7 +59,6 @@ const TruncatedText: React.FC<InterfaceTruncatedTextProps> = ({
34
59
35
60
truncateText ( ) ;
36
61
window . addEventListener ( 'resize' , truncateText ) ;
37
-
38
62
return ( ) => window . removeEventListener ( 'resize' , truncateText ) ;
39
63
} , [ text , maxWidthOverride ] ) ;
40
64
0 commit comments