"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.InputSpotlightDecorator = void 0;
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _keymap = require("@enact/core/keymap");
var _spotlight = require("@enact/spotlight");
var _Pause = _interopRequireDefault(require("@enact/spotlight/Pause"));
var _Spottable = _interopRequireDefault(require("@enact/spotlight/Spottable"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _pointer = require("./pointer");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var isBubbling = function isBubbling(ev) {
  return ev.currentTarget !== ev.target;
};

// A regex to check for input types that allow selectionStart
var SELECTABLE_TYPES = /text|password|search|tel|url/;
var isSelectionAtLocation = function isSelectionAtLocation(target, location) {
  if (SELECTABLE_TYPES.test(target.type)) {
    return target.selectionStart === location;
  } else {
    return true;
  }
};
var handleKeyDown = (0, _handle.handle)((0, _handle.forwardWithPrevent)('onKeyDown'), (0, _handle.call)('onKeyDown'));

/**
 * Default config for {@link agate/Input.InputSpotlightDecorator|InputSpotlightDecorator}.
 *
 * @memberof agate/Input/InputSpotlightDecorator.InputSpotlightDecorator
 * @hocconfig
 */
var defaultConfig = {
  /**
   * Suppress the pointer lock behavior of agate input
   *
   * @type {Boolean}
   * @default false
   * @memberof agate/Input/InputSpotlightDecorator.InputSpotlightDecorator.defaultConfig
  */
  noLockPointer: false
};

/**
 * A higher-order component that manages the
 * spotlight behavior for an {@link agate/Input.Input}
 *
 * @class InputSpotlightDecorator
 * @hoc
 * @memberof agate/Input/InputSpotlightDecorator
 * @private
 */
var InputSpotlightDecorator = exports.InputSpotlightDecorator = (0, _hoc["default"])(defaultConfig, function (config, Wrapped) {
  var _Class;
  var noLockPointer = config.noLockPointer;
  var Component = (0, _Spottable["default"])({
    emulateMouse: false
  }, Wrapped);
  var forwardBlur = (0, _handle.forward)('onBlur');
  var forwardMouseDown = (0, _handle.forward)('onMouseDown');
  var forwardFocus = (0, _handle.forward)('onFocus');
  var forwardKeyUp = (0, _handle.forward)('onKeyUp');
  return _Class = /*#__PURE__*/function (_ReactComponent) {
    function _Class(props) {
      var _this;
      _classCallCheck(this, _Class);
      _this = _callSuper(this, _Class, [props]);
      _this.updateFocus = function (prevState) {
        if (_this.state.node) {
          if (_spotlight.Spotlight.getCurrent() !== _this.state.node) {
            _this.state.node.focus();
          }
        }
        var focusChanged = _this.state.focused !== prevState.focused;
        if (focusChanged) {
          if (_this.state.focused === 'input') {
            (0, _handle.forward)('onActivate', {
              type: 'onActivate'
            }, _this.props);
            if (!noLockPointer) {
              (0, _pointer.lockPointer)(_this.state.node);
            }
            _this.paused.pause();
          } else if (prevState.focused === 'input') {
            (0, _handle.forward)('onDeactivate', {
              type: 'onDeactivate'
            }, _this.props);
            if (!noLockPointer) {
              (0, _pointer.releasePointer)(prevState.node);
            }
            _this.paused.resume();
          }
        }
      };
      _this.focus = function (focused, node) {
        _this.setState({
          focused: focused,
          node: node
        });
      };
      _this.blur = function () {
        _this.setState(function (state) {
          return state.focused || state.node ? {
            focused: null,
            node: null
          } : null;
        });
      };
      _this.focusDecorator = function (decorator) {
        _this.focus('decorator', decorator);
      };
      _this.focusInput = function (decorator) {
        _this.focus('input', decorator.querySelector('input'));
      };
      _this.onBlur = function (ev) {
        if (!_this.props.autoFocus) {
          if (isBubbling(ev)) {
            if (_spotlight.Spotlight.getPointerMode()) {
              _this.blur();
              forwardBlur(ev, _this.props);
            } else {
              _this.focusDecorator(ev.currentTarget);
              ev.stopPropagation();
            }
          } else if (!ev.currentTarget.contains(ev.relatedTarget)) {
            // Blurring decorator but not focusing input
            forwardBlur(ev, _this.props);
            _this.blur();
          }
        } else if (isBubbling(ev)) {
          if (_this.state.focused === 'input' && _this.state.node === ev.target && ev.currentTarget !== ev.relatedTarget) {
            _this.blur();
            forwardBlur(ev, _this.props);
          } else {
            _this.focusDecorator(ev.currentTarget);
            ev.stopPropagation();
            _this.blur();
          }
        }
      };
      _this.onMouseDown = function (ev) {
        var _this$props = _this.props,
          disabled = _this$props.disabled,
          spotlightDisabled = _this$props.spotlightDisabled;
        _this.setDownTarget(ev);
        // focus the <input> whenever clicking on any part of the component to ensure both that
        // the <input> has focus and Spotlight is paused.
        if (!disabled && !spotlightDisabled) {
          _this.focusInput(ev.currentTarget);
          if (ev.target.tagName !== 'INPUT') {
            ev.preventDefault();
          }
        }
        forwardMouseDown(ev, _this.props);
      };
      _this.onFocus = function (ev) {
        forwardFocus(ev, _this.props);

        // when in autoFocus mode, focusing the decorator directly will cause it to
        // forward the focus onto the <input>
        if (!isBubbling(ev) && _this.props.autoFocus && _this.state.focused === null && !_spotlight.Spotlight.getPointerMode()) {
          _this.focusInput(ev.currentTarget);
          ev.stopPropagation();
        }
      };
      _this.onKeyUp = function (ev) {
        var dismissOnEnter = _this.props.dismissOnEnter;
        var currentTarget = ev.currentTarget,
          keyCode = ev.keyCode,
          target = ev.target;

        // verify that we have a matching pair of key down/up events to avoid adjusting focus
        // when the component received focus mid-press
        if (target === _this.downTarget) {
          _this.downTarget = null;
          if (!_this.props.disabled) {
            if (_this.state.focused === 'input' && dismissOnEnter && (0, _keymap.is)('enter', keyCode)) {
              _this.focusDecorator(currentTarget);
              // prevent Enter onKeyPress which triggers an onMouseDown via Spotlight
              ev.preventDefault();
            } else if (_this.state.focused !== 'input' && (0, _keymap.is)('enter', keyCode)) {
              _this.focusInput(currentTarget);
            }
          }
        }
        forwardKeyUp(ev, _this.props);
      };
      _this.state = {
        focused: null,
        node: null
      };
      _this.paused = new _Pause["default"]('InputSpotlightDecorator');
      _this.handleKeyDown = handleKeyDown.bind(_this);
      return _this;
    }
    _inherits(_Class, _ReactComponent);
    return _createClass(_Class, [{
      key: "componentDidUpdate",
      value: function componentDidUpdate(_, prevState) {
        this.updateFocus(prevState);
      }
    }, {
      key: "componentWillUnmount",
      value: function componentWillUnmount() {
        this.paused.resume();
        if (this.state.focused === 'input') {
          var onSpotlightDisappear = this.props.onSpotlightDisappear;
          if (onSpotlightDisappear) {
            onSpotlightDisappear();
          }
          if (!noLockPointer) {
            (0, _pointer.releasePointer)(this.state.node);
          }
        }
      }
    }, {
      key: "onKeyDown",
      value: function onKeyDown(ev) {
        var currentTarget = ev.currentTarget,
          keyCode = ev.keyCode,
          target = ev.target;

        // cache the target if this is the first keyDown event to ensure the component had focus
        // when the key interaction started
        this.setDownTarget(ev);
        if (this.state.focused === 'input') {
          var isDown = (0, _keymap.is)('down', keyCode);
          var isLeft = (0, _keymap.is)('left', keyCode);
          var isRight = (0, _keymap.is)('right', keyCode);
          var isUp = (0, _keymap.is)('up', keyCode);

          // move spotlight
          var shouldSpotlightMove =
          // on left + at beginning of selection
          isLeft && isSelectionAtLocation(target, 0) ||
          // on right + at end of selection (note: fails on non-selectable types usually)
          isRight && isSelectionAtLocation(target, target.value.length) ||
          // on up
          isUp ||
          // on down
          isDown;

          // prevent modifying the value via 5-way for numeric fields
          if ((isUp || isDown) && target.type === 'number') {
            ev.preventDefault();
          }
          if (shouldSpotlightMove) {
            var direction = (0, _spotlight.getDirection)(keyCode);
            var getPointerMode = _spotlight.Spotlight.getPointerMode,
              move = _spotlight.Spotlight.move,
              setPointerMode = _spotlight.Spotlight.setPointerMode;
            if (getPointerMode()) {
              setPointerMode(false);
            }
            (0, _handle.stopImmediate)(ev);
            this.paused.resume();

            // Move spotlight in the keypress direction
            if (move(direction)) {
              // if successful, reset the internal state
              this.blur();
            } else {
              // if there is no other spottable elements, focus `InputDecorator` instead
              this.focusDecorator(currentTarget);
            }
          } else if (isLeft || isRight) {
            // prevent 5-way nav for left/right keys within the <input>
            (0, _handle.stopImmediate)(ev);
          }
        }
      }
    }, {
      key: "setDownTarget",
      value: function setDownTarget(ev) {
        var repeat = ev.repeat,
          target = ev.target;
        if (!repeat) {
          this.downTarget = target;
        }
      }
    }, {
      key: "render",
      value: function render() {
        var props = Object.assign({}, this.props);
        delete props.autoFocus;
        delete props.onActivate;
        delete props.onDeactivate;
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, _objectSpread(_objectSpread({}, props), {}, {
          focused: this.state.focused === 'input',
          onBlur: this.onBlur,
          onMouseDown: this.onMouseDown,
          onFocus: this.onFocus,
          onKeyDown: this.handleKeyDown,
          onKeyUp: this.onKeyUp
        }));
      }
    }]);
  }(_react.Component), _Class.displayName = 'InputSpotlightDecorator', _Class.propTypes = /** @lends agate/Input/InputSpotlightDecorator.InputSpotlightDecorator.prototype */{
    /**
     * Focuses the <input> when the decorator is focused via 5-way.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    autoFocus: _propTypes["default"].bool,
    /**
     * Applies a disabled style and the control becomes non-interactive.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    disabled: _propTypes["default"].bool,
    /**
     * Blurs the input when the "enter" key is pressed.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    dismissOnEnter: _propTypes["default"].bool,
    /**
     * Called when the internal <input> is focused.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onActivate: _propTypes["default"].func,
    /**
     * Called when the internal <input> loses focus.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onDeactivate: _propTypes["default"].func,
    /**
     * Called when the component is removed while retaining focus.
     *
     * @type {Function}
     * @param {Object} event
     * @public
     */
    onSpotlightDisappear: _propTypes["default"].func,
    /**
     * Disables spotlight navigation into the component.
     *
     * @type {Boolean}
     * @default false
     * @public
     */
    spotlightDisabled: _propTypes["default"].bool
  }, _Class;
});
var _default = exports["default"] = InputSpotlightDecorator;