forked from opendatahub-io/odh-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathTruncatedText.tsx
More file actions
72 lines (65 loc) · 1.75 KB
/
TruncatedText.tsx
File metadata and controls
72 lines (65 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React from 'react';
import { Tooltip } from '@patternfly/react-core';
type TruncatedTextProps = {
maxLines: number;
content: React.ReactNode;
tooltipMaxLines?: number;
} & Omit<React.HTMLProps<HTMLSpanElement>, 'content'>;
const TruncatedText: React.FC<TruncatedTextProps> = ({
maxLines,
content,
tooltipMaxLines,
...props
}) => {
const outerElementRef = React.useRef<HTMLElement>(null);
const textElementRef = React.useRef<HTMLElement>(null);
const [isTruncated, setIsTruncated] = React.useState<boolean>(false);
const updateTruncation = React.useCallback(() => {
if (textElementRef.current && outerElementRef.current) {
setIsTruncated(textElementRef.current.offsetHeight > outerElementRef.current.offsetHeight);
}
}, []);
const truncateBody = (
<span
{...props}
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
overflowWrap: 'anywhere',
overflow: 'hidden',
WebkitLineClamp: maxLines,
...(props.style || {}),
}}
ref={outerElementRef}
onMouseEnter={(e) => {
props.onMouseEnter?.(e);
updateTruncation();
}}
onFocus={(e) => {
props.onFocus?.(e);
updateTruncation();
}}
>
<span ref={textElementRef}>{content}</span>
</span>
);
const truncateTooltipBody = (
<span
style={{
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
overflowWrap: 'anywhere',
overflow: 'hidden',
WebkitLineClamp: tooltipMaxLines,
}}
>
{content}
</span>
);
return (
<Tooltip hidden={!isTruncated ? true : undefined} content={truncateTooltipBody}>
{truncateBody}
</Tooltip>
);
};
export default TruncatedText;