"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ComponentMenu = ComponentMenu;
exports.VersionRelatedDropdowns = VersionRelatedDropdowns;
exports.defaultLoadCurrentVersion = void 0;
exports.defaultLoadVersions = defaultLoadVersions;
function _react() {
  const data = _interopRequireWildcard(require("react"));
  _react = function () {
    return data;
  };
  return data;
}
function _reactRouterDom() {
  const data = require("react-router-dom");
  _reactRouterDom = function () {
    return data;
  };
  return data;
}
function _classnames() {
  const data = _interopRequireDefault(require("classnames"));
  _classnames = function () {
    return data;
  };
  return data;
}
function _lodash() {
  const data = require("lodash");
  _lodash = function () {
    return data;
  };
  return data;
}
function semver() {
  const data = _interopRequireWildcard(require("semver"));
  semver = function () {
    return data;
  };
  return data;
}
function _componentUi() {
  const data = require("@teambit/component.ui.version-dropdown");
  _componentUi = function () {
    return data;
  };
  return data;
}
function _uiFoundationUi() {
  const data = require("@teambit/ui-foundation.ui.main-dropdown");
  _uiFoundationUi = function () {
    return data;
  };
  return data;
}
function _componentId() {
  const data = require("@teambit/component-id");
  _componentId = function () {
    return data;
  };
  return data;
}
function _baseReactNavigation() {
  const data = require("@teambit/base-react.navigation.link");
  _baseReactNavigation = function () {
    return data;
  };
  return data;
}
function _uiFoundationUiUseBox() {
  const data = require("@teambit/ui-foundation.ui.use-box.dropdown");
  _uiFoundationUiUseBox = function () {
    return data;
  };
  return data;
}
function _lanesHooks() {
  const data = require("@teambit/lanes.hooks.use-lanes");
  _lanesHooks = function () {
    return data;
  };
  return data;
}
function _uiFoundationUiUseBox2() {
  const data = require("@teambit/ui-foundation.ui.use-box.menu");
  _uiFoundationUiUseBox2 = function () {
    return data;
  };
  return data;
}
function _useComponent() {
  const data = require("../use-component");
  _useComponent = function () {
    return data;
  };
  return data;
}
function _menuNav() {
  const data = require("./menu-nav");
  _menuNav = function () {
    return data;
  };
  return data;
}
function _useComponentFromLocation() {
  const data = require("../use-component-from-location");
  _useComponentFromLocation = function () {
    return data;
  };
  return data;
}
function _menuModule() {
  const data = _interopRequireDefault(require("./menu.module.scss"));
  _menuModule = function () {
    return data;
  };
  return data;
}
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 (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 getComponentIdStr(componentIdStr) {
  if ((0, _lodash().isFunction)(componentIdStr)) return componentIdStr();
  return componentIdStr;
}
/**
 * top bar menu.
 */
function ComponentMenu({
  navigationSlot,
  widgetSlot,
  className,
  host,
  menuItemSlot,
  consumeMethodSlot,
  rightSideMenuSlot,
  componentIdStr,
  skipRightSide,
  RightNode,
  useComponent,
  path,
  useComponentFilters
}) {
  const idFromLocation = (0, _useComponentFromLocation().useIdFromLocation)();
  const componentIdStrWithScopeFromLocation = (0, _useComponentFromLocation().useIdFromLocation)(undefined, true);
  const _componentIdStr = getComponentIdStr(componentIdStr);
  const componentId = _componentIdStr ? _componentId().ComponentID.fromString(_componentIdStr) : undefined;
  const resolvedComponentIdStr = path || idFromLocation;
  const mainMenuItems = (0, _react().useMemo)(() => (0, _lodash().groupBy)((0, _lodash().flatten)(menuItemSlot.values()), 'category'), [menuItemSlot]);
  const rightSideItems = (0, _react().useMemo)(() => (0, _lodash().orderBy)((0, _lodash().flatten)(rightSideMenuSlot.values()), 'order'), [rightSideMenuSlot]);
  const componentFilters = useComponentFilters?.() || {};
  const useComponentVersions = defaultLoadVersions(host, componentId?.toString() || componentIdStrWithScopeFromLocation, componentFilters, useComponent);
  const RightSide = /*#__PURE__*/_react().default.createElement("div", {
    className: _menuModule().default.rightSide
  }, RightNode || /*#__PURE__*/_react().default.createElement(_react().default.Fragment, null, /*#__PURE__*/_react().default.createElement(VersionRelatedDropdowns, {
    host: host,
    consumeMethods: consumeMethodSlot,
    componentId: componentId?.toString() || idFromLocation,
    useComponent: useComponentVersions,
    componentFilters: componentFilters
    // loading={loading}
  }), rightSideItems.map(({
    item
  }) => item), /*#__PURE__*/_react().default.createElement(_uiFoundationUi().MainDropdown, {
    className: _menuModule().default.hideOnMobile,
    menuItems: mainMenuItems
  })));
  return /*#__PURE__*/_react().default.createElement(_reactRouterDom().Routes, null, /*#__PURE__*/_react().default.createElement(_reactRouterDom().Route, {
    path: `${resolvedComponentIdStr}/*`,
    element: /*#__PURE__*/_react().default.createElement("div", {
      className: (0, _classnames().default)(_menuModule().default.topBar, className)
    }, /*#__PURE__*/_react().default.createElement("div", {
      className: _menuModule().default.leftSide
    }, /*#__PURE__*/_react().default.createElement(_menuNav().CollapsibleMenuNav, {
      navigationSlot: navigationSlot,
      widgetSlot: widgetSlot
    })), !skipRightSide && /*#__PURE__*/_react().default.createElement("div", {
      className: _menuModule().default.rightSide
    }, RightSide))
  }));
}
function defaultLoadVersions(host, componentId, componentFilters = {}, useComponent, loadingFromProps) {
  return _react().default.useCallback(_props => {
    const {
      skip,
      initialLoad
    } = _props || {};
    const fetchOptions = {
      logFilters: _objectSpread(_objectSpread({}, componentFilters), {}, {
        log: _objectSpread(_objectSpread({}, componentFilters.log), {}, {
          limit: initialLoad ? 3 : undefined
        })
      }),
      skip: loadingFromProps || skip,
      customUseComponent: useComponent
    };
    const {
      component,
      loading: loadingComponent,
      componentLogs = {}
    } = (0, _useComponent().useComponent)(host, componentId, fetchOptions);
    const logs = componentLogs?.logs;
    const loading = _react().default.useMemo(() => loadingComponent || loadingFromProps || componentLogs.loading, [loadingComponent, loadingFromProps, componentLogs.loading]);
    const snaps = (0, _react().useMemo)(() => {
      return (logs || []).filter(log => !log.tag).map(snap => _objectSpread(_objectSpread({}, snap), {}, {
        version: snap.hash
      }));
    }, [logs]);
    const tags = (0, _react().useMemo)(() => {
      const tagLookup = new Map();
      (logs || []).filter(log => log.tag).forEach(tag => {
        tagLookup.set(tag?.tag, tag);
      });
      return (0, _lodash().compact)((component?.tags?.toArray() || []).reverse().map(tag => tagLookup.get(tag.version.version))).map(tag => _objectSpread(_objectSpread({}, tag), {}, {
        version: tag.tag
      }));
    }, [logs]);
    return {
      loading,
      id: component?.id,
      packageName: component?.packageName,
      latestVersion: component?.latest,
      currentVersion: component?.version,
      snaps,
      tags,
      buildStatus: component?.buildStatus
    };
  }, [componentId, loadingFromProps, componentFilters]);
}
const defaultLoadCurrentVersion = props => {
  return _props => {
    const {
      skip,
      version: _version
    } = _props || {};
    const {
      snaps,
      tags,
      currentVersion,
      loading
    } = props.useComponent?.({
      skip,
      id: props.componentId
    }) ?? {};
    const version = _version ?? currentVersion;
    const isTag = _react().default.useMemo(() => semver().valid(version), [loading, version]);
    if (isTag) {
      return _react().default.useMemo(() => tags?.find(tag => tag.tag === version), [loading, tags?.length, version]);
    }
    return _react().default.useMemo(() => snaps?.find(snap => snap.version === version), [loading, snaps?.length, version]);
  };
};
exports.defaultLoadCurrentVersion = defaultLoadCurrentVersion;
function VersionRelatedDropdowns(props) {
  const updatedPropsWithDefaults = _objectSpread(_objectSpread({}, props), {}, {
    useLanes: props.useLanes ?? _lanesHooks().useLanes,
    dropdownOptions: _objectSpread(_objectSpread({}, props.dropdownOptions), {}, {
      showVersionDetails: props?.dropdownOptions?.showVersionDetails ?? true
    })
  });
  const loadVersion = defaultLoadCurrentVersion(updatedPropsWithDefaults);
  const {
    useLanes,
    consumeMethods,
    className,
    dropdownOptions,
    host
  } = updatedPropsWithDefaults;
  const {
    loading,
    id,
    tags,
    snaps,
    latest,
    packageName,
    currentVersion: _currentVersion
  } = props.useComponent?.({
    initialLoad: true
  }) || {};
  const location = (0, _baseReactNavigation().useLocation)();
  const {
    lanesModel
  } = useLanes();
  const lanes = id ? lanesModel?.getLanesByComponentId(id)?.filter(lane => !lane.id.isDefault()) || [] : [];
  const viewedLane = lanesModel?.viewedLane?.id && !lanesModel?.viewedLane?.id.isDefault() ? lanesModel.viewedLane : undefined;
  const isWorkspace = host === 'teambit.workspace/workspace';
  const isNew = tags?.length === 0 && snaps?.length === 0;
  const localVersion = isWorkspace && !isNew && (!viewedLane || lanesModel?.isViewingCurrentLane());
  const currentVersion = isWorkspace && !isNew && !location?.search.includes('version') ? 'workspace' : _currentVersion ?? '';
  const consumeMethodProps = _react().default.useMemo(() => {
    return id ? {
      id,
      packageName: packageName ?? '',
      latest,
      options: {
        viewedLane,
        disableInstall: !packageName
      }
    } : undefined;
  }, [id, packageName, latest, viewedLane]);
  const methods = useConsumeMethods(consumeMethods, consumeMethodProps);
  const hasMethods = methods?.length > 0;
  return /*#__PURE__*/_react().default.createElement(_react().default.Fragment, null, consumeMethods && id && hasMethods && /*#__PURE__*/_react().default.createElement(_uiFoundationUiUseBox().UseBoxDropdown, {
    position: "bottom-end",
    className: (0, _classnames().default)(_menuModule().default.useBox, _menuModule().default.hideOnMobile),
    Menu: /*#__PURE__*/_react().default.createElement(_uiFoundationUiUseBox2().Menu, {
      methods: methods,
      componentName: id.name
    })
  }), /*#__PURE__*/_react().default.createElement(_componentUi().VersionDropdown, {
    lanes: lanes,
    loading: loading,
    useComponentVersions: props.useComponent,
    hasMoreVersions: !isNew,
    useCurrentVersionLog: loadVersion,
    localVersion: localVersion,
    currentVersion: currentVersion,
    latestVersion: latest,
    currentLane: viewedLane,
    className: className,
    menuClassName: _menuModule().default.componentVersionMenu,
    getActiveTabIndex: dropdownOptions?.getActiveTabIndex,
    showVersionDetails: dropdownOptions?.showVersionDetails
  }));
}
function useConsumeMethods(consumeMethods, consumePluginProps) {
  return (0, _react().useMemo)(() => (0, _lodash().flatten)(consumeMethods?.values()).map(method => {
    if (!consumePluginProps) return undefined;
    return method?.(consumePluginProps);
  }).filter(x => !!x && x.Component && x.Title), [consumeMethods, consumePluginProps]);
}

//# sourceMappingURL=menu.js.map