"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.toSegments = exports.propTypes = exports.Route = exports.Router = exports.default = void 0;

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _warning = _interopRequireDefault(require("warning"));

var _class, _temp;

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

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, 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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var toSegments = function toSegments(path) {
  return Array.isArray(path) ? path : path.split('/').slice(1);
};

exports.toSegments = toSegments;

var getPaths = function getPaths(routes, base) {
  var result = [];
  Object.keys(routes).filter(function (s) {
    return s[0] !== '$';
  }).forEach(function (p) {
    var path = base + '/' + p;
    result.push(path);
    result = result.concat(getPaths(routes[p], path));
  });
  return result;
};

var stringifyRoutes = function stringifyRoutes(routes) {
  var pad = '\n\t';
  var paths = getPaths(routes, '');
  return pad + paths.join(pad);
};

var propTypes = {
  path: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.string), // array of path segments
  _propTypes.default.string // URI-style path
  ])
};
/**
 * A Router component for use with [`Panels`]{@link moonstone/Panels.Panels}
 *
 * @class Router
 * @memberof moonstone/Panels
 * @ui
 * @public
 */

exports.propTypes = propTypes;
var Router = (_temp = _class =
/*#__PURE__*/
function (_React$Component) {
  _inherits(Router, _React$Component);

  function Router(props) {
    var _this;

    _classCallCheck(this, Router);

    _this = _possibleConstructorReturn(this, (Router.__proto__ || Object.getPrototypeOf(Router)).call(this, props));

    _this.initRoutes(props);

    return _this;
  }

  _createClass(Router, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      this.initRoutes(nextProps);
    }
    /**
     * Selects either `props.routes` or generates routes from `props.children`
     *
     * @param {Object} props Component props
     *
     * @returns {undefined}
     */

  }, {
    key: "initRoutes",
    value: function initRoutes(props) {
      this.routes = props.routes || this.createRoutes(props.children, {});
    }
    /**
     * Generates a set of routes from `children` and appends them to `routes`
     *
     * @param  {React.element[]} children Array of children
     * @param  {Object}          routes   Route configuration object
     *
     * @returns {Object}                   Route configuration object
     */

  }, {
    key: "createRoutes",
    value: function createRoutes(children, routes) {
      var _this2 = this;

      _react.default.Children.forEach(children, function (child) {
        var _child$props = child.props,
            path = _child$props.path,
            grandchildren = _child$props.children,
            component = _child$props.component,
            rest = _objectWithoutProperties(_child$props, ["path", "children", "component"]);

        if (path && component) {
          routes[path] = {
            $component: component,
            $props: rest
          };

          if (grandchildren) {
            _this2.createRoutes(grandchildren, routes[path]);
          }
        }
      });

      return routes;
    }
    /**
     * Creates an array of React.elements for the current path
     *
     * @returns {React.element[]} Children to render
     */

  }, {
    key: "createChildren",
    value: function createChildren() {
      var segments = toSegments(this.props.path);
      var valid = true;
      var route = this.routes;
      var children = segments.map(function (segment, index) {
        var subPath = segments.slice(0, index + 1).join('/');
        route = route && route[segment];

        if (route && route.$component) {
          return _react.default.createElement(route.$component, _objectSpread({}, route.$props, {
            key: 'view$/' + subPath,
            spotlightId: "panel-".concat(subPath.replace(/\//g, '-'))
          }));
        }

        valid = false;
        return null;
      });
      process.env.NODE_ENV !== "production" ? (0, _warning.default)(valid, "".concat(this.props.path, " does not match the configured routes: ").concat(stringifyRoutes(this.routes))) : void 0;
      return valid ? children : [];
    }
  }, {
    key: "render",
    value: function render() {
      var _props = this.props,
          Component = _props.component,
          rest = _objectWithoutProperties(_props, ["component"]);

      var children = this.createChildren();
      delete rest.path;
      delete rest.routes;
      return _react.default.createElement(Component, rest, children);
    }
  }]);

  return Router;
}(_react.default.Component), Object.defineProperty(_class, "displayName", {
  configurable: true,
  enumerable: true,
  writable: true,
  value: 'Router'
}), Object.defineProperty(_class, "propTypes", {
  configurable: true,
  enumerable: true,
  writable: true,
  value:
  /** @lends moonstone/Panels.Router.prototype */
  {
    /**
     * List of views to render.
     *
     * Will be rendered as a flat array of views suitable for use in
     * Panels and not a hierarchy of views as the path implies.
     *
     * May either be a URI-style path (`'/app/home/settings'`) or an array
     * of strings (`['app', 'home', 'settings']`)
     *
     * @type {String|String[]}
     * @required
     * @public
     */
    path: propTypes.path.isRequired,

    /**
     * The component wrapping the rendered path
     *
     * @type {Component}
     * @default 'div'
     * @public
     */
    component: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.func]),

    /**
     * Routes defined as an object rather than via JSX.
     *
     * If specified, `routes` will take
     * precendence over a JSX definition.
     *
     * ```JavaScript
     * const routes = {
     *   'first': {
     *     '$props': {
     *       'title': 'About Routable Panels Pattern'
     *     },
     *     '$component': AboutPanel,
     *     'second': {
     *       '$props': {
     *         'next': 'fourth',
     *         'title': 'Second'
     *       },
     *       '$component': MainPanel
     *     },
     *     'third': {
     *       '$props': {
     *         'next': 'first',
     *         'title': 'Third'
     *       },
     *       '$component': MainPanel,
     *       'fourth': {
     *         '$props': {
     *           'next': 'third',
     *           'title': 'Fourth'
     *         },
     *         '$component': MainPanel
     *       }
     *     }
     *   }
     * };
     *
     *	<Panels path="/app/home/settings" routes={routes} />
     * ```
     *
     * @type {Object}
     * @public
     */
    routes: _propTypes.default.object
  }
}), Object.defineProperty(_class, "defaultProps", {
  configurable: true,
  enumerable: true,
  writable: true,
  value: {
    component: 'div'
  }
}), _temp);
/**
 * Used with {@link moonstone/Panels.Routable} to define the `path` segment and the
 * `component` to render.
 *
 *`Route` elements can be nested to build multiple level paths.
 *
 * In the below example, `Panels` would render `SettingsPanel` with breadcrumbs to
 * navigate `AppPanel` and `HomePanel`.
 *
 * ```
 *	<Panels path="/app/home/settings" onSelectBreadcrumb={this.handleNavigate}>
 *		<Route path="app" component={AppPanel}>
 *			<Route path="home" component={HomePanel}>
 *				<Route path="settings" component={SettingsPanel} />
 *			</Route>
 *		</Route>
 *		<Route path="admin" component={AdminPanel} />
 *		<Route path="help" component={HelpPanel} />
 *	</Panels>
 * ```
 *
 * @class Route
 * @memberof moonstone/Panels
 * @public
 */

exports.Router = Router;

var Route = function Route() {
  return null;
};

exports.Route = Route;
Route.propTypes = {
  /**
   * The component to render when the `path` for this Route matches the path of the
   * {@link moonstone/Panels.Routable} container.
   *
   * @type {String|Function}
   * @required
   * @public
   * @memberof moonstone/Panels.Route.prototype
   */
  component: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.func]).isRequired,

  /**
   * The name of the path segment
   *
   * @type {String}
   * @required
   * @public
   * @memberof moonstone/Panels.Route.prototype
   */
  path: _propTypes.default.string.isRequired
};
var _default = Router;
exports.default = _default;