/ src / utils / useTruncated.js
useTruncated.js
 1  import { useRef } from 'preact/hooks';
 2  import { useThrottledCallback } from 'use-debounce';
 3  import useResizeObserver from 'use-resize-observer';
 4  
 5  export default function useTruncated({ className = 'truncated' } = {}) {
 6    const ref = useRef();
 7    const onResize = useThrottledCallback(({ height }) => {
 8      if (ref.current) {
 9        const { scrollHeight } = ref.current;
10        let truncated = scrollHeight > height;
11        if (truncated) {
12          const { height: _height, maxHeight } = getComputedStyle(ref.current);
13          const computedHeight = parseInt(maxHeight || _height, 10);
14          truncated = scrollHeight > computedHeight;
15        }
16        ref.current.classList.toggle(className, truncated);
17      }
18    }, 300);
19    useResizeObserver({
20      ref,
21      box: 'border-box',
22      onResize,
23    });
24    return ref;
25  }