import { ComponentProps, ForwardedRef, RefObject, useContext, useMemo, useRef, } from 'react'; import { useForwardedRef, useIsomorphicLayoutEffect, } from '@leafygreen-ui/hooks'; import { DescendantContextType } from './DescendantsContext'; import { findDescendantIndexWithId } from './utils'; /** @deprecated */ const genId = () => `_${Math.random().toString(36).substr(2, 9)}`; interface UseDescendantReturnObject { ref: RefObject; index: number; id: string; } /** * Registers a component as a descendant of a given context, and calculates its index within the * rendered descendant list. * * Pass `props.index` to explicitly specify the index of the descendant in SSR environments. Doing * so will override the DOM index order. */ export const useDescendant = ( context: DescendantContextType, fwdRef?: RefObject | ForwardedRef, props?: ComponentProps, ): UseDescendantReturnObject => { const ref: React.RefObject = useForwardedRef(fwdRef ?? null, null); const propsWithDefault = props || {}; const { descendants, dispatch } = useContext(context); const id = useRef(genId()); // Use explicit index if provided or find the element with this id in the descendants list const index = useMemo(() => { return ( propsWithDefault?.index ?? findDescendantIndexWithId(descendants, id.current) ); }, [descendants, propsWithDefault.index]); // On render, register the element as a descendant useIsomorphicLayoutEffect(() => { const _id = id.current; // Use ownerDocument so containment checks work when the element is in an iframe. const refExists = ref.current?.ownerDocument?.contains(ref.current) ?? false; if (refExists) { // Register this component as a descendant dispatch({ type: 'register', id: _id, ref, }); } // On un-mount/cleanup remove the element from the descendants list return () => { dispatch({ type: 'remove', id: _id, }); }; }, [dispatch, ref]); // When the props change, update them in the descendants list so the parent has access. // We don't initially register the descendant with props, // so we don't have to remove & re-register it each time the props change useIsomorphicLayoutEffect(() => { dispatch({ type: 'update', id: id.current, props, }); }, [dispatch, props]); return { ref, index, id: id.current, }; };