({
children,
maxHeight = DEFAULT_MAX_HEIGHT,
className,
}: ExpandableContentProps)
| 19 | const DEFAULT_MAX_HEIGHT = 320; // pixels |
| 20 | |
| 21 | export function ExpandableContent({ |
| 22 | children, |
| 23 | maxHeight = DEFAULT_MAX_HEIGHT, |
| 24 | className, |
| 25 | }: ExpandableContentProps): ReactElement { |
| 26 | const [isExpanded, setIsExpanded] = useState(false); |
| 27 | const [showSeeMore, setShowSeeMore] = useState(false); |
| 28 | const contentRef = useRef<HTMLDivElement>(null); |
| 29 | |
| 30 | useEffect(() => { |
| 31 | const element = contentRef.current; |
| 32 | if (!element) { |
| 33 | return undefined; |
| 34 | } |
| 35 | |
| 36 | const checkHeight = () => { |
| 37 | const contentHeight = element.scrollHeight; |
| 38 | setShowSeeMore(contentHeight > maxHeight); |
| 39 | }; |
| 40 | |
| 41 | // Wait for browser to complete layout before checking height |
| 42 | // Using double RAF ensures the layout is fully calculated |
| 43 | const rafId = requestAnimationFrame(() => { |
| 44 | requestAnimationFrame(() => { |
| 45 | checkHeight(); |
| 46 | }); |
| 47 | }); |
| 48 | |
| 49 | // Only use ResizeObserver if there are images (for async loading) |
| 50 | const hasImages = element.querySelector('img') !== null; |
| 51 | if (!hasImages) { |
| 52 | return () => cancelAnimationFrame(rafId); |
| 53 | } |
| 54 | |
| 55 | const resizeObserver = new ResizeObserver(checkHeight); |
| 56 | resizeObserver.observe(element); |
| 57 | |
| 58 | return () => { |
| 59 | cancelAnimationFrame(rafId); |
| 60 | resizeObserver.disconnect(); |
| 61 | }; |
| 62 | }, [maxHeight, children]); |
| 63 | |
| 64 | return ( |
| 65 | <> |
| 66 | <div |
| 67 | ref={contentRef} |
| 68 | className={classNames( |
| 69 | 'relative transition-all duration-500 ease-in-out', |
| 70 | { |
| 71 | 'overflow-hidden': !isExpanded, |
| 72 | }, |
| 73 | className, |
| 74 | )} |
| 75 | style={{ |
| 76 | maxHeight: !isExpanded ? `${maxHeight}px` : undefined, |
| 77 | }} |
| 78 | > |
nothing calls this directly
no test coverage detected