(maxLines: number)
| 31 | * move where it starts. |
| 32 | */ |
| 33 | export const useFittedLineClamp = (maxLines: number): FittedLineClamp => { |
| 34 | // Nodes as state, not refs, so the effect re-runs when they attach. |
| 35 | const [container, setContainer] = useState<HTMLElement | null>(null); |
| 36 | const [text, setText] = useState<HTMLElement | null>(null); |
| 37 | const [lines, setLines] = useState(maxLines); |
| 38 | |
| 39 | useEffect(() => { |
| 40 | if (!container || !text || typeof ResizeObserver === 'undefined') { |
| 41 | return undefined; |
| 42 | } |
| 43 | |
| 44 | const measure = () => { |
| 45 | const style = getComputedStyle(text); |
| 46 | const lineHeight = parseFloat(style.lineHeight); |
| 47 | |
| 48 | // `normal` gives no number to divide by; leave the CSS clamp in charge. |
| 49 | if (!lineHeight) { |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | const bottom = |
| 54 | container.getBoundingClientRect().bottom - |
| 55 | parseFloat(getComputedStyle(container).paddingBottom || '0'); |
| 56 | const available = bottom - text.getBoundingClientRect().top; |
| 57 | |
| 58 | setLines( |
| 59 | Math.max(0, Math.min(maxLines, Math.floor(available / lineHeight))), |
| 60 | ); |
| 61 | }; |
| 62 | |
| 63 | // The container's height moves the floor, the text's moves the ceiling. |
| 64 | const observer = new ResizeObserver(measure); |
| 65 | |
| 66 | observer.observe(container); |
| 67 | observer.observe(text); |
| 68 | measure(); |
| 69 | |
| 70 | return () => observer.disconnect(); |
| 71 | }, [container, text, maxLines]); |
| 72 | |
| 73 | const style = useMemo<CSSProperties>( |
| 74 | () => (lines > 0 ? { WebkitLineClamp: lines } : { visibility: 'hidden' }), |
| 75 | [lines], |
| 76 | ); |
| 77 | |
| 78 | return { |
| 79 | containerRef: useCallback((node: HTMLElement | null) => { |
| 80 | setContainer(node); |
| 81 | }, []), |
| 82 | textRef: useCallback((node: HTMLElement | null) => { |
| 83 | setText(node); |
| 84 | }, []), |
| 85 | lines, |
| 86 | style, |
| 87 | }; |
| 88 | }; |
no test coverage detected