1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Add CRDs to Command Palette and fix bugs

- Deprecate the "scope" on command registrations as it is buggy and
  generally unfixable

- Switch to mounting CommandContainer in each new frame so that there is
  no need to broadcast anything other than opening palette

- Add CRD entries to the command registry within each cluster

- Add navigate to CommandActionContext to simplify handling of root
  frame scoped URLs

- Switch to using DI for some of the deps

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton 2021-11-25 09:05:07 -05:00
parent 4f75acf2b4
commit abe90ad92a
27 changed files with 607 additions and 431 deletions

View File

@ -0,0 +1,32 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { computed } from "mobx";
import { crdStore } from "../../../../renderer/components/+custom-resources/crd.store";
const customResourceDefinitionsInjectable = getInjectable({
instantiate: () => computed(() => [...crdStore.items]),
lifecycle: lifecycleEnum.singleton,
});
export default customResourceDefinitionsInjectable;

View File

@ -201,3 +201,18 @@ export function every<T>(src: Iterable<T>, fn: (val: T) => any): boolean {
return true; return true;
} }
/**
* Produce a new iterator that drains the first and then the second
* @param first The first iterable to iterate through
* @param second The second iterable to iterate through
*/
export function* chain<T>(first: Iterable<T>, second: Iterable<T>): IterableIterator<T> {
for (const t of first) {
yield t;
}
for (const t of second) {
yield t;
}
}

View File

