"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isSelectedValid = exports["default"] = exports.DropdownListBase = exports.DropdownList = void 0;
var _handle = require("@enact/core/handle");
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _kind = _interopRequireDefault(require("@enact/core/kind"));
var _propTypes = _interopRequireDefault(require("@enact/core/internal/prop-types"));
var _WithRef = require("@enact/core/internal/WithRef");
var _spotlight = _interopRequireDefault(require("@enact/spotlight"));
var _resolution = _interopRequireDefault(require("@enact/ui/resolution"));
var _propTypes2 = _interopRequireDefault(require("prop-types"));
var _compose = _interopRequireDefault(require("ramda/src/compose"));
var _react = require("react");
var _util = require("../internal/util");
var _Item = _interopRequireDefault(require("../Item"));
var _RadioItem = _interopRequireDefault(require("../RadioItem"));
var _Skinnable = _interopRequireDefault(require("../Skinnable"));
var _VirtualList = _interopRequireDefault(require("../VirtualList"));
var _DropdownModule = _interopRequireDefault(require("./Dropdown.module.css"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["index"],
  _excluded2 = ["key"],
  _excluded3 = ["dataSize", "itemRenderer", "itemSize", "scrollTo"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": 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 _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); }
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 _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
var isSelectedValid = exports.isSelectedValid = function isSelectedValid(_ref) {
  var children = _ref.children,
    selected = _ref.selected;
  return Array.isArray(children) && children[selected] != null;
};
var getKey = function getKey(_ref2) {
  var children = _ref2.children,
    selected = _ref2.selected;
  if (isSelectedValid({
    children: children,
    selected: selected
  })) {
    return children[selected].key;
  }
};
var indexFromKey = function indexFromKey(children, key) {
  var index = -1;
  if (children) {
    index = children.findIndex(function (child) {
      return child.key === key;
    });
  }
  return index;
};

/**
 * A stateless DropdownList component.
 *
 * @class DropdownListBase
 * @memberof agate/Dropdown
 * @ui
 * @public
 */
var DropdownListBase = exports.DropdownListBase = (0, _kind["default"])({
  name: 'DropdownListBase',
  propTypes: /** @lends agate/Dropdown.DropdownListBase.prototype */{
    /**
     * The selections for Dropdown
     *
     * @type {String[]|Array.<{key: (Number|String), children: (String|Component)}>}
     */
    children: _propTypes2["default"].oneOfType([_propTypes2["default"].arrayOf(_propTypes2["default"].string), _propTypes2["default"].arrayOf(_propTypes2["default"].shape({
      children: _propTypes["default"].renderable.isRequired,
      key: _propTypes2["default"].oneOfType([_propTypes2["default"].string, _propTypes2["default"].number]).isRequired
    }))]),
    /**
     * Placement of the Dropdown List.
     *
     * @type {String}
     */
    direction: _propTypes2["default"].string,
    /**
     * Called when an item is selected.
     *
     * @type {Function}
     */
    onSelect: _propTypes2["default"].func,
    /**
     * Callback function that will receive the scroller's scrollTo() method
     *
     * @type {Function}
     */
    scrollTo: _propTypes2["default"].func,
    /**
     * Index of the selected item.
     *
     * @type {Number}
     */
    selected: _propTypes2["default"].number,
    /**
     * The current skin for this component.
     *
     * @type {String}
     * @public
     */
    skin: _propTypes2["default"].string,
    /**
     * The width of DropdownList.
     *
     * @type {('smallest'|'small'|'medium'|'large'|'x-large'|'huge')}
     */
    width: _propTypes2["default"].oneOf(['smallest', 'small', 'medium', 'large', 'x-large', 'huge'])
  },
  defaultProps: {
    direction: 'below center'
  },
  styles: {
    css: _DropdownModule["default"],
    className: 'dropdownList'
  },
  handlers: {
    itemRenderer: function itemRenderer(_ref3, props) {
      var index = _ref3.index,
        rest = _objectWithoutProperties(_ref3, _excluded);
      var children = props.children,
        selected = props.selected,
        skin = props.skin;
      var isSelected = index === selected;
      var child = children[index];
      if (typeof child === 'string') {
        child = {
          children: child
        };
      }
      var data = child.children;
      var ItemComponent = skin === 'silicon' ? _RadioItem["default"] : _Item["default"];
      var itemProps = skin === 'silicon' ? {
        className: _DropdownModule["default"].dropDownListItem,
        css: _DropdownModule["default"],
        selected: isSelected,
        size: 'small'
      } : {
        css: _DropdownModule["default"],
        selected: isSelected
      };
      var _child = _objectSpread({}, child),
        key = _child.key,
        restChild = _objectWithoutProperties(_child, _excluded2);
      return /*#__PURE__*/(0, _react.createElement)(ItemComponent, _objectSpread(_objectSpread(_objectSpread({}, rest), restChild), {}, {
        "data-selected": isSelected,
        key: key
        // eslint-disable-next-line react/jsx-no-bind
        ,
        onClick: function onClick() {
          return (0, _handle.forward)('onSelect', {
            data: data,
            selected: index
          }, props);
        }
      }, itemProps));
    }
  },
  computed: {
    className: function className(_ref4) {
      var direction = _ref4.direction,
        skin = _ref4.skin,
        width = _ref4.width,
        styler = _ref4.styler;
      return styler.append(direction.substr(0, direction.indexOf(' ')), width, {
        dropdownListWithCustomizedScroller: skin === 'silicon'
      });
    },
    dataSize: function dataSize(_ref5) {
      var children = _ref5.children;
      return children ? children.length : 0;
    },
    // Note: Retaining this in case we need to support different item sizes for large text mode:
    itemSize: function itemSize(_ref6) {
      var skin = _ref6.skin;
      return skin === 'gallium' ? _resolution["default"].scale(90) : _resolution["default"].scale(60);
    }
  },
  render: function render(_ref7) {
    var dataSize = _ref7.dataSize,
      itemRenderer = _ref7.itemRenderer,
      itemSize = _ref7.itemSize,
      scrollTo = _ref7.scrollTo,
      rest = _objectWithoutProperties(_ref7, _excluded3);
    delete rest.width;
    delete rest.direction;
    delete rest.skin;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_VirtualList["default"], _objectSpread(_objectSpread({}, rest), {}, {
      cbScrollTo: scrollTo,
      dataSize: dataSize,
      focusableScrollbar: true,
      itemRenderer: itemRenderer,
      itemSize: itemSize
    }));
  }
});
var ReadyState = {
  // Initial state. Scrolling and focusing pending
  INIT: 0,
  // Scroll requested
  SCROLLED: 1,
  // Focus completed or not required
  DONE: 2
};

/**
 * Adds spotlight behaviors to DropdownList.
 *
 * @class DropdownListSpotlightDecorator
 * @hoc
 * @memberof agate/Dropdown
 * @private
 */
var DropdownListSpotlightDecorator = (0, _hoc["default"])(function (config, Wrapped) {
  var _Class;
  var WrappedWithRef = (0, _WithRef.WithRef)(Wrapped);
  return _Class = /*#__PURE__*/function (_Component) {
    function _Class(props) {
      var _this;
      _classCallCheck(this, _Class);
      _this = _callSuper(this, _Class, [props]);
      _this.setScrollTo = function (scrollTo) {
        _this.scrollTo = scrollTo;
      };
      _this.scrollIntoView = function () {
        var selected = _this.props.selected;
        if (_this.state.prevFocused == null && !isSelectedValid(_this.props)) {
          selected = 0;
        } else if (_this.state.prevFocused != null) {
          selected = _this.state.prevFocused;
        }
        _this.scrollTo({
          animate: false,
          focus: true,
          index: selected
        });
        _this.setState({
          ready: ReadyState.SCROLLED
        });
      };
      _this.handleFocus = function (ev) {
        var _this$clientSiblingRe;
        var current = ev.target;
        var dropdownListNode = (_this$clientSiblingRe = _this.clientSiblingRef) === null || _this$clientSiblingRe === void 0 ? void 0 : _this$clientSiblingRe.current;
        if (_this.state.ready === ReadyState.DONE && !_spotlight["default"].getPointerMode() && current.dataset['index'] != null && dropdownListNode.contains(current)) {
          var focusedIndex = Number(current.dataset['index']);
          var lastFocusedKey = getKey({
            children: _this.props.children,
            selected: focusedIndex
          });
          _this.lastFocusedKey = lastFocusedKey;
        }
        if (_this.props.onFocus) {
          _this.props.onFocus(ev);
        }
      };
      _this.state = {
        prevChildren: props.children,
        prevFocused: null,
        prevSelected: _this.props.selected,
        prevSelectedKey: getKey(props),
        ready: isSelectedValid(props) ? ReadyState.INIT : ReadyState.DONE
      };
      _this.clientSiblingRef = /*#__PURE__*/(0, _react.createRef)(null);
      return _this;
    }
    _inherits(_Class, _Component);
    return _createClass(_Class, [{
      key: "componentDidUpdate",
      value: function componentDidUpdate() {
        if (this.state.ready === ReadyState.INIT) {
          this.scrollIntoView();
        } else if (this.state.ready === ReadyState.SCROLLED) {
          this.focusSelected();
        } else {
          var key = getKey(this.props);
          var keysDiffer = key && this.state.prevSelectedKey && key !== this.state.prevSelectedKey;
          if (keysDiffer || (!key || !this.state.prevSelectedKey) && this.state.prevSelected !== this.props.selected || !(0, _util.compareChildren)(this.state.prevChildren, this.props.children)) {
            this.resetFocus(keysDiffer);
          }
        }
      }
    }, {
      key: "resetFocus",
      value: function resetFocus(keysDiffer) {
        var adjustedFocusIndex;
        if (!keysDiffer && this.lastFocusedKey) {
          var targetIndex = indexFromKey(this.props.children, this.lastFocusedKey);
          if (targetIndex >= 0) {
            adjustedFocusIndex = targetIndex;
          }
        }
        this.setState({
          prevChildren: this.props.children,
          prevFocused: adjustedFocusIndex,
          prevSelected: this.props.selected,
          prevSelectedKey: getKey(this.props),
          ready: ReadyState.INIT
        });
      }
    }, {
      key: "focusSelected",
      value: function focusSelected() {
        this.setState({
          ready: ReadyState.DONE
        });
      }
    }, {
      key: "render",
      value: function render() {
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(WrappedWithRef, _objectSpread(_objectSpread({}, this.props), {}, {
          onFocus: this.handleFocus,
          outermostRef: this.clientSiblingRef,
          referrerName: "DropdownList",
          scrollTo: this.setScrollTo
        }));
      }
    }]);
  }(_react.Component), _Class.displayName = 'DropdownListSpotlightDecorator', _Class.propTypes = /** @lends agate/Dropdown.DropdownListSpotlightDecorator.prototype */{
    /**
     * Called when an item receives focus.
     *
     * @type {Function}
     */
    onFocus: _propTypes2["default"].func,
    /**
     * Index of the selected item.
     *
     * @type {Number}
     */
    selected: _propTypes2["default"].number
  }, _Class;
});
var DropdownListDecorator = (0, _compose["default"])(DropdownListSpotlightDecorator, (0, _Skinnable["default"])({
  prop: 'skin'
}));
var DropdownList = exports.DropdownList = DropdownListDecorator(DropdownListBase);
var _default = exports["default"] = DropdownList;