|
1
|
import { Tooltip, clx } from "@medusajs/ui" |
|
2
|
import { useRef, useState } from "react" |
|
3
|
|
|
4
|
interface TruncatedTextProps { |
|
5
|
/** |
|
6
|
* The full text. Rendered truncated; also used as the tooltip content. |
|
7
|
*/ |
|
8
|
text: string |
|
9
|
className?: string |
|
10
|
} |
|
11
|
|
|
12
|
/** |
|
13
|
* Truncating text span that shows a tooltip with the full text only when the |
|
14
|
* content actually overflows its container. |
|
15
|
* |
|
16
|
* Overflow is measured lazily on hover, so layout/resize changes don't need |
|
17
|
* to be observed. |
|
18
|
*/ |
|
19
|
export const TruncatedText = ({ text, className }: TruncatedTextProps) => { |
|
20
|
const ref = useRef<HTMLSpanElement>(null) |
|
21
|
const [overflow, setOverflow] = useState(false) |
|
22
|
|
|
23
|
const check = () => { |
|
24
|
const el = ref.current |
|
25
|
if (el) { |
|
26
|
setOverflow(el.scrollWidth > el.clientWidth) |
|
27
|
} |
|
28
|
} |
|
29
|
|
|
30
|
return ( |
|
31
|
// Cap the tooltip's width and break long unbroken strings so the text |
|
32
|
// wraps inside the bubble instead of overflowing it. |
|
33
|
<Tooltip |
|
34
|
content={text} |
|
35
|
hidden={!overflow} |
|
36
|
className="max-w-[360px] break-words" |
|
37
|
> |
|
38
|
<span |
|
39
|
ref={ref} |
|
40
|
onMouseEnter={check} |
|
41
|
// min-w-0 lets the span shrink below its content inside flex parents |
|
42
|
// (e.g. a Badge), which is what allows `truncate` to kick in. |
|
43
|
className={clx("min-w-0 truncate", className)} |
|
44
|
> |
|
45
|
{text} |
|
46
|
</span> |
|
47
|
</Tooltip> |
|
48
|
) |
|
49
|
} |