"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ComponentUI = void 0;
function _react() {
  const data = _interopRequireDefault(require("react"));
  _react = function () {
    return data;
  };
  return data;
}
function _lodash() {
  const data = _interopRequireDefault(require("lodash.flatten"));
  _lodash = function () {
    return data;
  };
  return data;
}
function _copyToClipboard() {
  const data = _interopRequireDefault(require("copy-to-clipboard"));
  _copyToClipboard = function () {
    return data;
  };
  return data;
}
function _commandBar() {
  const data = require("@teambit/command-bar");
  _commandBar = function () {
    return data;
  };
  return data;
}
function _componentUi() {
  const data = require("@teambit/component.ui.deprecation-icon");
  _componentUi = function () {
    return data;
  };
  return data;
}
function _harmony() {
  const data = require("@teambit/harmony");
  _harmony = function () {
    return data;
  };
  return data;
}
function _preview() {
  const data = require("@teambit/preview");
  _preview = function () {
    return data;
  };
  return data;
}
function _pubsub() {
  const data = require("@teambit/pubsub");
  _pubsub = function () {
    return data;
  };
  return data;
}
function _reactRouter() {
  const data = require("@teambit/react-router");
  _reactRouter = function () {
    return data;
  };
  return data;
}
function _ui() {
  const data = require("@teambit/ui");
  _ui = function () {
    return data;
  };
  return data;
}
function _lodash2() {
  const data = require("lodash");
  _lodash2 = function () {
    return data;
  };
  return data;
}
function _uiFoundationUi() {
  const data = require("@teambit/ui-foundation.ui.is-browser");
  _uiFoundationUi = function () {
    return data;
  };
  return data;
}
function _uiFoundationUiUseBox() {
  const data = require("@teambit/ui-foundation.ui.use-box.menu");
  _uiFoundationUiUseBox = function () {
    return data;
  };
  return data;
}
function _componentPackageVersion() {
  const data = require("@teambit/component-package-version");
  _componentPackageVersion = function () {
    return data;
  };
  return data;
}
function _aspect() {
  const data = require("./aspect.section");
  _aspect = function () {
    return data;
  };
  return data;
}
function _component() {
  const data = require("./component.aspect");
  _component = function () {
    return data;
  };
  return data;
}
function _component2() {
  const data = require("./ui/component");
  _component2 = function () {
    return data;
  };
  return data;
}
function _componentSearcher() {
  const data = require("./ui/component-searcher");
  _componentSearcher = function () {
    return data;
  };
  return data;
}
function _menu() {
  const data = require("./ui/menu");
  _menu = function () {
    return data;
  };
  return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: 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); }
