"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useScrollButtons = exports["default"] = void 0;
var _handle = require("@enact/core/handle");
var _target = require("@enact/spotlight/src/target");
var _keymap = require("@enact/core/keymap");
var _spotlight = _interopRequireWildcard(require("@enact/spotlight"));
var _utilEvent = _interopRequireDefault(require("@enact/ui/useScroll/utilEvent"));
var _react = require("react");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
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 _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 _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
var nop = function nop() {},
  prepareButton = function prepareButton(isPrev) {
    return function (isVertical) {
      var direction;
      if (isVertical) {
        direction = isPrev ? 'up' : 'down';
      } else {
        direction = isPrev ? 'left' : 'right';
      }
      return 'arrowlarge' + direction;
    };
  },
  preparePrevButton = prepareButton(true),
  prepareNextButton = prepareButton(false),
  isPageUp = (0, _keymap.is)('pageUp'),
  isPageDown = (0, _keymap.is)('pageDown'),
  consumeEvent = function consumeEvent(ev) {
    ev.preventDefault();
    ev.stopPropagation();
  };

/**
 * A custom hook that returns Agate-themed scroll buttons behavior. It is used in {@link agate/useScroll.Scrollbar|Scrollbar}.
 *
 * @function useScrollButtons
 * @memberof agate/useScroll
 * @ui
 * @private
 */
