1 import type React from 'react';
2 import { useContext, useEffect } from 'react';
4 import { FloatingEllipsisContext } from '../FloatingEllipsisContext';
5 import type { FloatingEllipsisContextValue, FloatingEllipsisEventType } from './useFloatingEllipsisContext';
7 const VISIBILITY_CLASS = 'floating-ellipsis-hidden';
9 export const useFloatingEllipsisEventBasedUpdater = ({
13 visibilityControlRef: React.RefObject<HTMLDivElement>;
14 elem: React.RefObject<HTMLDivElement>;
16 const { events, getDimensions } = useContext<FloatingEllipsisContextValue>(FloatingEllipsisContext);
18 const updateVisibility = () => {
22 const { scrollWidth, scrollLeft } = getDimensions();
24 if (!visibilityControlRef.current) {
27 const rightEnd = visibilityControlRef.current.offsetLeft + visibilityControlRef.current.offsetWidth;
28 const elemWidth = elem.current?.offsetWidth || 0;
29 const visible = rightEnd > scrollWidth + scrollLeft;
31 elem.current.style.left = `${scrollWidth + scrollLeft - elemWidth}px`;
32 elem.current.classList.remove(VISIBILITY_CLASS);
34 elem.current.classList.add(VISIBILITY_CLASS);
39 const eventTypes: FloatingEllipsisEventType[] = ['resize', 'scroll'];
40 eventTypes.forEach((eventType) => events.addEventListener(eventType, updateVisibility));
42 eventTypes.forEach((eventType) => events.removeEventListener(eventType, updateVisibility));
46 return updateVisibility;