import { useRef, useState, useEffect, useCallback } from 'react';

const useOpenCloseTransitionStates = (openProp, options = {
  durationMs: 0
}) => {
  const {
    onOpenAnimationStart,
    onCloseAnimationStart,
    onOpenAnimationComplete,
    onCloseAnimationComplete,
    durationMs
  } = options;
  const prevOpenProp = useRef(openProp);
  const [state, setState] = useState(
    openProp ? "open" : "closed"
  );
  useEffect(() => {
    if (prevOpenProp.current && !openProp) {
      setState("closing");
    } else if (!prevOpenProp.current && openProp) {
      setState("opening");
    } else {
      setState(openProp ? "opening" : "closed");
    }
    prevOpenProp.current = openProp;
  }, [openProp]);
  useEffect(() => {
    if (!durationMs) return;
    if (state === "open" || state === "closed") return;
    if (state === "opening") {
      onOpenAnimationStart?.();
    } else if (state === "closing") {
      onCloseAnimationStart?.();
    }
    const d = typeof durationMs === "function" ? durationMs() : durationMs;
    const timeout = setTimeout(() => {
      if (state === "opening") {
        setState("open");
        onOpenAnimationComplete?.();
      } else if (state === "closing") {
        setState("closed");
        onCloseAnimationComplete?.();
      }
    }, d);
    return () => {
      clearTimeout(timeout);
    };
  }, [
    state,
    onOpenAnimationComplete,
    onCloseAnimationComplete,
    onOpenAnimationStart,
    onCloseAnimationStart,
    durationMs
  ]);
  const beginClosing = useCallback(() => {
    setState("closing");
  }, []);
  return {
    state,
    beginClosing,
    isOpenOrOpening: state === "open" || state === "opening",
    isClosedOrClosing: state === "closed" || state === "closing"
  };
};

export { useOpenCloseTransitionStates as u };
//# sourceMappingURL=useOpenCloseTransitionStates-CiTYrLGi.js.map