class ComponentUI {
  constructor(
  /**
   * Pubsub aspects
   */
  pubsub, routeSlot, navSlot, consumeMethodSlot,
  /**
   * slot for registering a new widget to the menu.
   */
  widgetSlot,
  /**
   * slot for registering the right section of the menu
   */
  rightSideMenuSlot, menuItemSlot, pageItemSlot, componentSearchResultSlot, commandBarUI, reactRouterUi) {
    this.pubsub = pubsub;
    this.routeSlot = routeSlot;
    this.navSlot = navSlot;
    this.consumeMethodSlot = consumeMethodSlot;
    this.widgetSlot = widgetSlot;
    this.rightSideMenuSlot = rightSideMenuSlot;
    this.menuItemSlot = menuItemSlot;
    this.pageItemSlot = pageItemSlot;
    this.componentSearchResultSlot = componentSearchResultSlot;
    this.commandBarUI = commandBarUI;
    _defineProperty(this, "routePath", `/*`);
    _defineProperty(this, "componentSearcher", void 0);
    /**
     * the current visible component
     */
    _defineProperty(this, "activeComponent", void 0);
    _defineProperty(this, "copyNpmId", () => {
      const packageName = this.activeComponent?.packageName;
      if (packageName) {
        const version = this.activeComponent?.id.version;
        const versionString = version ? `@${this.formatToInstallableVersion(version)}` : '';
        (0, _copyToClipboard().default)(`${packageName}${versionString}`);
      }
    });
    /**
     * key bindings used by component aspect
     */
    _defineProperty(this, "keyBindings", [{
      id: 'component.copyBitId',
      // TODO - extract to a component!
      action: () => {
        (0, _copyToClipboard().default)(this.activeComponent?.id.toString() || '');
      },
      displayName: 'Copy component ID',
      keybinding: '.'
    }, {
      id: 'component.copyNpmId',
      // TODO - extract to a component!
      action: this.copyNpmId,
      displayName: 'Copy component package name',
      keybinding: ','
    }]);
    _defineProperty(this, "menuItems", [{
      category: 'general',
      title: 'Open command bar',
      keyChar: 'mod+k',
      handler: () => this.commandBarUI?.run('command-bar.open')
    }, {
      category: 'general',
      title: 'Toggle component list',
      keyChar: 'alt+s',
      handler: () => this.commandBarUI?.run('sidebar.toggle')
    }, {
      category: 'workflow',
      title: 'Copy component ID',
      keyChar: '.',
      handler: () => this.commandBarUI?.run('component.copyBitId')
    }, {
      category: 'workflow',
      title: 'Copy component package name',
      keyChar: ',',
      handler: () => this.commandBarUI?.run('component.copyNpmId')
    }]);
    _defineProperty(this, "bitMethod", ({
      options,
      id: componentId,
      packageName: packageNameFromProps,
      latest: latestFromProps,
      componentModel
    }) => {
      const packageName = packageNameFromProps || componentModel?.packageName;
      const latest = latestFromProps || componentModel?.id.version;
      const version = componentId.version === latest ? '' : `@${componentId.version}`;
      const packageVersion = componentId.version === latest ? '' : `@${this.formatToInstallableVersion(componentId.version)}`;
      return {
        Title: /*#__PURE__*/_react().default.createElement("img", {
          style: {
            width: '20px'
          },
          src: "https://static.bit.dev/brands/bit-logo-text.svg"
        }),
        Component: !options?.hide ? /*#__PURE__*/_react().default.createElement(_uiFoundationUiUseBox().Import, {
          componentId: `${componentId.toString({
            ignoreVersion: true
          })}${version}`,
          packageName: `${packageName}${packageVersion}`,
          componentName: componentId.name,
          showInstallMethod: !options?.disableInstall
        }) : null,
        order: 0
      };
    });
    _defineProperty(this, "handleComponentChange", activeComponent => {
      this.activeComponent = activeComponent;
    });
    _defineProperty(this, "registerMenuItem", menuItems => {
      this.menuItemSlot.register(menuItems);
    });
    _defineProperty(this, "registerPageItem", (...items) => {
      this.pageItemSlot.register(items);
    });
    /** register widgets to the components listed in the command bar */
    _defineProperty(this, "registerSearchResultWidget", (...items) => {
      this.componentSearchResultSlot.register(items);
      const totalPlugins = (0, _lodash().default)(this.componentSearchResultSlot.values());
      this.componentSearcher.updatePlugins(totalPlugins);
    });
    _defineProperty(this, "updateComponents", components => {
      this.componentSearcher.update(components || []);
    });
    this.componentSearcher = new (_componentSearcher().ComponentSearcher)({
      navigate: reactRouterUi.navigateTo
    });
    if (_uiFoundationUi().isBrowser) this.registerPubSub();
  }
  get routes() {
    return this.routeSlot.toArray().map(([key, routes]) => [key, Array.isArray(routes) ? [...(0, _lodash().default)(routes)] : [routes]]);
  }
  formatToInstallableVersion(version) {
    return (0, _componentPackageVersion().snapToSemver)(version);
  }
  registerPubSub() {
    this.pubsub.sub(_preview().PreviewAspect.id, be => {
      if (be.type === _preview().ClickInsideAnIframeEvent.TYPE) {
        const event = new MouseEvent('mousedown', {
          view: window,
          bubbles: true,
          cancelable: true
        });
        const body = document.body;
        body?.dispatchEvent(event);
      }
    });
  }
  getComponentUI(host, options = {}) {
    return /*#__PURE__*/_react().default.createElement(_component2().Component, {
      routeSlot: this.routeSlot,
      containerSlot: this.pageItemSlot,
      onComponentChange: this.handleComponentChange,
      host: host,
      path: options.path,
      useComponent: options.useComponent,
      componentIdStr: options.componentId,
      useComponentFilters: options.useComponentFilters,
      overriddenRoutes: options.routes
    });
  }
  getMenu(host, options = {}) {
    return /*#__PURE__*/_react().default.createElement(_menu().ComponentMenu, {
      className: options.className,
      skipRightSide: options.skipRightSide,
      navigationSlot: this.navSlot,
      consumeMethodSlot: this.consumeMethodSlot,
      rightSideMenuSlot: this.rightSideMenuSlot,
      widgetSlot: this.widgetSlot,
      host: host,
      menuItemSlot: this.menuItemSlot,
      useComponent: options.useComponent,
      path: options.path,
      componentIdStr: options.componentId,
      useComponentFilters: options.useComponentFilters,
      RightNode: options.RightNode
    });
  }
  listMenuItems() {
    const mainMenuItems = (0, _lodash2().groupBy)((0, _lodash().default)(this.menuItemSlot.values()), 'category');
    return mainMenuItems;
  }
  registerRoute(routes) {
    this.routeSlot.register(routes);
    return this;
  }
  registerNavigation(nav, order) {
    this.navSlot.register({
      props: nav,
      order
    });
  }
  registerConsumeMethod(...consumeMethods) {
    this.consumeMethodSlot.register(consumeMethods);
  }
  registerWidget(widget, order) {
    this.widgetSlot.register({
      props: widget,
      order
    });
  }
  registerRightSideMenuItem(...rightSideMenuItem) {
    this.rightSideMenuSlot.register(rightSideMenuItem);
  }
  static async provider([pubsub, commandBarUI, reactRouterUI], config, [routeSlot, navSlot, consumeMethodSlot, widgetSlot, menuItemSlot, pageSlot, componentSearchResultSlot, rightSideMenuSlot]) {
    // TODO: refactor ComponentHost to a separate extension (including sidebar, host, graphql, etc.)
    // TODO: add contextual hook for ComponentHost @uri/@oded
    const componentUI = new ComponentUI(pubsub, routeSlot, navSlot, consumeMethodSlot, widgetSlot, rightSideMenuSlot, menuItemSlot, pageSlot, componentSearchResultSlot, commandBarUI, reactRouterUI);
    const aspectSection = new (_aspect().AspectSection)();
    // @ts-ignore
    componentUI.registerSearchResultWidget({
      key: 'deprecation',
      end: _componentUi().DeprecationIcon
    });
    if (componentUI.commandBarUI && config.commandBar) {
      componentUI.commandBarUI.addCommand(...componentUI.keyBindings);
      commandBarUI.addSearcher(componentUI.componentSearcher);
    }
    componentUI.registerMenuItem(componentUI.menuItems);
    componentUI.registerRoute(aspectSection.route);
    componentUI.registerWidget(aspectSection.navigationLink, aspectSection.order);
    componentUI.registerConsumeMethod(componentUI.bitMethod);
    componentUI.registerRightSideMenuItem({
      item: /*#__PURE__*/_react().default.createElement(commandBarUI.CommandBarButton, null),
      order: 90
    });
    return componentUI;
  }
}
exports.ComponentUI = ComponentUI;
_defineProperty(ComponentUI, "dependencies", [_pubsub().PubsubAspect, _commandBar().CommandBarAspect, _reactRouter().ReactRouterAspect]);
_defineProperty(ComponentUI, "runtime", _ui().UIRuntime);
_defineProperty(ComponentUI, "slots", [_harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType(), _harmony().Slot.withType()]);
_defineProperty(ComponentUI, "defaultConfig", {
  commandBar: true
});
var _default = exports.default = ComponentUI;
_component().ComponentAspect.addRuntime(ComponentUI);

//# sourceMappingURL=component.ui.runtime.js.map