var useScrollButtons = exports.useScrollButtons = function useScrollButtons(props) {
  var _useState = (0, _react.useState)(true),
    _useState2 = _slicedToArray(_useState, 2),
    prevButtonDisabled = _useState2[0],
    setPrevButtonDisabled = _useState2[1];
  var _useState3 = (0, _react.useState)(true),
    _useState4 = _slicedToArray(_useState3, 2),
    nextButtonDisabled = _useState4[0],
    setNextButtonDisabled = _useState4[1];
  var nextButtonRef = (0, _react.useRef)();
  var prevButtonRef = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    var nextRef = nextButtonRef.current;
    var prevRef = prevButtonRef.current;
    (0, _utilEvent["default"])('keydown').addEventListener(nextRef, onKeyDownNext);
    (0, _utilEvent["default"])('keydown').addEventListener(prevRef, onKeyDownPrev);
    return function () {
      (0, _utilEvent["default"])('keydown').removeEventListener(nextRef, onKeyDownNext);
      (0, _utilEvent["default"])('keydown').removeEventListener(prevRef, onKeyDownPrev);
    };
  });
  var updateButtons = function updateButtons(bounds) {
    var vertical = props.vertical,
      currentPos = vertical ? bounds.scrollTop : bounds.scrollLeft,
      maxPos = vertical ? bounds.maxTop : bounds.maxLeft,
      shouldDisablePrevButton = currentPos <= 0,
      shouldDisableNextButton = maxPos - currentPos <= 1,
      updatePrevButton = prevButtonDisabled !== shouldDisablePrevButton,
      updateNextButton = nextButtonDisabled !== shouldDisableNextButton;
    if (updatePrevButton) {
      setPrevButtonDisabled(shouldDisablePrevButton);
    }
    if (updateNextButton) {
      setNextButtonDisabled(shouldDisableNextButton);
    }
  };
  function isOneOfScrollButtonsFocused() {
    var current = _spotlight["default"].getCurrent();
    return current === prevButtonRef.current || current === nextButtonRef.current;
  }
  function onClickPrev(ev) {
    var _props$onPrevScroll = props.onPrevScroll,
      onPrevScroll = _props$onPrevScroll === void 0 ? nop : _props$onPrevScroll,
      vertical = props.vertical;
    onPrevScroll(_objectSpread(_objectSpread({}, ev), {}, {
      isPreviousScrollButton: true,
      isVerticalScrollBar: vertical
    }));
  }
  function onClickNext(ev) {
    var _props$onNextScroll = props.onNextScroll,
      onNextScroll = _props$onNextScroll === void 0 ? nop : _props$onNextScroll,
      vertical = props.vertical;
    onNextScroll(_objectSpread(_objectSpread({}, ev), {}, {
      isPreviousScrollButton: false,
      isVerticalScrollBar: vertical
    }));
  }
  function focusOnButton(isPrev) {
    _spotlight["default"].focus(isPrev ? prevButtonRef.current : nextButtonRef.current);
  }
  function focusOnOppositeScrollButton(ev, direction) {
    var buttonNode = ev.target === nextButtonRef.current ? prevButtonRef.current : nextButtonRef.current;
    if (!_spotlight["default"].focus(buttonNode)) {
      _spotlight["default"].move(direction);
    }
  }
  function onKeyDownButton(ev, position) {
    var focusableScrollButtons = props.focusableScrollButtons,
      vertical = props.vertical,
      preventBubblingOnKeyDown = props.preventBubblingOnKeyDown,
      keyCode = ev.keyCode,
      direction = (0, _spotlight.getDirection)(ev.keyCode),
      preventBubbling = preventBubblingOnKeyDown === 'programmatic',
      isNextButton = position === 'next',
      isPrevButton = position === 'prev',
      nextButton = {
        disabled: nextButtonDisabled,
        ref: nextButtonRef.current,
        click: onClickNext
      },
      prevButton = {
        disabled: prevButtonDisabled,
        ref: prevButtonRef.current,
        click: onClickPrev
      },
      currentButton = isPrevButton ? prevButton : nextButton,
      oppositeButton = isPrevButton ? nextButton : prevButton;
    if (isPageDown(keyCode) || isPageUp(keyCode)) {
      if (!vertical) {
        // should not call stopPropagation() here
        ev.preventDefault();
        return;
      }
      if (isPrevButton && isPageDown(keyCode) || isNextButton && isPageUp(keyCode)) {
        if (focusableScrollButtons && !_spotlight["default"].getPointerMode()) {
          consumeEvent(ev);
          _spotlight["default"].setPointerMode(false);
          _spotlight["default"].focus(oppositeButton.ref);
        } else if (!oppositeButton.disabled) {
          consumeEvent(ev);
          oppositeButton.click(ev);
        }
      } else if (!currentButton.disabled) {
        consumeEvent(ev);
        currentButton.click(ev);
      }
    } else if (direction) {
      var rtl = props.rtl,
        isDown = direction === 'down',
        isLeftMovement = direction === (rtl ? 'right' : 'left'),
        isRightMovement = direction === (rtl ? 'left' : 'right'),
        isUp = direction === 'up',
        fromNextToPrev = vertical ? isUp : isLeftMovement,
        fromPrevToNext = vertical ? isDown : isRightMovement;
      _spotlight["default"].setPointerMode(false);
      if (isNextButton && fromNextToPrev || isPrevButton && fromPrevToNext) {
        if (focusableScrollButtons) {
          consumeEvent(ev);
          focusOnOppositeScrollButton(ev, direction);
          if (!preventBubbling) {
            (0, _handle.forward)('onKeyDownButton', ev, props);
          }
        }
      } else {
        var
          // If it is vertical Scroller, move focus to the left for ltr or to the right for rtl
          // If is is horizontal Scroller, move focus to the up
          directionToContent = !vertical && 'up' || rtl && 'right' || 'left',
          isLeavingDown = vertical && isNextButton && isDown,
          isLeavingUp = vertical && isPrevButton && isUp,
          isLeavingLeft = !vertical && isPrevButton && isLeftMovement,
          isLeavingRight = !vertical && isNextButton && isRightMovement,
          isDirectionToLeave = vertical && isRightMovement || isLeavingUp || isLeavingDown || !vertical && isDown || isLeavingLeft || isLeavingRight;
        if (isDirectionToLeave) {
          if (!focusableScrollButtons && !(0, _target.getTargetByDirectionFromElement)(direction, ev.target)) {
            if (preventBubbling && isLeavingDown || isLeavingUp || isLeavingLeft || isLeavingRight) {
              consumeEvent(ev);
            }
            // move focus into contents and allow bubbling
            _spotlight["default"].move(directionToContent);
          }
        } else if (preventBubbling) {
          // move focus directly to stop bubbling
          consumeEvent(ev);
          _spotlight["default"].move(direction);
        }
      }
    }
  }
  function onKeyDownPrev(ev) {
    onKeyDownButton(ev, 'prev');
  }
  function onKeyDownNext(ev) {
    onKeyDownButton(ev, 'next');
  }
  return {
    focusOnButton: focusOnButton,
    isOneOfScrollButtonsFocused: isOneOfScrollButtonsFocused,
    nextButtonDisabled: nextButtonDisabled,
    nextButtonRef: nextButtonRef,
    nextIcon: prepareNextButton(props.vertical),
    onClickNext: onClickNext,
    onClickPrev: onClickPrev,
    prevButtonDisabled: prevButtonDisabled,
    prevButtonRef: prevButtonRef,
    prevIcon: preparePrevButton(props.vertical),
    updateButtons: updateButtons
  };
};
var _default = exports["default"] = useScrollButtons;