var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/hooks/focus/index.ts
var focus_exports = {};
__export(focus_exports, {
  useFocusGuards: () => useFocusGuards,
  useFocusManagement: () => useFocusManagement,
  useFocusOnceVisible: () => useFocusOnceVisible,
  useFocusTrap: () => useFocusTrap,
  useIsMounted: () => useIsMounted
});
module.exports = __toCommonJS(focus_exports);

// src/hooks/focus/useFocusGuards.ts
var import_react = require("react");
var selectorName = "data-hw-focus-guard";
function FocusGuard() {
  const element = document.createElement("div");
  element.setAttribute(selectorName, "");
  element.tabIndex = 0;
  element.style.border = "none";
  element.style.outline = "none";
  element.style.boxShadow = "none";
  element.style.opacity = "0";
  element.style.position = "fixed";
  element.style.pointerEvents = "none";
  return element;
}
var FocusGuardsService = class _FocusGuardsService {
  constructor() {
    this.count = 0;
  }
  static getInstance() {
    if (!_FocusGuardsService.instance) {
      _FocusGuardsService.instance = new _FocusGuardsService();
    }
    return _FocusGuardsService.instance;
  }
  add() {
    const edgeGuards = document.querySelectorAll(`[${selectorName}]`);
    document.body.insertAdjacentElement("afterbegin", edgeGuards[0] ?? FocusGuard());
    document.body.insertAdjacentElement("beforeend", edgeGuards[1] ?? FocusGuard());
    this.count++;
  }
  remove() {
    if (this.count === 1) {
      document.querySelectorAll(`[${selectorName}]`).forEach((node) => node.remove());
    }
    this.count--;
  }
};
var useFocusGuards = () => {
  (0, import_react.useEffect)(() => {
    FocusGuardsService.getInstance().add();
    return () => {
      FocusGuardsService.getInstance().remove();
    };
  }, []);
};

// src/hooks/focus/useFocusManagement.ts
var import_react2 = require("react");
function useFocusManagement() {
  const getFocusableElements = (0, import_react2.useCallback)(() => {
    return Array.from(
      document.querySelectorAll(
        'input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])'
      )
    ).filter(
      (el) => el instanceof HTMLElement && !el.hasAttribute("disabled") && !el.hasAttribute("hidden") && el.tabIndex !== -1
    );
  }, []);
  const getNextFocusElement = (0, import_react2.useCallback)(() => {
    const elements = getFocusableElements();
    if (elements.length === 0) {
      return void 0;
    }
    let nextElement = elements[0];
    if (document.activeElement instanceof HTMLElement) {
      const currentIndex = elements.indexOf(document.activeElement);
      nextElement = elements[(currentIndex + 1) % elements.length];
    }
    return nextElement;
  }, [getFocusableElements]);
  const focusNext = (0, import_react2.useCallback)(() => {
    const nextElement = getNextFocusElement();
    nextElement?.focus();
  }, [getNextFocusElement]);
  const getPreviousFocusElement = (0, import_react2.useCallback)(() => {
    const elements = getFocusableElements();
    if (elements.length === 0) {
      return void 0;
    }
    let previousElement = elements[0];
    if (document.activeElement instanceof HTMLElement) {
      const currentIndex = elements.indexOf(document.activeElement);
      if (currentIndex === 0) {
        previousElement = elements[elements.length - 1];
      } else {
        previousElement = elements[currentIndex - 1];
      }
    }
    return previousElement;
  }, [getFocusableElements]);
  const focusPrevious = (0, import_react2.useCallback)(() => {
    const previousElement = getPreviousFocusElement();
    if (previousElement) previousElement.focus();
  }, [getPreviousFocusElement]);
  return {
    getFocusableElements,
    getNextFocusElement,
    getPreviousFocusElement,
    focusNext,
    focusPrevious
  };
}

// src/hooks/focus/useFocusOnceVisible.ts
var import_react3 = __toESM(require("react"), 1);
var useFocusOnceVisible = (ref, disable = false) => {
  const [hasUsedFocus, setHasUsedFocus] = import_react3.default.useState(false);
  (0, import_react3.useEffect)(() => {
    if (disable || hasUsedFocus) {
      return;
    }
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting && !hasUsedFocus) {
        ref.current?.focus();
        setHasUsedFocus(hasUsedFocus);
      }
    }, {
      threshold: 0.1
    });
    if (ref.current) {
      observer.observe(ref.current);
    }
    return () => observer.disconnect();
  }, [disable, hasUsedFocus, ref]);
};

// src/hooks/focus/useFocusTrap.ts
var import_react5 = require("react");

// src/hooks/focus/useIsMounted.ts
var import_react4 = require("react");
var isClient = typeof window !== "undefined" && typeof document !== "undefined";
var useIsomorphicEffect = isClient ? import_react4.useLayoutEffect : import_react4.useEffect;
var useIsMounted = () => {
  const [isMounted, setIsMounted] = (0, import_react4.useState)(false);
  useIsomorphicEffect(() => {
    setIsMounted(true);
    return () => {
      setIsMounted(false);
    };
  }, []);
  return isMounted;
};

