2025-04-04 14:46:22 +00:00
|
|
|
import { useLayoutEffect, useState } from "react";
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* This hook checks if an element is truncated and returns a boolean value.
|
|
|
|
|
*/
|
|
|
|
|
// eslint-disable-next-line import/prefer-default-export
|
|
|
|
|
export const useCheckTruncatedElement = <T extends HTMLElement>(
|
|
|
|
|
ref: React.RefObject<T>
|
|
|
|
|
) => {
|
|
|
|
|
const [isTruncated, setIsTruncated] = useState(false);
|
|
|
|
|
|
2025-05-20 22:41:53 +00:00
|
|
|
const updateIsTruncated = (element: HTMLElement) => {
|
|
|
|
|
const { scrollWidth, clientWidth } = element;
|
|
|
|
|
setIsTruncated(scrollWidth > clientWidth);
|
|
|
|
|
};
|
|
|
|
|
|
2025-04-04 14:46:22 +00:00
|
|
|
useLayoutEffect(() => {
|
2025-05-20 22:41:53 +00:00
|
|
|
const resizeObserver = new ResizeObserver((entries) => {
|
|
|
|
|
entries.forEach((entry) => {
|
|
|
|
|
updateIsTruncated(entry.target as HTMLElement);
|
|
|
|
|
});
|
|
|
|
|
});
|
2025-04-04 14:46:22 +00:00
|
|
|
const element = ref.current;
|
2025-05-20 22:41:53 +00:00
|
|
|
if (element) {
|
|
|
|
|
updateIsTruncated(element);
|
|
|
|
|
resizeObserver.observe(ref.current as HTMLElement);
|
|
|
|
|
}
|
|
|
|
|
return () => {
|
2025-04-04 14:46:22 +00:00
|
|
|
if (element) {
|
2025-05-20 22:41:53 +00:00
|
|
|
resizeObserver.unobserve(element);
|
2025-04-04 14:46:22 +00:00
|
|
|
}
|
2025-05-20 22:41:53 +00:00
|
|
|
};
|
2025-04-04 14:46:22 +00:00
|
|
|
}, [ref]);
|
|
|
|
|
|
|
|
|
|
return isTruncated;
|
|
|
|
|
};
|