"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");

var _reactDom = _interopRequireDefault(require("react-dom"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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 [Scrollbar]{@link agate/useScroll.Scrollbar}.
 *
 * @function useScrollButtons
 * @memberof agate/useScroll
 * @ui
 * @private
 */


var 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 = /*#__PURE__*/(0, _react.createRef)();
  var prevButtonRef = /*#__PURE__*/(0, _react.createRef)();
  (0, _react.useEffect)(function () {
    (0, _utilEvent["default"])('keydown').addEventListener(nextButtonRef, onKeyDownNext);
    (0, _utilEvent["default"])('keydown').addEventListener(prevButtonRef, onKeyDownPrev);
    return function () {
      (0, _utilEvent["default"])('keydown').removeEventListener(nextButtonRef, onKeyDownNext);
      (0, _utilEvent["default"])('keydown').removeEventListener(prevButtonRef, onKeyDownPrev);
    };
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  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(_reactDom["default"].findDOMNode(oppositeButton.ref)); // eslint-disable-line react/no-find-dom-node

        } 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
  };
};

exports.useScrollButtons = useScrollButtons;
var _default = useScrollButtons;
exports["default"] = _default;