// src/hooks/focus/useFocusTrap.ts
var createFocusGuard = () => {
  const div = document.createElement("div");
  Object.assign(div.style, {
    opacity: "0",
    outline: "none",
    boxShadow: "none",
    position: "fixed",
    pointerEvents: "none",
    touchAction: "none"
  });
  div.tabIndex = 0;
  div.setAttribute("data-hw-focus-guard", "");
  document.body.appendChild(div);
  return div;
};
function getContainedFocusableElements(element) {
  return element?.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
}
var FocusTrapService = class {
  constructor() {
    // The last entry is always the active one
    this.listeners = [];
    this.onFocusIn = (event) => {
      const active = this.getActive();
      if (!active || !active.container.current) return;
      const { container } = active;
      if (!container.current.contains(event.target)) {
        this.focusElement();
      }
    };
  }
  getActive() {
    if (this.listeners.length === 0) return void 0;
    return this.listeners[this.listeners.length - 1];
  }
  focusElement() {
    const active = this.getActive();
    if (!active) return;
    const { container, initialFocusElement } = active;
    const containerElement = container.current;
    if (initialFocusElement?.current) {
      initialFocusElement.current.focus();
    } else {
      const elements = getContainedFocusableElements(containerElement);
      if (elements && elements.length > 0) {
        const first = elements.item(0);
        first.focus();
      } else {
        containerElement.focus();
      }
    }
  }
  removeGuards() {
    document.querySelectorAll("[data-hw-focus-guard]").forEach((node) => node.remove());
  }
  addGuards() {
    document.body.insertAdjacentElement("afterbegin", createFocusGuard());
    document.body.insertAdjacentElement("beforeend", createFocusGuard());
  }
  activate() {
    document.addEventListener("focusin", this.onFocusIn);
    this.addGuards();
  }
  deactivate() {
    document.removeEventListener("focusin", this.onFocusIn);
    this.removeGuards();
  }
  register(listener) {
    this.listeners.push(listener);
    if (this.listeners.length === 1) {
      this.activate();
    }
    const active = listener;
    this.listeners.forEach((listener2) => {
      const { focus, pause } = listener2;
      if (listener2 === active) {
        focus();
      } else {
        pause();
      }
    });
  }
  unregister(id) {
    const index = this.listeners.findIndex((trap) => trap.id === id);
    if (index !== -1) {
      const isActive = index === this.listeners.length - 1;
      const listener = this.listeners[index];
      this.listeners = this.listeners.filter((listener2) => listener2.id !== id);
      if (isActive) {
        this.deactivate();
        listener.focusLast();
        const active = this.getActive();
        this.listeners.forEach((listener2) => {
          const { pause, unpause } = listener2;
          if (listener2 === active) {
            unpause();
          } else {
            pause();
          }
        });
        if (this.listeners.length > 0) {
          this.activate();
        }
      }
    } else {
      console.warn(`Unable to unregister id ${id}: not found`);
    }
  }
};
var service = new FocusTrapService();
var useFocusTrap = ({
  container,
  active = true,
  initialFocus,
  focusFirst = true
}) => {
  const lastFocusRef = (0, import_react5.useRef)(null);
  const [paused, setPaused] = (0, import_react5.useState)(false);
  const isMounted = useIsMounted();
  const id = (0, import_react5.useId)();
  const focusElement = (0, import_react5.useCallback)(() => {
    const containerElement = container.current;
    if (initialFocus?.current) {
      initialFocus.current.focus();
    } else {
      const elements = getContainedFocusableElements(containerElement);
      if (elements && elements.length > 0) {
        const first = elements.item(0);
        first.focus();
      } else {
        containerElement.focus();
      }
    }
  }, [container, initialFocus]);
  (0, import_react5.useEffect)(() => {
    if (active && isMounted) {
      let pause = function() {
        setPaused(true);
      }, unpause = function() {
        setPaused(false);
        if (!container.current.contains(document.activeElement)) {
          focusElement();
        }
      }, focus = function() {
        focusElement();
        setPaused(false);
      }, focusLast = function() {
        lastFocusRef.current?.focus();
      };
      if (!lastFocusRef.current) {
        lastFocusRef.current = document.activeElement;
      }
      service.register({ id, pause, focus, focusLast, unpause, container, initialFocusElement: initialFocus });
      return () => {
        service.unregister(id);
        lastFocusRef.current = void 0;
      };
    }
  }, [active, container, focusElement, id, initialFocus, isMounted]);
  (0, import_react5.useEffect)(() => {
    if (active && !paused && isMounted) {
      let onKeyDown = function(event) {
        const key = event.key;
        const elements = getContainedFocusableElements(containerElement);
        const active2 = document.activeElement;
        const index = [...elements].findIndex((value) => value === active2);
        if (index === -1 || event.altKey || event.ctrlKey || event.metaKey) {
          return;
        }
        if (key === "Tab") {
          const next = event.shiftKey ? -1 : 1;
          const nextIndex = (index + next + elements.length) % elements.length;
          const nextElement = elements[nextIndex];
          nextElement.focus();
          event.preventDefault();
        }
      };
      const containerElement = container.current;
      containerElement.addEventListener("keydown", onKeyDown);
      return () => {
        containerElement.removeEventListener("keydown", onKeyDown);
      };
    }
  }, [active, paused, isMounted, container, initialFocus, focusFirst, focusElement]);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useFocusGuards,
  useFocusManagement,
  useFocusOnceVisible,
  useFocusTrap,
  useIsMounted
});
//# sourceMappingURL=index.cjs.map