import B from "../../../@babel/runtime/helpers/esm/slicedToArray.mjs";
import c from "../../../rc-util/es/KeyCode.mjs";
import I from "../../../rc-util/es/raf.mjs";
import { useState as R, useRef as d, useEffect as m } from "react";
import { addGlobalMouseDownEvent as P, getTargetFromEvent as x } from "../utils/uiUtil.mjs";
function z(t) {
  var n = t.open, F = t.value, l = t.isClickOutside, a = t.triggerOpen, w = t.forwardKeyDown, O = t.onKeyDown, D = t.blurToCancel, b = t.changeOnBlur, g = t.onSubmit, h = t.onCancel, y = t.onFocus, v = t.onBlur, k = R(!1), E = B(k, 2), f = E[0], u = E[1], M = R(!1), C = B(M, 2), K = C[0], S = C[1], s = d(!1), p = d(!1), T = d(!1), A = {
    onMouseDown: function() {
      u(!0), a(!0);
    },
    onKeyDown: function(e) {
      var r = function() {
        T.current = !0;
      };
      if (O(e, r), !T.current) {
        switch (e.which) {
          case c.ENTER: {
            n ? g() !== !1 && u(!0) : a(!0), e.preventDefault();
            return;
          }
          case c.TAB: {
            f && n && !e.shiftKey ? (u(!1), e.preventDefault()) : !f && n && !w(e) && e.shiftKey && (u(!0), e.preventDefault());
            return;
          }
          case c.ESC: {
            u(!0), h();
            return;
          }
        }
        !n && ![c.SHIFT].includes(e.which) ? a(!0) : f || w(e);
      }
    },
    onFocus: function(e) {
      u(!0), S(!0), y && y(e);
    },
    onBlur: function(e) {
      if (s.current || !l(document.activeElement)) {
        s.current = !1;
        return;
      }
      D ? setTimeout(function() {
        for (var r = document, o = r.activeElement; o && o.shadowRoot; )
          o = o.shadowRoot.activeElement;
        l(o) && h();
      }, 0) : n && (a(!1), p.current && g()), S(!1), v == null || v(e);
    }
  };
  return m(function() {
    p.current = !1;
  }, [n]), m(function() {
    p.current = !0;
  }, [F]), m(function() {
    return P(function(i) {
      var e = x(i), r = l(e);
      n && (r ? !b && !D && (!K || r) && a(!1) : (s.current = !0, I(function() {
        s.current = !1;
      })));
    });
  }), [A, {
    focused: K,
    typing: f
  }];
}
export {
  z as default
};
