2023-09-19 11:27:22 +03:00
|
|
|
import { useRef } from 'preact/hooks';
|
2023-10-03 08:03:03 +03:00
|
|
|
import { useDebouncedCallback } from 'use-debounce';
|
2023-09-19 11:27:22 +03:00
|
|
|
import useResizeObserver from 'use-resize-observer';
|
|
|
|
|
|
|
|
export default function useTruncated({ className = 'truncated' } = {}) {
|
|
|
|
const ref = useRef();
|
2023-10-03 08:03:03 +03:00
|
|
|
const onResize = useDebouncedCallback(
|
|
|
|
({ height }) => {
|
2023-09-19 11:27:22 +03:00
|
|
|
if (ref.current) {
|
|
|
|
const { scrollHeight } = ref.current;
|
2023-10-03 08:03:03 +03:00
|
|
|
let truncated = scrollHeight > height;
|
|
|
|
if (truncated) {
|
|
|
|
const { height: _height, maxHeight } = getComputedStyle(ref.current);
|
|
|
|
const computedHeight = parseInt(maxHeight || _height, 10);
|
|
|
|
truncated = scrollHeight > computedHeight;
|
|
|
|
}
|
|
|
|
ref.current.classList.toggle(className, truncated);
|
2023-09-19 11:27:22 +03:00
|
|
|
}
|
|
|
|
},
|
2023-10-03 08:03:03 +03:00
|
|
|
300,
|
|
|
|
{
|
|
|
|
maxWait: 2000,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
useResizeObserver({
|
|
|
|
ref,
|
|
|
|
box: 'border-box',
|
|
|
|
onResize,
|
2023-09-19 11:27:22 +03:00
|
|
|
});
|
|
|
|
return ref;
|
|
|
|
}
|