"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.BreadcrumbDecorator = void 0;
var _hoc = _interopRequireDefault(require("@enact/core/hoc"));
var _kind = _interopRequireDefault(require("@enact/core/kind"));
var _util = require("@enact/core/util");
var _spotlight = _interopRequireDefault(require("@enact/spotlight"));
var _ViewManager = _interopRequireDefault(require("@enact/ui/ViewManager"));
var _invariant = _interopRequireDefault(require("invariant"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = require("react");
var _Skinnable = _interopRequireDefault(require("../Skinnable"));
var _IdProvider = _interopRequireDefault(require("./IdProvider"));
var _Arrangers = require("./Arrangers");
var _Breadcrumb = _interopRequireDefault(require("./Breadcrumb"));
var _Breadcrumbs = _interopRequireDefault(require("./Breadcrumbs"));
var _CancelDecorator = _interopRequireDefault(require("./CancelDecorator"));
var _PanelsModule = _interopRequireDefault(require("./Panels.module.css"));
var _jsxRuntime = require("react/jsx-runtime");
var _excluded = ["breadcrumbs", "childProps", "children", "className", "generateId", "handleBreadcrumbWillTransition", "id", "index", "noAnimation"]; // TODO: Figure out how to document private sub-module members
/**
 * Default config for {@link agate/Panels.BreadcrumbDecorator}
 * @hocconfig
 * @memberof agate/Panels.BreadcrumbDecorator
 */
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 _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 defaultConfig = {
  /**
   * Classes to be added to the root node
   *
   * @type {String}
   * @default null
   * @memberof agate/Panels.BreadcrumbDecorator.defaultConfig
   */
  className: null,
  /**
   * Maximum number of breadcrumbs to display. If a function, it will be called on render to
   * calculate the number of breadcrumbs
   *
   * @type {Number|Function}
   * @default 0
   * @memberof agate/Panels.BreadcrumbDecorator.defaultConfig
   */
  max: 0,
  /**
   * Arranger for Panels
   *
   * @type {Object}
   * @default null
   * @memberof agate/Panels.BreadcrumbDecorator.defaultConfig
   */
  panelArranger: null
};

/**
 * A higher-order component that adds breadcrumbs to a Panels component
 *
 * @class BreadcrumbDecorator
 * @memberof agate/Panels
 * @hoc
 * @private
 */
var BreadcrumbDecorator = exports.BreadcrumbDecorator = (0, _hoc["default"])(defaultConfig, function (config, Wrapped) {
  var max = config.max,
    panelArranger = config.panelArranger,
    cfgClassName = config.className;
  var calcMax = (0, _util.coerceFunction)(max);
  var Decorator = (0, _kind["default"])({
    name: 'BreadcrumbDecorator',
    propTypes: /** @lends agate/Panels.BreadcrumbDecorator.prototype */{
      /**
       * Array of breadcrumbs or a function that generates an array of breadcrumbs
       *
       * @type {Function|Node[]}
       * @default Breadcrumbs
       */
      breadcrumbs: _propTypes["default"].oneOfType([_propTypes["default"].func,
      // generator
      _propTypes["default"].arrayOf(_propTypes["default"].node) // static array of breadcrumbs
      ]),
      /**
       * An object containing properties to be passed to each child. `aria-owns` will be added
       * or updated to this object to add the breadcrumbs to the accessibility tree of each
       * panel.
       *
       * @type {Object}
       * @public
       */
      childProps: _propTypes["default"].object,
      /**
       * Panels to be rendered
       *
       * @type {Node}
       */
      children: _propTypes["default"].node,
      /**
       * Function that generates unique identifiers for Panel instances
       *
       * @type {Function}
       * @required
       * @private
       */
      generateId: _propTypes["default"].func,
      /**
       * Unique identifier for the Panels instance
       *
       * @type {String}
       * @public
       */
      id: _propTypes["default"].string,
      /**
       * Index of the active panel
       *
       * @type {Number}
       * @default 0
       */
      index: _propTypes["default"].number,
      /**
       * Disable breadcrumb transitions.
       *
       * @type {Boolean}
       * @default false
       */
      noAnimation: _propTypes["default"].bool,
      /**
       * Called when a breadcrumb is clicked. The payload includes the `index` of the selected
       * breadcrumb
       *
       * @type {Function}
       */
      onSelectBreadcrumb: _propTypes["default"].func
    },
    defaultProps: {
      breadcrumbs: _Breadcrumbs["default"],
      index: 0,
      noAnimation: false
    },
    styles: {
      css: _PanelsModule["default"],
      className: cfgClassName
    },
    handlers: {
      handleBreadcrumbWillTransition: function handleBreadcrumbWillTransition(ev, _ref) {
        var id = _ref.id;
        var current = _spotlight["default"].getCurrent();
        if (!current) return;
        var breadcrumbs = document.querySelector("#".concat(id, " .").concat(_PanelsModule["default"].breadcrumbs));
        if (breadcrumbs && breadcrumbs.contains(current)) {
          current.blur();
        }
      }
    },
    computed: {
      // Invokes the breadcrumb generator, if provided
      breadcrumbs: function breadcrumbs(_ref2) {
        var _breadcrumbs = _ref2.breadcrumbs,
          id = _ref2.id,
          index = _ref2.index,
          onSelectBreadcrumb = _ref2.onSelectBreadcrumb;
        var x = calcMax(index);
        if (Array.isArray(_breadcrumbs)) {
          // limit the number of breadcrumbs based on the index and config.max
          var start = Math.max(index - x, 0);
          var children = _react.Children.toArray(_breadcrumbs).slice(start, start + x);

          // map over the children to either clone it with the appropriate props or to
          // create a Breadcrumb if passed an array of renderable primitives
          return _react.Children.map(children, function (child, i) {
            var props = {
              id: "".concat(id, "_bc_").concat(i),
              index: i,
              onSelect: onSelectBreadcrumb
            };
            if ( /*#__PURE__*/(0, _react.isValidElement)(child)) {
              return /*#__PURE__*/(0, _react.cloneElement)(child, props);
            } else {
              return /*#__PURE__*/(0, _react.createElement)(_Breadcrumb["default"], props, child);
            }
          });
        } else {
          return _breadcrumbs(id, index, x, onSelectBreadcrumb);
        }
      },
      childProps: function childProps(_ref3) {
        var _childProps = _ref3.childProps,
          id = _ref3.id,
          index = _ref3.index;
        if (!id || index === 0) {
          return _childProps;
        }
        var start = Math.max(index - calcMax(index), 0);
        var updatedChildProps = Object.assign({}, _childProps);
        var ariaOwns = [];
        for (var i = start; i < index; i++) {
          ariaOwns.push("".concat(id, "_bc_").concat(i));
        }
        if (updatedChildProps['aria-owns']) {
          ariaOwns.unshift(updatedChildProps['aria-owns']);
        }
        updatedChildProps['aria-owns'] = ariaOwns.join(' ');
        return updatedChildProps;
      }
    },
    render: function render(_ref4) {
      var breadcrumbs = _ref4.breadcrumbs,
        childProps = _ref4.childProps,
        children = _ref4.children,
        className = _ref4.className,
        generateId = _ref4.generateId,
        handleBreadcrumbWillTransition = _ref4.handleBreadcrumbWillTransition,
        id = _ref4.id,
        index = _ref4.index,
        noAnimation = _ref4.noAnimation,
        rest = _objectWithoutProperties(_ref4, _excluded);
      delete rest.onSelectBreadcrumb;
      var count = _react.Children.count(children);
      !(index === 0 && count === 0 || index < count) ? process.env.NODE_ENV !== "production" ? (0, _invariant["default"])(false, "Panels index, ".concat(index, ", is invalid for number of children, ").concat(count)) : (0, _invariant["default"])(false) : void 0;
      return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: className,
        "data-index": index,
        id: id,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ViewManager["default"], {
          arranger: _Arrangers.BreadcrumbArranger,
          className: _PanelsModule["default"].breadcrumbs,
          duration: 300,
          end: calcMax(),
          index: index - 1,
          noAnimation: noAnimation,
          onWillTransition: handleBreadcrumbWillTransition,
          start: 0,
          children: breadcrumbs
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread(_objectSpread({}, rest), {}, {
          arranger: panelArranger,
          childProps: childProps,
          generateId: generateId,
          id: "".concat(id, "_panels"),
          index: index,
          noAnimation: noAnimation,
          children: children
        }))]
      });
    }
  });
  return (0, _CancelDecorator["default"])({
    cancel: 'onSelectBreadcrumb'
  }, (0, _IdProvider["default"])((0, _Skinnable["default"])(Decorator)));
});
var _default = exports["default"] = BreadcrumbDecorator;