// packages/compose/src/hooks/use-dialog/index.ts
import { useRef, useEffect, useCallback } from "@wordpress/element";
import { ESCAPE } from "@wordpress/keycodes";
import useConstrainedTabbing from "../use-constrained-tabbing/index.mjs";
import useFocusOnMount from "../use-focus-on-mount/index.mjs";
import useFocusReturn from "../use-focus-return/index.mjs";
import useFocusOutside from "../use-focus-outside/index.mjs";
import useMergeRefs from "../use-merge-refs/index.mjs";
function useDialog(options) {
  const currentOptions = useRef();
  const { constrainTabbing = options.focusOnMount !== false } = options;
  useEffect(() => {
    currentOptions.current = options;
  }, Object.values(options));
  const constrainedTabbingRef = useConstrainedTabbing();
  const focusOnMountRef = useFocusOnMount(options.focusOnMount);
  const focusReturnRef = useFocusReturn();
  const focusOutsideProps = useFocusOutside((event) => {
    if (currentOptions.current?.__unstableOnClose) {
      currentOptions.current.__unstableOnClose("focus-outside", event);
    } else if (currentOptions.current?.onClose) {
      currentOptions.current.onClose();
    }
  });
  const closeOnEscapeRef = useCallback((node) => {
    if (!node) {
      return;
    }
    node.addEventListener("keydown", (event) => {
      if (event.keyCode === ESCAPE && !event.defaultPrevented && currentOptions.current?.onClose) {
        event.preventDefault();
        currentOptions.current.onClose();
      }
    });
  }, []);
  return [
    useMergeRefs([
      constrainTabbing ? constrainedTabbingRef : null,
      options.focusOnMount !== false ? focusReturnRef : null,
      options.focusOnMount !== false ? focusOnMountRef : null,
      closeOnEscapeRef
    ]),
    {
      ...focusOutsideProps,
      tabIndex: -1
    }
  ];
}
var use_dialog_default = useDialog;
export {
  use_dialog_default as default
};
//# sourceMappingURL=index.mjs.map
