UNPKG

@blocdigital/usetoplayerelement

Version:
59 lines (58 loc) 2.1 kB
export interface useTopLayerElementsReturn<T extends HTMLElement> { ref: React.RefObject<T | null>; topElement: HTMLElement | null; topDialog: HTMLElement | null; isInTopLayer: boolean; isTopElement: boolean; topLayerList: HTMLElement[]; } /** * React hook to track and interact with elements in the "top layer" (such as dialogs and popovers). * * This hook provides a ref to attach to your element, and returns information about its position * and presence in the top layer, as well as the current list of top layer elements. * * The top layer is determined by listening for the `toggle` event on dialogs and popovers, * and by observing DOM mutations for automatic cleanup. * * @template T - The type of HTMLElement to track. * @returns {useTopLayerElementsReturn<T>} An object containing: * - `ref`: React ref to attach to your element. * - `topElement`: The topmost element in the top layer. * - `topDialog`: The topmost dialog element in the top layer. * - `isInTopLayer`: Whether your element is currently in the top layer. * - `isTopElement`: Whether your element is the topmost element in the top layer. * - `topLayerList`: Array of all elements currently in the top layer. * * @example * ```tsx * import useTopLayerElements from './useTopLayerElement'; * * function MyDialog() { * const { ref, isInTopLayer, isTopElement } = useTopLayerElements<HTMLDialogElement>(); * * return ( * <dialog ref={ref} open> * {isInTopLayer && <span>I'm in the top layer!</span>} * {isTopElement && <span>I'm the topmost dialog!</span>} * </dialog> * ); * } * ``` * * @example * ```tsx * import useTopLayerElements from './useTopLayerElement'; * * function MyPopover() { * const { ref, topLayerList } = useTopLayerElements<HTMLDivElement>(); * * return ( * <div ref={ref} popover="auto"> * <span>Current top layer count: {topLayerList.length}</span> * </div> * ); * } * ``` */ export default function useTopLayerElements<T extends HTMLElement>(): useTopLayerElementsReturn<T>;