mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge pull request #4527 from jansav/make-menu-registry-obsolete
Remove MenuRegistry in favour of dependency injection
This commit is contained in:
75 files changed
+2597
-886
No files matched your search
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 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 { createContainer } from "@ogre-tools/injectable";
|
||||
|
||||
export const getDi = () =>
|
||||
createContainer(
|
||||
getRequireContextForMainCode,
|
||||
getRequireContextForCommonExtensionCode,
|
||||
);
|
||||
|
||||
const getRequireContextForMainCode = () =>
|
||||
require.context("./", true, /\.injectable\.(ts|tsx)$/);
|
||||
|
||||
const getRequireContextForCommonExtensionCode = () =>
|
||||
require.context("../extensions", true, /\.injectable\.(ts|tsx)$/);
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 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 glob from "glob";
|
||||
import { memoize } from "lodash/fp";
|
||||
|
||||
import {
|
||||
createContainer,
|
||||
ConfigurableDependencyInjectionContainer,
|
||||
} from "@ogre-tools/injectable";
|
||||
|
||||
export const getDiForUnitTesting = () => {
|
||||
const di: ConfigurableDependencyInjectionContainer = createContainer();
|
||||
|
||||
getInjectableFilePaths()
|
||||
.map(key => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const injectable = require(key).default;
|
||||
|
||||
return {
|
||||
id: key,
|
||||
...injectable,
|
||||
aliases: [injectable, ...(injectable.aliases || [])],
|
||||
};
|
||||
})
|
||||
|
||||
.forEach(injectable => di.register(injectable));
|
||||
|
||||
di.preventSideEffects();
|
||||
|
||||
return di;
|
||||
};
|
||||
|
||||
const getInjectableFilePaths = memoize(() => [
|
||||
...glob.sync("./**/*.injectable.{ts,tsx}", { cwd: __dirname }),
|
||||
...glob.sync("../extensions/**/*.injectable.{ts,tsx}", { cwd: __dirname }),
|
||||
]);
|
||||
+30
-27
@@ -36,11 +36,9 @@ import { mangleProxyEnv } from "./proxy-env";
|
||||
import { registerFileProtocol } from "../common/register-protocol";
|
||||
import logger from "./logger";
|
||||
import { appEventBus } from "../common/event-bus";
|
||||
import { ExtensionLoader } from "../extensions/extension-loader";
|
||||
import { InstalledExtension, ExtensionDiscovery } from "../extensions/extension-discovery";
|
||||
import type { LensExtensionId } from "../extensions/lens-extension";
|
||||
import { installDeveloperTools } from "./developer-tools";
|
||||
import { LensProtocolRouterMain } from "./protocol-handler";
|
||||
import { disposer, getAppVersion, getAppVersionFromProxyServer, storedKubeConfigFolder } from "../common/utils";
|
||||
import { bindBroadcastHandlers, ipcMainOn } from "../common/ipc";
|
||||
import { startUpdateChecking } from "./app-updater";
|
||||
@@ -61,11 +59,17 @@ import { FilesystemProvisionerStore } from "./extension-filesystem";
|
||||
import { SentryInit } from "../common/sentry";
|
||||
import { ensureDir } from "fs-extra";
|
||||
import { Router } from "./router";
|
||||
import { initMenu } from "./menu";
|
||||
import { initMenu } from "./menu/menu";
|
||||
import { initTray } from "./tray";
|
||||
import { kubeApiRequest, shellApiRequest, ShellRequestAuthenticator } from "./proxy-functions";
|
||||
import { AppPaths } from "../common/app-paths";
|
||||
import { ShellSession } from "./shell-session/shell-session";
|
||||
import { getDi } from "./getDi";
|
||||
import electronMenuItemsInjectable from "./menu/electron-menu-items.injectable";
|
||||
import extensionLoaderInjectable from "../extensions/extension-loader/extension-loader.injectable";
|
||||
import lensProtocolRouterMainInjectable from "./protocol-handler/lens-protocol-router-main/lens-protocol-router-main.injectable";
|
||||
|
||||
const di = getDi();
|
||||
|
||||
injectSystemCAs();
|
||||
|
||||
@@ -75,7 +79,6 @@ const onQuitCleanup = disposer();
|
||||
SentryInit();
|
||||
app.setName(appName);
|
||||
|
||||
|
||||
logger.info(`📟 Setting ${productName} as protocol client for lens://`);
|
||||
|
||||
if (app.setAsDefaultProtocolClient("lens")) {
|
||||
@@ -99,7 +102,10 @@ configurePackages();
|
||||
mangleProxyEnv();
|
||||
|
||||
logger.debug("[APP-MAIN] initializing ipc main handlers");
|
||||
initializers.initIpcMainHandlers();
|
||||
|
||||
const menuItems = di.inject(electronMenuItemsInjectable);
|
||||
|
||||
initializers.initIpcMainHandlers(menuItems);
|
||||
|
||||
if (app.commandLine.getSwitchValue("proxy-server") !== "") {
|
||||
process.env.HTTPS_PROXY = app.commandLine.getSwitchValue("proxy-server");
|
||||
@@ -107,14 +113,14 @@ if (app.commandLine.getSwitchValue("proxy-server") !== "") {
|
||||
|
||||
logger.debug("[APP-MAIN] Lens protocol routing main");
|
||||
|
||||
const lensProtocolRouterMain = di.inject(lensProtocolRouterMainInjectable);
|
||||
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.exit();
|
||||
} else {
|
||||
const lprm = LensProtocolRouterMain.createInstance();
|
||||
|
||||
for (const arg of process.argv) {
|
||||
if (arg.toLowerCase().startsWith("lens://")) {
|
||||
lprm.route(arg);
|
||||
lensProtocolRouterMain.route(arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -122,11 +128,9 @@ if (!app.requestSingleInstanceLock()) {
|
||||
app.on("second-instance", (event, argv) => {
|
||||
logger.debug("second-instance message");
|
||||
|
||||
const lprm = LensProtocolRouterMain.createInstance();
|
||||
|
||||
for (const arg of argv) {
|
||||
if (arg.toLowerCase().startsWith("lens://")) {
|
||||
lprm.route(arg);
|
||||
lensProtocolRouterMain.route(arg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,10 +227,12 @@ app.on("ready", async () => {
|
||||
return app.exit();
|
||||
}
|
||||
|
||||
initializers.initRegistries();
|
||||
const extensionDiscovery = ExtensionDiscovery.createInstance();
|
||||
const extensionLoader = di.inject(extensionLoaderInjectable);
|
||||
|
||||
extensionLoader.init();
|
||||
|
||||
const extensionDiscovery = ExtensionDiscovery.createInstance(extensionLoader);
|
||||
|
||||
ExtensionLoader.createInstance().init();
|
||||
extensionDiscovery.init();
|
||||
|
||||
// Start the app without showing the main window when auto starting on login
|
||||
@@ -237,7 +243,7 @@ app.on("ready", async () => {
|
||||
const windowManager = WindowManager.createInstance();
|
||||
|
||||
onQuitCleanup.push(
|
||||
initMenu(windowManager),
|
||||
initMenu(windowManager, menuItems),
|
||||
initTray(windowManager),
|
||||
() => ShellSession.cleanup(),
|
||||
);
|
||||
@@ -253,7 +259,7 @@ app.on("ready", async () => {
|
||||
await ensureDir(storedKubeConfigFolder());
|
||||
KubeconfigSyncManager.getInstance().startSync();
|
||||
startUpdateChecking();
|
||||
LensProtocolRouterMain.getInstance().rendererLoaded = true;
|
||||
lensProtocolRouterMain.rendererLoaded = true;
|
||||
});
|
||||
|
||||
logger.info("🧩 Initializing extensions");
|
||||
@@ -268,13 +274,13 @@ app.on("ready", async () => {
|
||||
// Subscribe to extensions that are copied or deleted to/from the extensions folder
|
||||
extensionDiscovery.events
|
||||
.on("add", (extension: InstalledExtension) => {
|
||||
ExtensionLoader.getInstance().addExtension(extension);
|
||||
extensionLoader.addExtension(extension);
|
||||
})
|
||||
.on("remove", (lensExtensionId: LensExtensionId) => {
|
||||
ExtensionLoader.getInstance().removeExtension(lensExtensionId);
|
||||
extensionLoader.removeExtension(lensExtensionId);
|
||||
});
|
||||
|
||||
ExtensionLoader.getInstance().initExtensions(extensions);
|
||||
extensionLoader.initExtensions(extensions);
|
||||
} catch (error) {
|
||||
dialog.showErrorBox("Lens Error", `Could not load extensions${error?.message ? `: ${error.message}` : ""}`);
|
||||
console.error(error);
|
||||
@@ -309,7 +315,6 @@ app.on("will-quit", (event) => {
|
||||
|
||||
// This is called when the close button of the main window is clicked
|
||||
|
||||
const lprm = LensProtocolRouterMain.getInstance(false);
|
||||
|
||||
logger.info("APP:QUIT");
|
||||
appEventBus.emit({ name: "app", action: "close" });
|
||||
@@ -317,11 +322,9 @@ app.on("will-quit", (event) => {
|
||||
KubeconfigSyncManager.getInstance(false)?.stopSync();
|
||||
onCloseCleanup();
|
||||
|
||||
if (lprm) {
|
||||
// This is set to false here so that LPRM can wait to send future lens://
|
||||
// requests until after it loads again
|
||||
lprm.rendererLoaded = false;
|
||||
}
|
||||
// This is set to false here so that LPRM can wait to send future lens://
|
||||
// requests until after it loads again
|
||||
lensProtocolRouterMain.rendererLoaded = false;
|
||||
|
||||
if (blockQuit) {
|
||||
// Quit app on Cmd+Q (MacOS)
|
||||
@@ -331,7 +334,7 @@ app.on("will-quit", (event) => {
|
||||
return; // skip exit to make tray work, to quit go to app's global menu or tray's menu
|
||||
}
|
||||
|
||||
lprm?.cleanup();
|
||||
lensProtocolRouterMain.cleanup();
|
||||
onQuitCleanup();
|
||||
});
|
||||
|
||||
@@ -340,7 +343,7 @@ app.on("open-url", (event, rawUrl) => {
|
||||
|
||||
// lens:// protocol handler
|
||||
event.preventDefault();
|
||||
LensProtocolRouterMain.getInstance().route(rawUrl);
|
||||
lensProtocolRouterMain.route(rawUrl);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -18,8 +18,6 @@
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export * from "./registries";
|
||||
export * from "./metrics-providers";
|
||||
export * from "./ipc";
|
||||
export * from "./cluster-metadata-detectors";
|
||||
@@ -34,9 +34,11 @@ import { IpcMainWindowEvents, WindowManager } from "../window-manager";
|
||||
import path from "path";
|
||||
import { remove } from "fs-extra";
|
||||
import { AppPaths } from "../../common/app-paths";
|
||||
import { getAppMenu } from "../menu";
|
||||
import { getAppMenu } from "../menu/menu";
|
||||
import type { MenuRegistration } from "../menu/menu-registration";
|
||||
import type { IComputedValue } from "mobx";
|
||||
|
||||
export function initIpcMainHandlers() {
|
||||
export function initIpcMainHandlers(electronMenuItems: IComputedValue<MenuRegistration[]>) {
|
||||
ipcMainHandle(clusterActivateHandler, (event, clusterId: ClusterId, force = false) => {
|
||||
return ClusterStore.getInstance()
|
||||
.getById(clusterId)
|
||||
@@ -151,7 +153,7 @@ export function initIpcMainHandlers() {
|
||||
});
|
||||
|
||||
ipcMainOn(IpcMainWindowEvents.OPEN_CONTEXT_MENU, async (event) => {
|
||||
const menu = Menu.buildFromTemplate(getAppMenu(WindowManager.getInstance()));
|
||||
const menu = Menu.buildFromTemplate(getAppMenu(WindowManager.getInstance(), electronMenuItems.get()));
|
||||
const options = {
|
||||
...BrowserWindow.fromWebContents(event.sender),
|
||||
// Center of the topbar menu icon
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 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 { Injectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { computed, IComputedValue } from "mobx";
|
||||
import type { LensMainExtension } from "../../extensions/lens-main-extension";
|
||||
import extensionsInjectable from "../../extensions/extensions.injectable";
|
||||
import type { MenuRegistration } from "./menu-registration";
|
||||
|
||||
const electronMenuItemsInjectable: Injectable<
|
||||
IComputedValue<MenuRegistration[]>,
|
||||
{ extensions: IComputedValue<LensMainExtension[]> }
|
||||
> = {
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
|
||||
getDependencies: di => ({
|
||||
extensions: di.inject(extensionsInjectable),
|
||||
}),
|
||||
|
||||
instantiate: ({ extensions }) =>
|
||||
computed(() => extensions.get().flatMap(extension => extension.appMenus)),
|
||||
};
|
||||
|
||||
export default electronMenuItemsInjectable;
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* 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 type { ConfigurableDependencyInjectionContainer } from "@ogre-tools/injectable";
|
||||
import { LensMainExtension } from "../../extensions/lens-main-extension";
|
||||
import electronMenuItemsInjectable from "./electron-menu-items.injectable";
|
||||
import type { IComputedValue } from "mobx";
|
||||
import { computed, ObservableMap, runInAction } from "mobx";
|
||||
import type { MenuRegistration } from "./menu-registration";
|
||||
import extensionsInjectable from "../../extensions/extensions.injectable";
|
||||
import { getDiForUnitTesting } from "../getDiForUnitTesting";
|
||||
|
||||
describe("electron-menu-items", () => {
|
||||
let di: ConfigurableDependencyInjectionContainer;
|
||||
let electronMenuItems: IComputedValue<MenuRegistration[]>;
|
||||
let extensionsStub: ObservableMap<string, LensMainExtension>;
|
||||
|
||||
beforeEach(() => {
|
||||
di = getDiForUnitTesting();
|
||||
|
||||
extensionsStub = new ObservableMap();
|
||||
|
||||
di.override(
|
||||
extensionsInjectable,
|
||||
computed(() => [...extensionsStub.values()]),
|
||||
);
|
||||
|
||||
electronMenuItems = di.inject(electronMenuItemsInjectable);
|
||||
});
|
||||
|
||||
it("does not have any items yet", () => {
|
||||
expect(electronMenuItems.get()).toHaveLength(0);
|
||||
});
|
||||
|
||||
describe("when extension is enabled", () => {
|
||||
beforeEach(() => {
|
||||
const someExtension = new SomeTestExtension({
|
||||
id: "some-extension-id",
|
||||
appMenus: [{ parentId: "some-parent-id-from-first-extension" }],
|
||||
});
|
||||
|
||||
runInAction(() => {
|
||||
extensionsStub.set("some-extension-id", someExtension);
|
||||
});
|
||||
});
|
||||
|
||||
it("has menu items", () => {
|
||||
expect(electronMenuItems.get()).toEqual([
|
||||
{
|
||||
parentId: "some-parent-id-from-first-extension",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("when disabling extension, does not have menu items", () => {
|
||||
extensionsStub.delete("some-extension-id");
|
||||
|
||||
expect(electronMenuItems.get()).toHaveLength(0);
|
||||
});
|
||||
|
||||
describe("when other extension is enabled", () => {
|
||||
beforeEach(() => {
|
||||
const someOtherExtension = new SomeTestExtension({
|
||||
id: "some-extension-id",
|
||||
appMenus: [{ parentId: "some-parent-id-from-second-extension" }],
|
||||
});
|
||||
|
||||
extensionsStub.set("some-other-extension-id", someOtherExtension);
|
||||
});
|
||||
|
||||
it("has menu items for both extensions", () => {
|
||||
expect(electronMenuItems.get()).toEqual([
|
||||
{
|
||||
parentId: "some-parent-id-from-first-extension",
|
||||
},
|
||||
|
||||
{
|
||||
parentId: "some-parent-id-from-second-extension",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("when extension is disabled, still returns menu items for extensions that are enabled", () => {
|
||||
runInAction(() => {
|
||||
extensionsStub.delete("some-other-extension-id");
|
||||
});
|
||||
|
||||
expect(electronMenuItems.get()).toEqual([
|
||||
{
|
||||
parentId: "some-parent-id-from-first-extension",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class SomeTestExtension extends LensMainExtension {
|
||||
constructor({ id, appMenus }: {
|
||||
id: string;
|
||||
appMenus: MenuRegistration[];
|
||||
}) {
|
||||
super({
|
||||
id,
|
||||
absolutePath: "irrelevant",
|
||||
isBundled: false,
|
||||
isCompatible: false,
|
||||
isEnabled: false,
|
||||
manifest: { name: id, version: "some-version" },
|
||||
manifestPath: "irrelevant",
|
||||
});
|
||||
|
||||
this.appMenus = appMenus;
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,8 @@
|
||||
* 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 type { MenuItemConstructorOptions } from "electron";
|
||||
|
||||
import * as registries from "../../extensions/registries";
|
||||
|
||||
export function initRegistries() {
|
||||
registries.MenuRegistry.createInstance();
|
||||
export interface MenuRegistration extends MenuItemConstructorOptions {
|
||||
parentId: string;
|
||||
}
|
||||
@@ -18,18 +18,17 @@
|
||||
* 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 { app, BrowserWindow, dialog, Menu, MenuItem, MenuItemConstructorOptions, webContents, shell } from "electron";
|
||||
import { autorun } from "mobx";
|
||||
import type { WindowManager } from "./window-manager";
|
||||
import { appName, isMac, isWindows, docsUrl, supportUrl, productName } from "../common/vars";
|
||||
import { MenuRegistry } from "../extensions/registries/menu-registry";
|
||||
import logger from "./logger";
|
||||
import { exitApp } from "./exit-app";
|
||||
import { broadcastMessage } from "../common/ipc";
|
||||
import * as packageJson from "../../package.json";
|
||||
import { preferencesURL, extensionsURL, addClusterURL, catalogURL, welcomeURL } from "../common/routes";
|
||||
import { checkForUpdates, isAutoUpdateEnabled } from "./app-updater";
|
||||
import { autorun, IComputedValue } from "mobx";
|
||||
import type { WindowManager } from "../window-manager";
|
||||
import { appName, isMac, isWindows, docsUrl, supportUrl, productName } from "../../common/vars";
|
||||
import logger from "../logger";
|
||||
import { exitApp } from "../exit-app";
|
||||
import { broadcastMessage } from "../../common/ipc";
|
||||
import * as packageJson from "../../../package.json";
|
||||
import { preferencesURL, extensionsURL, addClusterURL, catalogURL, welcomeURL } from "../../common/routes";
|
||||
import { checkForUpdates, isAutoUpdateEnabled } from "../app-updater";
|
||||
import type { MenuRegistration } from "./menu-registration";
|
||||
|
||||
export type MenuTopId = "mac" | "file" | "edit" | "view" | "help";
|
||||
|
||||
@@ -37,8 +36,11 @@ interface MenuItemsOpts extends MenuItemConstructorOptions {
|
||||
submenu?: MenuItemConstructorOptions[];
|
||||
}
|
||||
|
||||
export function initMenu(windowManager: WindowManager) {
|
||||
return autorun(() => buildMenu(windowManager), {
|
||||
export function initMenu(
|
||||
windowManager: WindowManager,
|
||||
electronMenuItems: IComputedValue<MenuRegistration[]>,
|
||||
) {
|
||||
return autorun(() => buildMenu(windowManager, electronMenuItems.get()), {
|
||||
delay: 100,
|
||||
});
|
||||
}
|
||||
@@ -61,7 +63,10 @@ export function showAbout(browserWindow: BrowserWindow) {
|
||||
});
|
||||
}
|
||||
|
||||
export function getAppMenu(windowManager: WindowManager) {
|
||||
export function getAppMenu(
|
||||
windowManager: WindowManager,
|
||||
electronMenuItems: MenuRegistration[],
|
||||
) {
|
||||
function ignoreIf(check: boolean, menuItems: MenuItemConstructorOptions[]) {
|
||||
return check ? [] : menuItems;
|
||||
}
|
||||
@@ -302,14 +307,17 @@ export function getAppMenu(windowManager: WindowManager) {
|
||||
]);
|
||||
|
||||
// Modify menu from extensions-api
|
||||
for (const { parentId, ...menuItem } of MenuRegistry.getInstance().getItems()) {
|
||||
if (!appMenu.has(parentId)) {
|
||||
logger.error(`[MENU]: cannot register menu item for parentId=${parentId}, parent item doesn't exist`, { menuItem });
|
||||
for (const menuItem of electronMenuItems) {
|
||||
if (!appMenu.has(menuItem.parentId)) {
|
||||
logger.error(
|
||||
`[MENU]: cannot register menu item for parentId=${menuItem.parentId}, parent item doesn't exist`,
|
||||
{ menuItem },
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
appMenu.get(parentId).submenu.push(menuItem);
|
||||
appMenu.get(menuItem.parentId).submenu.push(menuItem);
|
||||
}
|
||||
|
||||
if (!isMac) {
|
||||
@@ -320,6 +328,11 @@ export function getAppMenu(windowManager: WindowManager) {
|
||||
|
||||
}
|
||||
|
||||
export function buildMenu(windowManager: WindowManager) {
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(getAppMenu(windowManager)));
|
||||
export function buildMenu(
|
||||
windowManager: WindowManager,
|
||||
electronMenuItems: MenuRegistration[],
|
||||
) {
|
||||
Menu.setApplicationMenu(
|
||||
Menu.buildFromTemplate(getAppMenu(windowManager, electronMenuItems)),
|
||||
);
|
||||
}
|
||||
@@ -25,11 +25,15 @@ import { broadcastMessage } from "../../../common/ipc";
|
||||
import { ProtocolHandlerExtension, ProtocolHandlerInternal } from "../../../common/protocol-handler";
|
||||
import { delay, noop } from "../../../common/utils";
|
||||
import { LensExtension } from "../../../extensions/main-api";
|
||||
import { ExtensionLoader } from "../../../extensions/extension-loader";
|
||||
import { ExtensionsStore } from "../../../extensions/extensions-store";
|
||||
import { LensProtocolRouterMain } from "../router";
|
||||
import type { LensProtocolRouterMain } from "../lens-protocol-router-main/lens-protocol-router-main";
|
||||
import mockFs from "mock-fs";
|
||||
import { AppPaths } from "../../../common/app-paths";
|
||||
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
|
||||
import extensionLoaderInjectable
|
||||
from "../../../extensions/extension-loader/extension-loader.injectable";
|
||||
import lensProtocolRouterMainInjectable
|
||||
from "../lens-protocol-router-main/lens-protocol-router-main.injectable";
|
||||
|
||||
jest.mock("../../../common/ipc");
|
||||
|
||||
@@ -58,14 +62,22 @@ function throwIfDefined(val: any): void {
|
||||
}
|
||||
|
||||
describe("protocol router tests", () => {
|
||||
// TODO: This test suite is using any to access protected property.
|
||||
// Unit tests are allowed to only public interfaces.
|
||||
let extensionLoader: any;
|
||||
let lpr: LensProtocolRouterMain;
|
||||
|
||||
beforeEach(() => {
|
||||
const di = getDiForUnitTesting();
|
||||
|
||||
extensionLoader = di.inject(extensionLoaderInjectable);
|
||||
|
||||
mockFs({
|
||||
"tmp": {},
|
||||
});
|
||||
ExtensionsStore.createInstance();
|
||||
ExtensionLoader.createInstance();
|
||||
|
||||
const lpr = LensProtocolRouterMain.createInstance();
|
||||
lpr = di.inject(lensProtocolRouterMainInjectable);
|
||||
|
||||
lpr.rendererLoaded = true;
|
||||
});
|
||||
@@ -74,15 +86,11 @@ describe("protocol router tests", () => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
ExtensionsStore.resetInstance();
|
||||
ExtensionLoader.resetInstance();
|
||||
LensProtocolRouterMain.resetInstance();
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("should throw on non-lens URLS", async () => {
|
||||
try {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
|
||||
expect(await lpr.route("https://google.ca")).toBeUndefined();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
@@ -91,8 +99,6 @@ describe("protocol router tests", () => {
|
||||
|
||||
it("should throw when host not internal or extension", async () => {
|
||||
try {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
|
||||
expect(await lpr.route("lens://foobar")).toBeUndefined();
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
@@ -113,14 +119,13 @@ describe("protocol router tests", () => {
|
||||
isCompatible: true,
|
||||
absolutePath: "/foo/bar",
|
||||
});
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
|
||||
ext.protocolHandlers.push({
|
||||
pathSchema: "/",
|
||||
handler: noop,
|
||||
});
|
||||
|
||||
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
|
||||
extensionLoader.instances.set(extId, ext);
|
||||
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@mirantis/minikube" });
|
||||
|
||||
lpr.addInternalHandler("/", noop);
|
||||
@@ -143,7 +148,6 @@ describe("protocol router tests", () => {
|
||||
});
|
||||
|
||||
it("should call handler if matches", async () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
let called = false;
|
||||
|
||||
lpr.addInternalHandler("/page", () => { called = true; });
|
||||
@@ -159,7 +163,6 @@ describe("protocol router tests", () => {
|
||||
});
|
||||
|
||||
it("should call most exact handler", async () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
let called: any = 0;
|
||||
|
||||
lpr.addInternalHandler("/page", () => { called = 1; });
|
||||
@@ -178,7 +181,6 @@ describe("protocol router tests", () => {
|
||||
it("should call most exact handler for an extension", async () => {
|
||||
let called: any = 0;
|
||||
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
const extId = uuid.v4();
|
||||
const ext = new LensExtension({
|
||||
id: extId,
|
||||
@@ -202,7 +204,7 @@ describe("protocol router tests", () => {
|
||||
handler: params => { called = params.pathname.id; },
|
||||
});
|
||||
|
||||
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
|
||||
extensionLoader.instances.set(extId, ext);
|
||||
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@foobar/icecream" });
|
||||
|
||||
try {
|
||||
@@ -217,7 +219,6 @@ describe("protocol router tests", () => {
|
||||
});
|
||||
|
||||
it("should work with non-org extensions", async () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
let called: any = 0;
|
||||
|
||||
{
|
||||
@@ -241,7 +242,7 @@ describe("protocol router tests", () => {
|
||||
handler: params => { called = params.pathname.id; },
|
||||
});
|
||||
|
||||
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
|
||||
extensionLoader.instances.set(extId, ext);
|
||||
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "@foobar/icecream" });
|
||||
}
|
||||
|
||||
@@ -266,7 +267,7 @@ describe("protocol router tests", () => {
|
||||
handler: () => { called = 1; },
|
||||
});
|
||||
|
||||
(ExtensionLoader.getInstance() as any).instances.set(extId, ext);
|
||||
extensionLoader.instances.set(extId, ext);
|
||||
(ExtensionsStore.getInstance() as any).state.set(extId, { enabled: true, name: "icecream" });
|
||||
}
|
||||
|
||||
@@ -286,13 +287,10 @@ describe("protocol router tests", () => {
|
||||
});
|
||||
|
||||
it("should throw if urlSchema is invalid", () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
|
||||
expect(() => lpr.addInternalHandler("/:@", noop)).toThrowError();
|
||||
});
|
||||
|
||||
it("should call most exact handler with 3 found handlers", async () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
let called: any = 0;
|
||||
|
||||
lpr.addInternalHandler("/", () => { called = 2; });
|
||||
@@ -311,7 +309,6 @@ describe("protocol router tests", () => {
|
||||
});
|
||||
|
||||
it("should call most exact handler with 2 found handlers", async () => {
|
||||
const lpr = LensProtocolRouterMain.getInstance();
|
||||
let called: any = 0;
|
||||
|
||||
lpr.addInternalHandler("/", () => { called = 2; });
|
||||
|
||||
@@ -19,4 +19,4 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
export * from "./router";
|
||||
export * from "./lens-protocol-router-main/lens-protocol-router-main";
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 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 type { Injectable } from "@ogre-tools/injectable";
|
||||
import { lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import extensionLoaderInjectable from "../../../extensions/extension-loader/extension-loader.injectable";
|
||||
import type { Dependencies } from "./lens-protocol-router-main";
|
||||
import { LensProtocolRouterMain } from "./lens-protocol-router-main";
|
||||
|
||||
const lensProtocolRouterMainInjectable: Injectable<
|
||||
LensProtocolRouterMain,
|
||||
Dependencies
|
||||
> = {
|
||||
getDependencies: di => ({
|
||||
extensionLoader: di.inject(extensionLoaderInjectable),
|
||||
}),
|
||||
|
||||
instantiate: dependencies => new LensProtocolRouterMain(dependencies),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
};
|
||||
|
||||
export default lensProtocolRouterMainInjectable;
|
||||
+14
-9
@@ -19,15 +19,16 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import logger from "../logger";
|
||||
import * as proto from "../../common/protocol-handler";
|
||||
import logger from "../../logger";
|
||||
import * as proto from "../../../common/protocol-handler";
|
||||
import URLParse from "url-parse";
|
||||
import type { LensExtension } from "../../extensions/lens-extension";
|
||||
import { broadcastMessage } from "../../common/ipc";
|
||||
import type { LensExtension } from "../../../extensions/lens-extension";
|
||||
import { broadcastMessage } from "../../../common/ipc";
|
||||
import { observable, when, makeObservable } from "mobx";
|
||||
import { ProtocolHandlerInvalid, RouteAttempt } from "../../common/protocol-handler";
|
||||
import { disposer, noop } from "../../common/utils";
|
||||
import { WindowManager } from "../window-manager";
|
||||
import { ProtocolHandlerInvalid, RouteAttempt } from "../../../common/protocol-handler";
|
||||
import { disposer, noop } from "../../../common/utils";
|
||||
import { WindowManager } from "../../window-manager";
|
||||
import type { ExtensionLoader } from "../../../extensions/extension-loader";
|
||||
|
||||
export interface FallbackHandler {
|
||||
(name: string): Promise<boolean>;
|
||||
@@ -50,6 +51,10 @@ function checkHost<Query>(url: URLParse<Query>): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export interface Dependencies {
|
||||
extensionLoader: ExtensionLoader
|
||||
}
|
||||
|
||||
export class LensProtocolRouterMain extends proto.LensProtocolRouter {
|
||||
private missingExtensionHandlers: FallbackHandler[] = [];
|
||||
|
||||
@@ -57,8 +62,8 @@ export class LensProtocolRouterMain extends proto.LensProtocolRouter {
|
||||
|
||||
protected disposers = disposer();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
constructor(protected dependencies: Dependencies) {
|
||||
super(dependencies);
|
||||
|
||||
makeObservable(this);
|
||||
}
|
||||
+1
-1
@@ -23,7 +23,7 @@ import path from "path";
|
||||
import packageInfo from "../../package.json";
|
||||
import { Menu, Tray } from "electron";
|
||||
import { autorun } from "mobx";
|
||||
import { showAbout } from "./menu";
|
||||
import { showAbout } from "./menu/menu";
|
||||
import { checkForUpdates, isAutoUpdateEnabled } from "./app-updater";
|
||||
import type { WindowManager } from "./window-manager";
|
||||
import logger from "./logger";
|
||||
|
||||
Reference in new issue
Block a user