1 import type { RefObject } from 'react';
2 import { useEffect, useState } from 'react';
4 export type FloatingEllipsisEventType = 'resize' | 'scroll';
6 export interface FloatingEllipsisContextValue {
8 getDimensions: () => FloatingEllipsisContainerDimensions;
11 interface FloatingEllipsisContainerDimensions {
16 export const useFloatingEllipsisContext = ({
20 containerRef: RefObject<HTMLDivElement>;
21 resizableRef?: RefObject<HTMLElement>;
22 }): FloatingEllipsisContextValue => {
23 const [events] = useState<EventTarget>(new EventTarget());
24 const getDimensions = (): FloatingEllipsisContainerDimensions => ({
25 scrollWidth: containerRef.current?.clientWidth ?? 0,
26 scrollLeft: containerRef.current?.scrollLeft ?? 0,
28 const [context] = useState<FloatingEllipsisContextValue>({
33 const triggerScroll = () => events.dispatchEvent(new Event('scroll' as FloatingEllipsisEventType));
35 const resizeObserver = new ResizeObserver(() => {
36 events.dispatchEvent(new Event('resize' as FloatingEllipsisEventType));
40 if (!containerRef.current) {
43 resizeObserver.observe(containerRef.current);
44 containerRef.current.addEventListener('scroll', triggerScroll);
46 if (resizableRef?.current) {
47 resizeObserver.observe(resizableRef.current);
51 if (!containerRef.current) {
54 resizeObserver.disconnect();
55 containerRef.current.removeEventListener('scroll', triggerScroll);