@ -19,7 +19,6 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
import mockFs from "mock-fs";
import { watch } from "chokidar"; import { watch } from "chokidar";
import { ExtensionsStore } from "../extensions-store"; import { ExtensionsStore } from "../extensions-store";
import path from "path"; import path from "path";
@ -30,6 +29,7 @@ import { AppPaths } from "../../common/app-paths";
import type { ExtensionLoader } from "../extension-loader"; import type { ExtensionLoader } from "../extension-loader";
import extensionLoaderInjectable from "../extension-loader/extension-loader.injectable"; import extensionLoaderInjectable from "../extension-loader/extension-loader.injectable";
import { getDiForUnitTesting } from "../getDiForUnitTesting"; import { getDiForUnitTesting } from "../getDiForUnitTesting";
import * as fse from "fs-extra";
jest.setTimeout(60_000); jest.setTimeout(60_000);
@ -43,6 +43,7 @@ jest.mock("../extension-installer", () => ({
installPackage: jest.fn(), installPackage: jest.fn(),
}, },
})); }));
jest.mock("fs-extra");
jest.mock("electron", () => ({ jest.mock("electron", () => ({
app: { app: {
getVersion: () => "99.99.99", getVersion: () => "99.99.99",
@ -63,6 +64,7 @@ AppPaths.init();
console = new Console(process.stdout, process.stderr); // fix mockFS console = new Console(process.stdout, process.stderr); // fix mockFS
const mockedWatch = watch as jest.MockedFunction<typeof watch>; const mockedWatch = watch as jest.MockedFunction<typeof watch>;
const mockedFse = fse as jest.Mocked<typeof fse>;
describe("ExtensionDiscovery", () => { describe("ExtensionDiscovery", () => {
let extensionLoader: ExtensionLoader; let extensionLoader: ExtensionLoader;
@ -77,22 +79,20 @@ describe("ExtensionDiscovery", () => {
extensionLoader = di.inject(extensionLoaderInjectable); extensionLoader = di.inject(extensionLoaderInjectable);
}); });
describe("with mockFs", () => {
beforeEach(() => {
mockFs({
[`${os.homedir()}/.k8slens/extensions/my-extension/package.json`]: JSON.stringify({
name: "my-extension",
}),
});
});
afterEach(() => {
mockFs.restore();
});
it("emits add for added extension", async (done) => { it("emits add for added extension", async (done) => {
let addHandler: (filePath: string) => void; let addHandler: (filePath: string) => void;
mockedFse.readJson.mockImplementation((p) => {
expect(p).toBe(path.join(os.homedir(), ".k8slens/extensions/my-extension/package.json"));
return {
name: "my-extension",
version: "1.0.0",
};
});
mockedFse.pathExists.mockImplementation(() => true);
const mockWatchInstance: any = { const mockWatchInstance: any = {
on: jest.fn((event: string, handler: typeof addHandler) => { on: jest.fn((event: string, handler: typeof addHandler) => {
if (event === "add") { if (event === "add") {
@ -106,7 +106,6 @@ describe("ExtensionDiscovery", () => {
mockedWatch.mockImplementationOnce(() => mockedWatch.mockImplementationOnce(() =>
(mockWatchInstance) as any, (mockWatchInstance) as any,
); );
const extensionDiscovery = ExtensionDiscovery.createInstance( const extensionDiscovery = ExtensionDiscovery.createInstance(
extensionLoader, extensionLoader,
); );
@ -125,6 +124,7 @@ describe("ExtensionDiscovery", () => {
isCompatible: false, isCompatible: false,
manifest: { manifest: {
name: "my-extension", name: "my-extension",
version: "1.0.0",
}, },
manifestPath: path.normalize("node_modules/my-extension/package.json"), manifestPath: path.normalize("node_modules/my-extension/package.json"),
}); });
@ -133,7 +133,6 @@ describe("ExtensionDiscovery", () => {
addHandler(path.join(extensionDiscovery.localFolderPath, "/my-extension/package.json")); addHandler(path.join(extensionDiscovery.localFolderPath, "/my-extension/package.json"));
}); });
});
it("doesn't emit add for added file under extension", async done => { it("doesn't emit add for added file under extension", async done => {
let addHandler: (filePath: string) => void; let addHandler: (filePath: string) => void;
@ -172,3 +171,4 @@ describe("ExtensionDiscovery", () => {
}, 10); }, 10);
}); });
}); });

View File

@ -262,7 +262,6 @@ export class ExtensionLoader {
registries.AppPreferenceRegistry.getInstance().add(extension.appPreferences), registries.AppPreferenceRegistry.getInstance().add(extension.appPreferences),
registries.EntitySettingRegistry.getInstance().add(extension.entitySettings), registries.EntitySettingRegistry.getInstance().add(extension.entitySettings),
registries.StatusBarRegistry.getInstance().add(extension.statusBarItems), registries.StatusBarRegistry.getInstance().add(extension.statusBarItems),
registries.CommandRegistry.getInstance().add(extension.commands),
registries.CatalogEntityDetailRegistry.getInstance().add(extension.catalogEntityDetailItems), registries.CatalogEntityDetailRegistry.getInstance().add(extension.catalogEntityDetailItems),
]; ];
@ -293,7 +292,6 @@ export class ExtensionLoader {
registries.KubeObjectDetailRegistry.getInstance().add(extension.kubeObjectDetailItems), registries.KubeObjectDetailRegistry.getInstance().add(extension.kubeObjectDetailItems),
registries.KubeObjectStatusRegistry.getInstance().add(extension.kubeObjectStatusTexts), registries.KubeObjectStatusRegistry.getInstance().add(extension.kubeObjectStatusTexts),
registries.WorkloadsOverviewDetailRegistry.getInstance().add(extension.kubeWorkloadsOverviewItems), registries.WorkloadsOverviewDetailRegistry.getInstance().add(extension.kubeWorkloadsOverviewItems),
registries.CommandRegistry.getInstance().add(extension.commands),
]; ];
this.events.on("remove", (removedExtension: LensRendererExtension) => { this.events.on("remove", (removedExtension: LensRendererExtension) => {

View File

@ -30,6 +30,7 @@ import type { TopBarRegistration } from "../renderer/components/layout/top-bar/t
import type { KubernetesCluster } from "../common/catalog-entities"; import type { KubernetesCluster } from "../common/catalog-entities";
import type { WelcomeMenuRegistration } from "../renderer/components/+welcome/welcome-menu-items/welcome-menu-registration"; import type { WelcomeMenuRegistration } from "../renderer/components/+welcome/welcome-menu-items/welcome-menu-registration";
import type { WelcomeBannerRegistration } from "../renderer/components/+welcome/welcome-banner-items/welcome-banner-registration"; import type { WelcomeBannerRegistration } from "../renderer/components/+welcome/welcome-banner-items/welcome-banner-registration";
import type { CommandRegistration } from "../renderer/components/command-palette/registered-commands/commands";
export class LensRendererExtension extends LensExtension { export class LensRendererExtension extends LensExtension {
globalPages: registries.PageRegistration[] = []; globalPages: registries.PageRegistration[] = [];
@ -42,7 +43,7 @@ export class LensRendererExtension extends LensExtension {
kubeObjectDetailItems: registries.KubeObjectDetailRegistration[] = []; kubeObjectDetailItems: registries.KubeObjectDetailRegistration[] = [];
kubeObjectMenuItems: registries.KubeObjectMenuRegistration[] = []; kubeObjectMenuItems: registries.KubeObjectMenuRegistration[] = [];
kubeWorkloadsOverviewItems: registries.WorkloadsOverviewDetailRegistration[] = []; kubeWorkloadsOverviewItems: registries.WorkloadsOverviewDetailRegistration[] = [];
commands: registries.CommandRegistration[] = []; commands: CommandRegistration[] = [];
welcomeMenus: WelcomeMenuRegistration[] = []; welcomeMenus: WelcomeMenuRegistration[] = [];
welcomeBanners: WelcomeBannerRegistration[] = []; welcomeBanners: WelcomeBannerRegistration[] = [];
catalogEntityDetailItems: registries.CatalogEntityDetailRegistration<CatalogEntity>[] = []; catalogEntityDetailItems: registries.CatalogEntityDetailRegistration<CatalogEntity>[] = [];

View File

@ -28,7 +28,6 @@ export * from "./status-bar-registry";
export * from "./kube-object-detail-registry"; export * from "./kube-object-detail-registry";
export * from "./kube-object-menu-registry"; export * from "./kube-object-menu-registry";
export * from "./kube-object-status-registry"; export * from "./kube-object-status-registry";
export * from "./command-registry";
export * from "./entity-setting-registry"; export * from "./entity-setting-registry";
export * from "./catalog-entity-detail-registry"; export * from "./catalog-entity-detail-registry";
export * from "./workloads-overview-detail-registry"; export * from "./workloads-overview-detail-registry";

View File

@ -81,7 +81,7 @@ describe("kubeconfig manager tests", () => {
let contextHandler: ContextHandler; let contextHandler: ContextHandler;
beforeEach(() => { beforeEach(() => {
const mockOpts = { mockFs({
"minikube-config.yml": JSON.stringify({ "minikube-config.yml": JSON.stringify({
apiVersion: "v1", apiVersion: "v1",
clusters: [{ clusters: [{
@ -103,9 +103,7 @@ describe("kubeconfig manager tests", () => {
kind: "Config", kind: "Config",
preferences: {}, preferences: {},
}), }),
}; });
mockFs(mockOpts);
cluster = new Cluster({ cluster = new Cluster({
id: "foo", id: "foo",

View File

@ -24,11 +24,15 @@ import { createContainer } from "@ogre-tools/injectable";
export const getDi = () => export const getDi = () =>
createContainer( createContainer(
getRequireContextForMainCode, getRequireContextForMainCode,
getRequireContextForCommonCode,
getRequireContextForCommonExtensionCode, getRequireContextForCommonExtensionCode,
); );
const getRequireContextForMainCode = () => const getRequireContextForMainCode = () =>
require.context("./", true, /\.injectable\.(ts|tsx)$/); require.context("./", true, /\.injectable\.(ts|tsx)$/);
const getRequireContextForCommonCode = () =>
require.context("../common", true, /\.injectable\.(ts|tsx)$/);
const getRequireContextForCommonExtensionCode = () => const getRequireContextForCommonExtensionCode = () =>
require.context("../extensions", true, /\.injectable\.(ts|tsx)$/); require.context("../extensions", true, /\.injectable\.(ts|tsx)$/);

View File

@ -216,8 +216,14 @@ export function getAppMenu(
label: "Command Palette...", label: "Command Palette...",
accelerator: "Shift+CmdOrCtrl+P", accelerator: "Shift+CmdOrCtrl+P",
id: "command-palette", id: "command-palette",
click() { click(_m, _b, event) {
/**
* Don't broadcast unless it was triggered by menu iteration so that
* there aren't double events in renderer
*/
if (!event?.triggeredByAccelerator) {
broadcastMessage("command-palette:open"); broadcastMessage("command-palette:open");
}
}, },
}, },
{ type: "separator" }, { type: "separator" },

View File

@ -32,6 +32,7 @@ import { CatalogRunEvent } from "../../common/catalog/catalog-run-event";
import { ipcRenderer } from "electron"; import { ipcRenderer } from "electron";
import { CatalogIpcEvents } from "../../common/ipc/catalog"; import { CatalogIpcEvents } from "../../common/ipc/catalog";
import { navigate } from "../navigation"; import { navigate } from "../navigation";
import { isMainFrame } from "process";
export type EntityFilter = (entity: CatalogEntity) => any; export type EntityFilter = (entity: CatalogEntity) => any;
export type CatalogEntityOnBeforeRun = (event: CatalogRunEvent) => void | Promise<void>; export type CatalogEntityOnBeforeRun = (event: CatalogRunEvent) => void | Promise<void>;
@ -85,6 +86,16 @@ export class CatalogEntityRegistry {
// Make sure that we get items ASAP and not the next time one of them changes // Make sure that we get items ASAP and not the next time one of them changes
ipcRenderer.send(CatalogIpcEvents.INIT); ipcRenderer.send(CatalogIpcEvents.INIT);
if (isMainFrame) {
ipcRendererOn("catalog-entity:run", (event, id: string) => {
const entity = this.getById(id);
if (entity) {
this.onRun(entity);
}
});
}
} }
@action updateItems(items: (CatalogEntityData & CatalogEntityKindData)[]) { @action updateItems(items: (CatalogEntityData & CatalogEntityKindData)[]) {

View File

@ -21,13 +21,14 @@
import { when } from "mobx"; import { when } from "mobx";
import { catalogCategoryRegistry } from "../../../common/catalog"; import { catalogCategoryRegistry } from "../../../common/catalog";
import { catalogEntityRegistry } from "../../../renderer/api/catalog-entity-registry"; import { catalogEntityRegistry } from "../catalog-entity-registry";
import { isActiveRoute } from "../../../renderer/navigation"; import { isActiveRoute } from "../../navigation";
import type { GeneralEntity } from "../../../common/catalog-entities";
export async function setEntityOnRouteMatch() { export async function setEntityOnRouteMatch() {
await when(() => catalogEntityRegistry.entities.size > 0); await when(() => catalogEntityRegistry.entities.size > 0);
const entities = catalogEntityRegistry.getItemsForCategory(catalogCategoryRegistry.getByName("General")); const entities: GeneralEntity[] = catalogEntityRegistry.getItemsForCategory(catalogCategoryRegistry.getByName("General"));
const activeEntity = entities.find(entity => isActiveRoute(entity.spec.path)); const activeEntity = entities.find(entity => isActiveRoute(entity.spec.path));
if (activeEntity) { if (activeEntity) {

View File

@ -49,7 +49,7 @@ import { SentryInit } from "../common/sentry";
import { TerminalStore } from "./components/dock/terminal.store"; import { TerminalStore } from "./components/dock/terminal.store";
import { AppPaths } from "../common/app-paths"; import { AppPaths } from "../common/app-paths";
import { registerCustomThemes } from "./components/monaco-editor"; import { registerCustomThemes } from "./components/monaco-editor";
import { getDi } from "./components/getDi"; import { getDi } from "./getDi";
import { DiContextProvider } from "@ogre-tools/injectable-react"; import { DiContextProvider } from "@ogre-tools/injectable-react";
import type { DependencyInjectionContainer } from "@ogre-tools/injectable"; import type { DependencyInjectionContainer } from "@ogre-tools/injectable";
import extensionLoaderInjectable from "../extensions/extension-loader/extension-loader.injectable"; import extensionLoaderInjectable from "../extensions/extension-loader/extension-loader.injectable";
@ -102,9 +102,6 @@ export async function bootstrap(comp: () => Promise<AppComponent>, di: Dependenc
logger.info(`${logPrefix} initializing Registries`); logger.info(`${logPrefix} initializing Registries`);
initializers.initRegistries(); initializers.initRegistries();
logger.info(`${logPrefix} initializing CommandRegistry`);
initializers.initCommandRegistry();
logger.info(`${logPrefix} initializing EntitySettingsRegistry`); logger.info(`${logPrefix} initializing EntitySettingsRegistry`);
initializers.initEntitySettingsRegistry(); initializers.initEntitySettingsRegistry();

View File

@ -66,22 +66,15 @@ export class CRDStore extends KubeObjectStore<CustomResourceDefinition> {
@computed get groups() { @computed get groups() {
const groups: Record<string, CustomResourceDefinition[]> = {}; const groups: Record<string, CustomResourceDefinition[]> = {};
return this.items.reduce((groups, crd) => { for (const crd of this.items) {
const group = crd.getGroup(); (groups[crd.getGroup()] ??= []).push(crd);
}
if (!groups[group]) groups[group] = [];
groups[group].push(crd);
return groups; return groups;
}, groups);
} }
getByGroup(group: string, pluralName: string) { getByGroup(group: string, pluralName: string) {
const crdInGroup = this.groups[group]; return this.groups[group]?.find(crd => crd.getPluralName() === pluralName);
if (!crdInGroup) return null;
return crdInGroup.find(crd => crd.getPluralName() === pluralName);
} }
getByObject(obj: KubeObject) { getByObject(obj: KubeObject) {

View File

@ -22,6 +22,7 @@
import { computed } from "mobx"; import { computed } from "mobx";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import React from "react"; import React from "react";
import { broadcastMessage } from "../../../common/ipc";
import type { CatalogEntity } from "../../api/catalog-entity"; import type { CatalogEntity } from "../../api/catalog-entity";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry"; import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
import { CommandOverlay } from "../command-palette"; import { CommandOverlay } from "../command-palette";
@ -37,7 +38,7 @@ export class ActivateEntityCommand extends React.Component {
} }
onSelect(entity: CatalogEntity): void { onSelect(entity: CatalogEntity): void {
catalogEntityRegistry.onRun(entity); broadcastMessage("catalog-entity:run", entity.getId());
CommandOverlay.close(); CommandOverlay.close();
} }

View File

@ -38,7 +38,7 @@ import * as routes from "../../../common/routes";
import { DeleteClusterDialog } from "../delete-cluster-dialog"; import { DeleteClusterDialog } from "../delete-cluster-dialog";
import { reaction } from "mobx"; import { reaction } from "mobx";
import { navigation } from "../../navigation"; import { navigation } from "../../navigation";
import { setEntityOnRouteMatch } from "../../../main/catalog-sources/helpers/general-active-sync"; import { setEntityOnRouteMatch } from "../../api/helpers/general-active-sync";
import { catalogURL, getPreviousTabUrl } from "../../../common/routes"; import { catalogURL, getPreviousTabUrl } from "../../../common/routes";
import { TopBar } from "../layout/top-bar/top-bar"; import { TopBar } from "../layout/top-bar/top-bar";

View File

@ -21,20 +21,30 @@
import "./command-container.scss"; import "./command-container.scss";
import { observer } from "mobx-react"; import { disposeOnUnmount, observer } from "mobx-react";
import React from "react"; import React from "react";
import { Dialog } from "../dialog"; import { Dialog } from "../dialog";
import { ipcRendererOn } from "../../../common/ipc";
import { CommandDialog } from "./command-dialog"; import { CommandDialog } from "./command-dialog";
import type { ClusterId } from "../../../common/cluster-types"; import type { ClusterId } from "../../../common/cluster-types";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
import { CommandRegistration, CommandRegistry } from "../../../extensions/registries/command-registry";
import { CommandOverlay } from "./command-overlay"; import { CommandOverlay } from "./command-overlay";
import { isMac } from "../../../common/vars";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
import { broadcastMessage, ipcRendererOn } from "../../../common/ipc";
import { getMatchedClusterId } from "../../navigation";
import type { Disposer } from "../../utils";
export interface CommandContainerProps { export interface CommandContainerProps {
clusterId?: ClusterId; clusterId?: ClusterId;
} }
function addWindowEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): Disposer {
window.addEventListener(type, listener, options);
return () => {
window.removeEventListener(type, listener);
};
}
@observer @observer
export class CommandContainer extends React.Component<CommandContainerProps> { export class CommandContainer extends React.Component<CommandContainerProps> {
private escHandler(event: KeyboardEvent) { private escHandler(event: KeyboardEvent) {
@ -44,31 +54,39 @@ export class CommandContainer extends React.Component<CommandContainerProps> {
} }
} }
private findCommandById(commandId: string) { handleCommandPalette = () => {
return CommandRegistry.getInstance().getItems().find((command) => command.id === commandId); const clusterIsActive = getMatchedClusterId() !== undefined;
}
private runCommand(command: CommandRegistration) { if (clusterIsActive) {
command.action({ broadcastMessage(`command-palette:${catalogEntityRegistry.activeEntity.getId()}:open`);
entity: catalogEntityRegistry.activeEntity, } else {
}); CommandOverlay.open(<CommandDialog />);
}
};
onKeyboardShortcut(action: () => void) {
return ({ key, shiftKey, ctrlKey, altKey, metaKey }: KeyboardEvent) => {
const ctrlOrCmd = isMac ? metaKey && !ctrlKey : !metaKey && ctrlKey;
if (key === "p" && shiftKey && ctrlOrCmd && !altKey) {
action();
}
};
} }
componentDidMount() { componentDidMount() {
if (this.props.clusterId) { const action = this.props.clusterId
ipcRendererOn(`command-palette:run-action:${this.props.clusterId}`, (event, commandId: string) => { ? () => CommandOverlay.open(<CommandDialog />)
const command = this.findCommandById(commandId); : this.handleCommandPalette;
const ipcChannel = this.props.clusterId
? `command-palette:${this.props.clusterId}:open`
: "command-palette:open";
if (command) { disposeOnUnmount(this, [
this.runCommand(command); ipcRendererOn(ipcChannel, action),
} addWindowEventListener("keydown", this.onKeyboardShortcut(action)),
}); addWindowEventListener("keyup", (e) => this.escHandler(e), true),
} else { ]);
ipcRendererOn("command-palette:open", () => {
CommandOverlay.open(<CommandDialog />);
});
}
window.addEventListener("keyup", (e) => this.escHandler(e), true);
} }
render() { render() {

View File

@ -21,61 +21,31 @@
import { Select } from "../select"; import { Select } from "../select";
import { computed, makeObservable, observable } from "mobx"; import type { IComputedValue } from "mobx";
import { observer } from "mobx-react"; import { observer } from "mobx-react";
import React from "react"; import React, { useState } from "react";
import { CommandRegistry } from "../../../extensions/registries/command-registry";
import { CommandOverlay } from "./command-overlay"; import { CommandOverlay } from "./command-overlay";
import { broadcastMessage } from "../../../common/ipc";
import { navigate } from "../../navigation";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
import type { CatalogEntity } from "../../../common/catalog"; import type { CatalogEntity } from "../../../common/catalog";
import { clusterViewURL } from "../../../common/routes"; import { navigate } from "../../navigation";
import { broadcastMessage } from "../../../common/ipc";
import { IpcRendererNavigationEvents } from "../../navigation/events";
import type { RegisteredCommand } from "./registered-commands/commands";
import { iter } from "../../utils";
import { orderBy } from "lodash";
import { withInjectables } from "@ogre-tools/injectable-react";
import registeredCommandsInjectable from "./registered-commands/registered-commands.injectable";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
@observer interface Dependencies {
export class CommandDialog extends React.Component { commands: IComputedValue<Map<string, RegisteredCommand>>;
@observable menuIsOpen = true; activeEntity?: CatalogEntity;
@observable searchValue: any = undefined;
constructor(props: {}) {
super(props);
makeObservable(this);
} }
@computed get activeEntity(): CatalogEntity | undefined { const NonInjectedCommandDialog = observer(({ commands, activeEntity }: Dependencies) => {
return catalogEntityRegistry.activeEntity; const [searchValue, setSearchValue] = useState("");
}
@computed get options() { const executeAction = (commandId: string) => {
const registry = CommandRegistry.getInstance(); const command = commands.get().get(commandId);
const context = {
entity: this.activeEntity,
};
return registry.getItems().filter((command) => {
if (command.scope === "entity" && !this.activeEntity) {
return false;
}
try {
return command.isActive?.(context) ?? true;
} catch(e) {
console.error(e);
}
return false;
})
.map((command) => ({
value: command.id,
label: command.title,
}))
.sort((a, b) => a.label > b.label ? 1 : -1);
}
private onChange(value: string) {
const registry = CommandRegistry.getInstance();
const command = registry.getItems().find((cmd) => cmd.id === value);
if (!command) { if (!command) {
return; return;
@ -83,46 +53,73 @@ export class CommandDialog extends React.Component {
try { try {
CommandOverlay.close(); CommandOverlay.close();
if (command.scope === "global") {
command.action({ command.action({
entity: this.activeEntity, entity: activeEntity,
}); navigate: (url, opts = {}) => {
} else if(this.activeEntity) { const { forceRootFrame = false } = opts;
navigate(clusterViewURL({
params: { if (forceRootFrame) {
clusterId: this.activeEntity.metadata.uid, broadcastMessage(IpcRendererNavigationEvents.NAVIGATE_IN_APP, url);
}, } else {
})); navigate(url);
broadcastMessage(`command-palette:run-action:${this.activeEntity.metadata.uid}`, command.id);
} }
},
});
} catch (error) { } catch (error) {
console.error("[COMMAND-DIALOG] failed to execute command", command.id, error); console.error("[COMMAND-DIALOG] failed to execute command", command.id, error);
} }
};
const context = {
entity: activeEntity,
};
const activeCommands = iter.filter(commands.get().values(), command => {
try {
return command.isActive(context);
} catch (error) {
console.error(`[COMMAND-DIALOG]: isActive for ${command.id} threw an error, defaulting to false`, error);
} }
render() { return false;
});
const options = Array.from(activeCommands, ({ id, title }) => ({
value: id,
label: typeof title === "function"
? title(context)
: title,
}));
// Make sure the options are in the correct order
orderBy(options, "label", "asc");
return ( return (
<Select <Select
menuPortalTarget={null} menuPortalTarget={null}
onChange={v => this.onChange(v.value)} onChange={v => executeAction(v.value)}
components={{ components={{
DropdownIndicator: null, DropdownIndicator: null,
IndicatorSeparator: null, IndicatorSeparator: null,
}} }}
menuIsOpen={this.menuIsOpen} menuIsOpen
options={this.options} options={options}
autoFocus={true} autoFocus={true}
escapeClearsValue={false} escapeClearsValue={false}
data-test-id="command-palette-search" data-test-id="command-palette-search"
placeholder="Type a command or search&hellip;" placeholder="Type a command or search&hellip;"
onInputChange={(newValue, { action }) => { onInputChange={(newValue, { action }) => {
if (action === "input-change") { if (action === "input-change") {
this.searchValue = newValue; setSearchValue(newValue);
} }
}} }}
inputValue={this.searchValue} inputValue={searchValue}
/> />
); );
} });
}
export const CommandDialog = withInjectables<Dependencies>(NonInjectedCommandDialog, {
getProps: di => ({
commands: di.inject(registeredCommandsInjectable),
// TODO: replace with injection
activeEntity: catalogEntityRegistry.activeEntity,
}),
});

View File

@ -19,34 +19,55 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
// Extensions API -> Commands import type { CatalogEntity } from "../../../../common/catalog";
import { BaseRegistry } from "./base-registry";
import type { LensExtension } from "../lens-extension";
import type { CatalogEntity } from "../../common/catalog";
/**
* The context given to commands when executed
*/
export interface CommandContext { export interface CommandContext {
entity?: CatalogEntity; entity?: CatalogEntity;
} }
export interface CommandActionNavigateOptions {
/**
* If `true` then the navigate will only navigate on the root frame and not
* within a cluster
* @default false
*/
forceRootFrame?: boolean;
}
export interface CommandActionContext extends CommandContext {
navigate: (url: string, opts?: CommandActionNavigateOptions) => void;
}
export interface CommandRegistration { export interface CommandRegistration {
/**
* The ID of the command, must be globally unique
*/
id: string; id: string;
title: string;
scope: "entity" | "global"; /**
action: (context: CommandContext) => void; * The display name of the command in the command pallet
*/
title: string | ((context: CommandContext) => string);
/**
* @deprecated use `isActive` instead since there is always an entity active
*/
scope?: "global" | "entity";
/**
* The function to run when this command is selected
*/
action: (context: CommandActionContext) => void;
/**
* A function that determines if the command is active.
*
* @default () => true
*/
isActive?: (context: CommandContext) => boolean; isActive?: (context: CommandContext) => boolean;
} }
export class CommandRegistry extends BaseRegistry<CommandRegistration> { export type RegisteredCommand = Required<Omit<CommandRegistration, "scope">>;
add(items: CommandRegistration | CommandRegistration[], extension?: LensExtension) {
const itemArray = [items].flat();
const newIds = itemArray.map((item) => item.id);
const currentIds = this.getItems().map((item) => item.id);
const filteredIds = newIds.filter((id) => !currentIds.includes(id));
const filteredItems = itemArray.filter((item) => filteredIds.includes(item.id));
return super.add(filteredItems, extension);
}
}

View File

@ -0,0 +1,215 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import * as routes from "../../../../common/routes";
import { EntitySettingRegistry } from "../../../../extensions/registries";
import { CommandOverlay } from "../../../components/command-palette";
import { createTerminalTab } from "../../../components/dock/terminal.store";
import { HotbarAddCommand } from "../../../components/hotbar/hotbar-add-command";
import { HotbarRemoveCommand } from "../../../components/hotbar/hotbar-remove-command";
import { HotbarSwitchCommand } from "../../../components/hotbar/hotbar-switch-command";
import { HotbarRenameCommand } from "../../../components/hotbar/hotbar-rename-command";
import { ActivateEntityCommand } from "../../../components/activate-entity-command";
import type { CommandContext, CommandRegistration } from "./commands";
export function isKubernetesClusterActive(context: CommandContext): boolean {
return context.entity?.kind === "KubernetesCluster";
}
export const internalCommands: CommandRegistration[] = [
{
id: "app.showPreferences",
title: "Preferences: Open",
action: ({ navigate }) => navigate(routes.preferencesURL(), {
forceRootFrame: true,
}),
},
{
id: "cluster.viewHelmCharts",
title: "Cluster: View Helm Charts",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.helmChartsURL()),
},
{
id: "cluster.viewHelmReleases",
title: "Cluster: View Helm Releases",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.releaseURL()),
},
{
id: "cluster.viewConfigMaps",
title: "Cluster: View ConfigMaps",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.configMapsURL()),
},
{
id: "cluster.viewSecrets",
title: "Cluster: View Secrets",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.secretsURL()),
},
{
id: "cluster.viewResourceQuotas",
title: "Cluster: View ResourceQuotas",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.resourceQuotaURL()),
},
{
id: "cluster.viewLimitRanges",
title: "Cluster: View LimitRanges",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.limitRangeURL()),
},
{
id: "cluster.viewHorizontalPodAutoscalers",
title: "Cluster: View HorizontalPodAutoscalers (HPA)",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.hpaURL()),
},
{
id: "cluster.viewPodDisruptionBudget",
title: "Cluster: View PodDisruptionBudgets",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.pdbURL()),
},
{
id: "cluster.viewServices",
title: "Cluster: View Services",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.servicesURL()),
},
{
id: "cluster.viewEndpoints",
title: "Cluster: View Endpoints",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.endpointURL()),
},
{
id: "cluster.viewIngresses",
title: "Cluster: View Ingresses",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.ingressURL()),
},
{
id: "cluster.viewNetworkPolicies",
title: "Cluster: View NetworkPolicies",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.networkPoliciesURL()),
},
{
id: "cluster.viewNodes",
title: "Cluster: View Nodes",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.nodesURL()),
},
{
id: "cluster.viewPods",
title: "Cluster: View Pods",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.podsURL()),
},
{
id: "cluster.viewDeployments",
title: "Cluster: View Deployments",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.deploymentsURL()),
},
{
id: "cluster.viewDaemonSets",
title: "Cluster: View DaemonSets",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.daemonSetsURL()),
},
{
id: "cluster.viewStatefulSets",
title: "Cluster: View StatefulSets",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.statefulSetsURL()),
},
{
id: "cluster.viewJobs",
title: "Cluster: View Jobs",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.jobsURL()),
},
{
id: "cluster.viewCronJobs",
title: "Cluster: View CronJobs",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.cronJobsURL()),
},
{
id: "cluster.viewCustomResourceDefinitions",
title: "Cluster: View Custom Resource Definitions",
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(routes.crdURL()),
},
{
id: "entity.viewSettings",
title: ({ entity }) => `${entity.kind}/${entity.getName()}: View Settings`,
action: ({ entity, navigate }) => navigate(`/entity/${entity.getId()}/settings`, {
forceRootFrame: true,
}),
isActive: ({ entity }) => {
if (!entity) {
return false;
}
// TODO: replace with injection
const entries = EntitySettingRegistry.getInstance()
.getItemsForKind(entity.kind, entity.apiVersion, entity.metadata.source);
return entries.length > 0;
},
},
{
id: "cluster.openTerminal",
title: "Cluster: Open terminal",
action: () => createTerminalTab(),
isActive: isKubernetesClusterActive,
},
{
id: "hotbar.switchHotbar",
title: "Hotbar: Switch ...",
action: () => CommandOverlay.open(<HotbarSwitchCommand />),
},
{
id: "hotbar.addHotbar",
title: "Hotbar: Add Hotbar ...",
action: () => CommandOverlay.open(<HotbarAddCommand />),
},
{
id: "hotbar.removeHotbar",
title: "Hotbar: Remove Hotbar ...",
action: () => CommandOverlay.open(<HotbarRemoveCommand />),
},
{
id: "hotbar.renameHotbar",
title: "Hotbar: Rename Hotbar ...",
action: () => CommandOverlay.open(<HotbarRenameCommand />),
},
{
id: "catalog.searchEntities",
title: "Catalog: Activate Entity ...",
action: () => CommandOverlay.open(<ActivateEntityCommand />),
},
];

View File

@ -0,0 +1,70 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { computed, IComputedValue } from "mobx";
import type { CustomResourceDefinition } from "../../../../common/k8s-api/endpoints";
import customResourceDefinitionsInjectable from "../../../../common/k8s-api/endpoints/custom-resources/custom-resources.injectable";
import type { LensRendererExtension } from "../../../../extensions/lens-renderer-extension";
import rendererExtensionsInjectable from "../../../../extensions/renderer-extensions.injectable";
import { iter } from "../../../utils";
import type { RegisteredCommand } from "./commands";
import { internalCommands, isKubernetesClusterActive } from "./internal-commands";
interface Dependencies {
extensions: IComputedValue<LensRendererExtension[]>;
customResourceDefinitions: IComputedValue<CustomResourceDefinition[]>;
}
const instantiateRegisteredCommands = ({ extensions, customResourceDefinitions }: Dependencies) => computed(() => {
const result = new Map<string, RegisteredCommand>();
const commands = iter.chain(
internalCommands,
iter.chain(
iter.flatMap(extensions.get(), extension => extension.commands),
iter.map(customResourceDefinitions.get(), command => ({
id: `cluster.view.${command.getResourceKind()}`,
title: `Cluster: View ${command.getResourceKind()}`,
isActive: isKubernetesClusterActive,
action: ({ navigate }) => navigate(command.getResourceUrl()),
})),
),
);
for (const { scope, isActive = () => true, ...command } of commands) {
if (!result.has(command.id)) {
result.set(command.id, { ...command, isActive });
}
}
return result;
});
const registeredCommandsInjectable = getInjectable({
instantiate: (di) => instantiateRegisteredCommands({
extensions: di.inject(rendererExtensionsInjectable),
customResourceDefinitions: di.inject(customResourceDefinitionsInjectable),
}),
lifecycle: lifecycleEnum.singleton,
});
export default registeredCommandsInjectable;

View File

@ -103,6 +103,10 @@ export class Input extends React.Component<InputProps, State> {
submitted: false, submitted: false,
}; };
componentWillUnmount(): void {
this.setDirtyOnChange.cancel();
}
setValue(value = "") { setValue(value = "") {
if (value !== this.getValue()) { if (value !== this.getValue()) {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(this.input.constructor.prototype, "value").set; const nativeInputValueSetter = Object.getOwnPropertyDescriptor(this.input.constructor.prototype, "value").set;

View File

@ -280,5 +280,5 @@ const addDynamicMenuItem = ({
const kubeObjectMenuRegistry = di.inject(kubeObjectMenuRegistryInjectable); const kubeObjectMenuRegistry = di.inject(kubeObjectMenuRegistryInjectable);
kubeObjectMenuRegistry.add(dynamicMenuItemStub); kubeObjectMenuRegistry.add([dynamicMenuItemStub]);
}; };

View File

@ -24,11 +24,15 @@ import { createContainer } from "@ogre-tools/injectable";
export const getDi = () => export const getDi = () =>
createContainer( createContainer(
getRequireContextForRendererCode, getRequireContextForRendererCode,
getRequireContextForCommonCode,
getRequireContextForCommonExtensionCode, getRequireContextForCommonExtensionCode,
); );
const getRequireContextForRendererCode = () => const getRequireContextForRendererCode = () =>
require.context("../", true, /\.injectable\.(ts|tsx)$/); require.context("./", true, /\.injectable\.(ts|tsx)$/);
const getRequireContextForCommonCode = () =>
require.context("../common", true, /\.injectable\.(ts|tsx)$/);
const getRequireContextForCommonExtensionCode = () => const getRequireContextForCommonExtensionCode = () =>
require.context("../../extensions", true, /\.injectable\.(ts|tsx)$/); require.context("../extensions", true, /\.injectable\.(ts|tsx)$/);

View File

@ -1,207 +0,0 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from "react";
import * as routes from "../../common/routes";
import { CommandRegistry } from "../../extensions/registries";
import { getActiveClusterEntity } from "../api/catalog-entity-registry";
import { CommandOverlay } from "../components/command-palette";
import { createTerminalTab } from "../components/dock/terminal.store";
import { HotbarAddCommand } from "../components/hotbar/hotbar-add-command";
import { HotbarRemoveCommand } from "../components/hotbar/hotbar-remove-command";
import { HotbarSwitchCommand } from "../components/hotbar/hotbar-switch-command";
import { navigate } from "../navigation";
import { HotbarRenameCommand } from "../components/hotbar/hotbar-rename-command";
import { ActivateEntityCommand } from "../components/activate-entity-command";
export function initCommandRegistry() {
CommandRegistry.getInstance()
.add([
{
id: "app.showPreferences",
title: "Preferences: Open",
scope: "global",
action: () => navigate(routes.preferencesURL()),
},
{
id: "cluster.viewHelmCharts",
title: "Cluster: View Helm Charts",
scope: "entity",
action: () => navigate(routes.helmChartsURL()),
},
{
id: "cluster.viewHelmReleases",
title: "Cluster: View Helm Releases",
scope: "entity",
action: () => navigate(routes.releaseURL()),
},
{
id: "cluster.viewConfigMaps",
title: "Cluster: View ConfigMaps",
scope: "entity",
action: () => navigate(routes.configMapsURL()),
},
{
id: "cluster.viewSecrets",
title: "Cluster: View Secrets",
scope: "entity",
action: () => navigate(routes.secretsURL()),
},
{
id: "cluster.viewResourceQuotas",
title: "Cluster: View ResourceQuotas",
scope: "entity",
action: () => navigate(routes.resourceQuotaURL()),
},
{
id: "cluster.viewLimitRanges",
title: "Cluster: View LimitRanges",
scope: "entity",
action: () => navigate(routes.limitRangeURL()),
},
{
id: "cluster.viewHorizontalPodAutoscalers",
title: "Cluster: View HorizontalPodAutoscalers (HPA)",
scope: "entity",
action: () => navigate(routes.hpaURL()),
},
{
id: "cluster.viewPodDisruptionBudget",
title: "Cluster: View PodDisruptionBudgets",
scope: "entity",
action: () => navigate(routes.pdbURL()),
},
{
id: "cluster.viewServices",
title: "Cluster: View Services",
scope: "entity",
action: () => navigate(routes.servicesURL()),
},
{
id: "cluster.viewEndpoints",
title: "Cluster: View Endpoints",
scope: "entity",
action: () => navigate(routes.endpointURL()),
},
{
id: "cluster.viewIngresses",
title: "Cluster: View Ingresses",
scope: "entity",
action: () => navigate(routes.ingressURL()),
},
{
id: "cluster.viewNetworkPolicies",
title: "Cluster: View NetworkPolicies",
scope: "entity",
action: () => navigate(routes.networkPoliciesURL()),
},
{
id: "cluster.viewNodes",
title: "Cluster: View Nodes",
scope: "entity",
action: () => navigate(routes.nodesURL()),
},
{
id: "cluster.viewPods",
title: "Cluster: View Pods",
scope: "entity",
action: () => navigate(routes.podsURL()),
},
{
id: "cluster.viewDeployments",
title: "Cluster: View Deployments",
scope: "entity",
action: () => navigate(routes.deploymentsURL()),
},
{
id: "cluster.viewDaemonSets",
title: "Cluster: View DaemonSets",
scope: "entity",
action: () => navigate(routes.daemonSetsURL()),
},
{
id: "cluster.viewStatefulSets",
title: "Cluster: View StatefulSets",
scope: "entity",
action: () => navigate(routes.statefulSetsURL()),
},
{
id: "cluster.viewJobs",
title: "Cluster: View Jobs",
scope: "entity",
action: () => navigate(routes.jobsURL()),
},
{
id: "cluster.viewCronJobs",
title: "Cluster: View CronJobs",
scope: "entity",
action: () => navigate(routes.cronJobsURL()),
},
{
id: "cluster.viewCurrentClusterSettings",
title: "Cluster: View Settings",
scope: "global",
action: () => navigate(routes.entitySettingsURL({
params: {
entityId: getActiveClusterEntity()?.id,
},
})),
isActive: (context) => !!context.entity,
},
{
id: "cluster.openTerminal",
title: "Cluster: Open terminal",
scope: "entity",
action: () => createTerminalTab(),
isActive: (context) => !!context.entity,
},
{
id: "hotbar.switchHotbar",
title: "Hotbar: Switch ...",
scope: "global",
action: () => CommandOverlay.open(<HotbarSwitchCommand />),
},
{
id: "hotbar.addHotbar",
title: "Hotbar: Add Hotbar ...",
scope: "global",
action: () => CommandOverlay.open(<HotbarAddCommand />),
},
{
id: "hotbar.removeHotbar",
title: "Hotbar: Remove Hotbar ...",
scope: "global",
action: () => CommandOverlay.open(<HotbarRemoveCommand />),
},
{
id: "hotbar.renameHotbar",
title: "Hotbar: Rename Hotbar ...",
scope: "global",
action: () => CommandOverlay.open(<HotbarRenameCommand />),
},
{
id: "catalog.searchEntities",
title: "Catalog: Activate Entity ...",
scope: "global",
action: () => CommandOverlay.open(<ActivateEntityCommand />),
},
]);
}

View File

@ -21,7 +21,6 @@
export * from "./catalog-entity-detail-registry"; export * from "./catalog-entity-detail-registry";
export * from "./catalog"; export * from "./catalog";
export * from "./command-registry";
export * from "./entity-settings-registry"; export * from "./entity-settings-registry";
export * from "./ipc"; export * from "./ipc";
export * from "./kube-object-detail-registry"; export * from "./kube-object-detail-registry";

View File

@ -26,7 +26,6 @@ export function initRegistries() {
registries.CatalogEntityDetailRegistry.createInstance(); registries.CatalogEntityDetailRegistry.createInstance();
registries.ClusterPageMenuRegistry.createInstance(); registries.ClusterPageMenuRegistry.createInstance();
registries.ClusterPageRegistry.createInstance(); registries.ClusterPageRegistry.createInstance();
registries.CommandRegistry.createInstance();
registries.EntitySettingRegistry.createInstance(); registries.EntitySettingRegistry.createInstance();
registries.GlobalPageRegistry.createInstance(); registries.GlobalPageRegistry.createInstance();
registries.KubeObjectDetailRegistry.createInstance(); registries.KubeObjectDetailRegistry.createInstance();

View File

@ -54,7 +54,7 @@ export function isActiveRoute(route: string | string[] | RouteProps): boolean {
return !!matchRoute(route); return !!matchRoute(route);
} }
export function getMatchedClusterId(): string { export function getMatchedClusterId(): string | undefined {
const matched = matchPath<ClusterViewRouteParams>(navigation.location.pathname, { const matched = matchPath<ClusterViewRouteParams>(navigation.location.pathname, {
exact: true, exact: true,
path: clusterViewRoute.path, path: clusterViewRoute.path,