Merge branch 'master' into hotbar-commands-and-navigate

This commit is contained in:
Jari Kolehmainen authored and GitHub committed 2021-04-20 10:11:36 +03:00
commit 241b726e37
94 files changed
+1342 -745

No files matched your search

+16 -6
View File
@@ -3,6 +3,9 @@ import mockFs from "mock-fs";
import yaml from "js-yaml";
import { Cluster } from "../../main/cluster";
import { ClusterStore, getClusterIdFromHost } from "../cluster-store";
import { Console } from "console";
console = new Console(process.stdout, process.stderr); // fix mockFS
const testDataIcon = fs.readFileSync("test-data/cluster-store-migration-icon.png");
const kubeconfig = `
@@ -292,6 +295,13 @@ users:
});
});
const minimalValidKubeConfig = JSON.stringify({
apiVersion: "v1",
clusters: [],
users: [],
contexts: [],
});
describe("pre 2.0 config with an existing cluster", () => {
beforeEach(() => {
ClusterStore.resetInstance();
@@ -303,7 +313,7 @@ describe("pre 2.0 config with an existing cluster", () => {
version: "1.0.0"
}
},
cluster1: "kubeconfig content"
cluster1: minimalValidKubeConfig,
})
}
};
@@ -321,7 +331,7 @@ describe("pre 2.0 config with an existing cluster", () => {
it("migrates to modern format with kubeconfig in a file", async () => {
const config = clusterStore.clustersList[0].kubeConfigPath;
expect(fs.readFileSync(config, "utf8")).toBe("kubeconfig content");
expect(fs.readFileSync(config, "utf8")).toContain(`"contexts":[]`);
});
});
@@ -375,7 +385,7 @@ describe("pre 2.6.0 config with a cluster icon", () => {
}
},
cluster1: {
kubeConfig: "foo",
kubeConfig: minimalValidKubeConfig,
icon: "icon_path",
preferences: {
terminalCWD: "/tmp"
@@ -417,7 +427,7 @@ describe("for a pre 2.7.0-beta.0 config without a workspace", () => {
}
},
cluster1: {
kubeConfig: "foo",
kubeConfig: minimalValidKubeConfig,
preferences: {
terminalCWD: "/tmp"
}
@@ -451,7 +461,7 @@ describe("pre 3.6.0-beta.1 config with an existing cluster", () => {
clusters: [
{
id: "cluster1",
kubeConfig: "kubeconfig content",
kubeConfig: minimalValidKubeConfig,
contextName: "cluster",
preferences: {
icon: "store://icon_path",
@@ -476,7 +486,7 @@ describe("pre 3.6.0-beta.1 config with an existing cluster", () => {
it("migrates to modern format with kubeconfig in a file", async () => {
const config = clusterStore.clustersList[0].kubeConfigPath;
expect(fs.readFileSync(config, "utf8")).toBe("kubeconfig content");
expect(fs.readFileSync(config, "utf8")).toBe(minimalValidKubeConfig);
});
it("migrates to modern format with icon not in file", async () => {
+189 -36
View File
@@ -1,5 +1,5 @@
import { KubeConfig } from "@kubernetes/client-node";
import { validateKubeConfig } from "../kube-helpers";
import { validateKubeConfig, loadConfig } from "../kube-helpers";
const kubeconfig = `
apiVersion: v1
@@ -40,61 +40,214 @@ users:
const kc = new KubeConfig();
describe("validateKubeconfig", () => {
beforeAll(() => {
kc.loadFromString(kubeconfig);
});
describe("with default validation options", () => {
describe("with valid kubeconfig", () => {
it("does not raise exceptions", () => {
expect(() => { validateKubeConfig(kc, "valid");}).not.toThrow();
});
interface kubeconfig {
apiVersion: string,
clusters: [{
name: string,
cluster: {
server: string
}
}],
contexts: [{
context: {
cluster: string,
user: string,
},
name: string
}],
users: [{
name: string
}],
kind: string,
"current-context": string,
preferences: {}
}
let mockKubeConfig: kubeconfig;
describe("kube helpers", () => {
describe("validateKubeconfig", () => {
beforeAll(() => {
kc.loadFromString(kubeconfig);
});
describe("with invalid context object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalid");}).toThrow("No valid context object provided in kubeconfig for context 'invalid'");
describe("with default validation options", () => {
describe("with valid kubeconfig", () => {
it("does not raise exceptions", () => {
expect(() => { validateKubeConfig(kc, "valid");}).not.toThrow();
});
});
describe("with invalid context object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalid");}).toThrow("No valid context object provided in kubeconfig for context 'invalid'");
});
});
describe("with invalid cluster object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidCluster");}).toThrow("No valid cluster object provided in kubeconfig for context 'invalidCluster'");
});
});
describe("with invalid user object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidUser");}).toThrow("No valid user object provided in kubeconfig for context 'invalidUser'");
});
});
describe("with invalid exec command", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidExec");}).toThrow("User Exec command \"foo\" not found on host. Please ensure binary is found in PATH or use absolute path to binary in Kubeconfig");
});
});
});
describe("with invalid cluster object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidCluster");}).toThrow("No valid cluster object provided in kubeconfig for context 'invalidCluster'");
describe("with validateCluster as false", () => {
describe("with invalid cluster object", () => {
it("does not raise exception", () => {
expect(() => { validateKubeConfig(kc, "invalidCluster", { validateCluster: false });}).not.toThrow();
});
});
});
describe("with invalid user object", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidUser");}).toThrow("No valid user object provided in kubeconfig for context 'invalidUser'");
describe("with validateUser as false", () => {
describe("with invalid user object", () => {
it("does not raise exceptions", () => {
expect(() => { validateKubeConfig(kc, "invalidUser", { validateUser: false });}).not.toThrow();
});
});
});
describe("with invalid exec command", () => {
it("it raises exception", () => {
expect(() => { validateKubeConfig(kc, "invalidExec");}).toThrow("User Exec command \"foo\" not found on host. Please ensure binary is found in PATH or use absolute path to binary in Kubeconfig");
describe("with validateExec as false", () => {
describe("with invalid exec object", () => {
it("does not raise exceptions", () => {
expect(() => { validateKubeConfig(kc, "invalidExec", { validateExec: false });}).not.toThrow();
});
});
});
});
describe("with validateCluster as false", () => {
describe("with invalid cluster object", () => {
it("does not raise exception", () => {
expect(() => { validateKubeConfig(kc, "invalidCluster", { validateCluster: false });}).not.toThrow();
describe("pre-validate context object in kubeconfig tests", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("Check logger.error() output", () => {
it("invalid yaml string", () => {
const invalidYAMLString = "fancy foo config";
expect(() => loadConfig(invalidYAMLString)).toThrowError("must be an object");
});
it("empty contexts", () => {
const emptyContexts = `apiVersion: v1\ncontexts:`;
expect(() => loadConfig(emptyContexts)).not.toThrow();
});
});
});
describe("with validateUser as false", () => {
describe("with invalid user object", () => {
it("does not raise excpetions", () => {
expect(() => { validateKubeConfig(kc, "invalidUser", { validateUser: false });}).not.toThrow();
describe("Check valid kubeconfigs", () => {
beforeEach(() => {
mockKubeConfig = {
apiVersion: "v1",
clusters: [{
name: "minikube",
cluster: {
server: "https://192.168.64.3:8443",
},
}],
contexts: [{
context: {
cluster: "minikube",
user: "minikube",
},
name: "minikube",
}],
users: [{
name: "minikube",
}],
kind: "Config",
"current-context": "minikube",
preferences: {},
};
});
it("single context is ok", async () => {
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
});
it("multiple context is ok", async () => {
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: "cluster-2"}, name: "cluster-2"});
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
expect(kc.contexts.length).toBe(2);
});
});
});
describe("with validateExec as false", () => {
describe("with invalid exec object", () => {
it("does not raise excpetions", () => {
expect(() => { validateKubeConfig(kc, "invalidExec", { validateExec: false });}).not.toThrow();
describe("Check invalid kubeconfigs", () => {
beforeEach(() => {
mockKubeConfig = {
apiVersion: "v1",
clusters: [{
name: "minikube",
cluster: {
server: "https://192.168.64.3:8443",
},
}],
contexts: [{
context: {
cluster: "minikube",
user: "minikube",
},
name: "minikube",
}],
users: [{
name: "minikube",
}],
kind: "Config",
"current-context": "minikube",
preferences: {},
};
});
it("empty name in context causes it to be removed", async () => {
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: "cluster-2"}, name: ""});
expect(mockKubeConfig.contexts.length).toBe(2);
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
expect(kc.contexts.length).toBe(1);
});
it("empty cluster in context causes it to be removed", async () => {
mockKubeConfig.contexts.push({context: {cluster: "", user: "cluster-2"}, name: "cluster-2"});
expect(mockKubeConfig.contexts.length).toBe(2);
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
expect(kc.contexts.length).toBe(1);
});
it("empty user in context causes it to be removed", async () => {
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: ""}, name: "cluster-2"});
expect(mockKubeConfig.contexts.length).toBe(2);
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
expect(kc.contexts.length).toBe(1);
});
it("invalid context in between valid contexts is removed", async () => {
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: ""}, name: "cluster-2"});
mockKubeConfig.contexts.push({context: {cluster: "cluster-3", user: "cluster-3"}, name: "cluster-3"});
expect(mockKubeConfig.contexts.length).toBe(3);
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
expect(kc.getCurrentContext()).toBe("minikube");
expect(kc.contexts.length).toBe(2);
expect(kc.contexts[0].name).toBe("minikube");
expect(kc.contexts[1].name).toBe("cluster-3");
});
});
});
@@ -50,7 +50,7 @@ export class KubernetesCluster implements CatalogEntity {
icon: "settings",
title: "Settings",
onlyVisibleForSource: "local",
onClick: async () => context.navigate(`/cluster/${this.metadata.uid}/settings`)
onClick: async () => context.navigate(`/entity/${this.metadata.uid}/settings`)
},
{
icon: "delete",
+13
View File
@@ -52,11 +52,23 @@ export type CatalogEntityContextMenu = {
}
};
export type CatalogEntitySettingsMenu = {
group?: string;
title: string;
components: {
View: React.ComponentType<any>
};
};
export interface CatalogEntityContextMenuContext {
navigate: (url: string) => void;
menuItems: CatalogEntityContextMenu[];
}
export interface CatalogEntitySettingsContext {
menuItems: CatalogEntityContextMenu[];
}
export interface CatalogEntityAddMenuContext {
navigate: (url: string) => void;
menuItems: CatalogEntityContextMenu[];
@@ -78,4 +90,5 @@ export interface CatalogEntity extends CatalogEntityData {
onRun: (context: CatalogEntityActionContext) => Promise<void>;
onDetailsOpen: (context: CatalogEntityActionContext) => Promise<void>;
onContextMenuOpen: (context: CatalogEntityContextMenuContext) => Promise<void>;
onSettingsOpen?: (context: CatalogEntitySettingsContext) => Promise<void>;
}
+1 -1
View File
@@ -11,7 +11,7 @@ import { dumpConfigYaml } from "./kube-helpers";
import { saveToAppFiles } from "./utils/saveToAppFiles";
import { KubeConfig } from "@kubernetes/client-node";
import { handleRequest, requestMain, subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
import { ResourceType } from "../renderer/components/+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../renderer/components/cluster-settings/components/cluster-metrics-setting";
export interface ClusterIconUpload {
clusterId: string;
+29 -6
View File
@@ -6,6 +6,7 @@ import yaml from "js-yaml";
import logger from "../main/logger";
import commandExists from "command-exists";
import { ExecValidationNotFoundError } from "./custom-errors";
import { newClusters, newContexts, newUsers } from "@kubernetes/client-node/dist/config_types";
export type KubeConfigValidationOpts = {
validateCluster?: boolean;
@@ -23,14 +24,36 @@ function resolveTilde(filePath: string) {
return filePath;
}
function readResolvedPathSync(filePath: string): string {
return fse.readFileSync(path.resolve(resolveTilde(filePath)), "utf8");
}
function checkRawContext(rawContext: any): boolean {
return rawContext.name && rawContext.context?.cluster && rawContext.context?.user;
}
function loadToOptions(rawYaml: string): any {
const obj = yaml.safeLoad(rawYaml);
if (typeof obj !== "object" || !obj) {
throw new TypeError("KubeConfig root entry must be an object");
}
const { clusters: rawClusters, users: rawUsers, contexts: rawContexts, "current-context": currentContext } = obj;
const clusters = newClusters(rawClusters);
const users = newUsers(rawUsers);
const contexts = newContexts(rawContexts?.filter(checkRawContext));
return { clusters, users, contexts, currentContext };
}
export function loadConfig(pathOrContent?: string): KubeConfig {
const content = fse.pathExistsSync(pathOrContent) ? readResolvedPathSync(pathOrContent) : pathOrContent;
const options = loadToOptions(content);
const kc = new KubeConfig();
if (fse.pathExistsSync(pathOrContent)) {
kc.loadFromFile(path.resolve(resolveTilde(pathOrContent)));
} else {
kc.loadFromString(pathOrContent);
}
// need to load using the kubernetes client to generate a kubeconfig object
kc.loadFromOptions(options);
return kc;
}
@@ -146,7 +169,7 @@ export function podHasIssues(pod: V1Pod) {
return (
notReady ||
pod.status.phase !== "Running" ||
pod.spec.priority > 500000 // We're interested in high prio pods events regardless of their running status
pod.spec.priority > 500000 // We're interested in high priority pods events regardless of their running status
);
}
+5 -1
View File
@@ -2,7 +2,7 @@ import type { ThemeId } from "../renderer/theme.store";
import { app, remote } from "electron";
import semver from "semver";
import { readFile } from "fs-extra";
import { action, observable, reaction, toJS } from "mobx";
import { action, computed, observable, reaction, toJS } from "mobx";
import { BaseStore } from "./base-store";
import migrations from "../migrations/user-store";
import { getAppVersion } from "./utils/app-version";
@@ -114,6 +114,10 @@ export class UserStore extends BaseStore<UserStoreModel> {
this.kubeConfigPath = kubeConfigDefaultPath;
}
@computed get isDefaultKubeConfigPath(): boolean {
return this.kubeConfigPath === kubeConfigDefaultPath;
}
@action
async resetTheme() {
await this.whenLoaded;
+1 -1
View File
@@ -211,8 +211,8 @@ export class ExtensionLoader {
this.autoInitExtensions(async (extension: LensRendererExtension) => {
const removeItems = [
registries.globalPageRegistry.add(extension.globalPages, extension),
registries.globalPageMenuRegistry.add(extension.globalPageMenus, extension),
registries.appPreferenceRegistry.add(extension.appPreferences),
registries.entitySettingRegistry.add(extension.entitySettings),
registries.statusBarRegistry.add(extension.statusBarItems),
registries.commandRegistry.add(extension.commands),
];
@@ -3,6 +3,7 @@ import type { Cluster } from "../main/cluster";
import { LensExtension } from "./lens-extension";
import { getExtensionPageUrl } from "./registries/page-registry";
import { CommandRegistration } from "./registries/command-registry";
import { EntitySettingRegistration } from "./registries/entity-setting-registry";
export class LensRendererExtension extends LensExtension {
globalPages: PageRegistration[] = [];
@@ -11,6 +12,7 @@ export class LensRendererExtension extends LensExtension {
clusterPageMenus: ClusterPageMenuRegistration[] = [];
kubeObjectStatusTexts: KubeObjectStatusRegistration[] = [];
appPreferences: AppPreferenceRegistration[] = [];
entitySettings: EntitySettingRegistration[] = [];
statusBarItems: StatusBarRegistration[] = [];
kubeObjectDetailItems: KubeObjectDetailRegistration[] = [];
kubeObjectMenuItems: KubeObjectMenuRegistration[] = [];
@@ -0,0 +1,49 @@
import type React from "react";
import { CatalogEntity } from "../../common/catalog-entity";
import { BaseRegistry } from "./base-registry";
export interface EntitySettingViewProps {
entity: CatalogEntity;
}
export interface EntitySettingComponents {
View: React.ComponentType<EntitySettingViewProps>;
}
export interface EntitySettingRegistration {
title: string;
kind: string;
apiVersions: string[];
source?: string;
id?: string;
components: EntitySettingComponents;
}
export interface RegisteredEntitySetting extends EntitySettingRegistration {
id: string;
}
export class EntitySettingRegistry extends BaseRegistry<EntitySettingRegistration, RegisteredEntitySetting> {
getRegisteredItem(item: EntitySettingRegistration): RegisteredEntitySetting {
return {
id: item.id || item.title.toLowerCase(),
...item,
};
}
getItemsForKind(kind: string, apiVersion: string, source?: string) {
const items = this.getItems().filter((item) => {
return item.kind === kind && item.apiVersions.includes(apiVersion);
});
if (source) {
return items.filter((item) => {
return !item.source || item.source === source;
});
} else {
return items;
}
}
}
export const entitySettingRegistry = new EntitySettingRegistry();
+1
View File
@@ -9,3 +9,4 @@ export * from "./kube-object-detail-registry";
export * from "./kube-object-menu-registry";
export * from "./kube-object-status-registry";
export * from "./command-registry";
export * from "./entity-setting-registry";
@@ -57,5 +57,4 @@ export class ClusterPageMenuRegistry extends PageMenuRegistry<ClusterPageMenuReg
}
}
export const globalPageMenuRegistry = new PageMenuRegistry();
export const clusterPageMenuRegistry = new ClusterPageMenuRegistry();
+17 -4
View File
@@ -675,6 +675,8 @@ export class Cluster implements ClusterModel, ClusterState {
};
}
protected getAllowedNamespacesErrorCount = 0;
protected async getAllowedNamespaces() {
if (this.accessibleNamespaces.length) {
return this.accessibleNamespaces;
@@ -683,16 +685,27 @@ export class Cluster implements ClusterModel, ClusterState {
const api = (await this.getProxyKubeconfig()).makeApiClient(CoreV1Api);
try {
const namespaceList = await api.listNamespace();
const { body: { items }} = await api.listNamespace();
const namespaces = items.map(ns => ns.metadata.name);
return namespaceList.body.items.map(ns => ns.metadata.name);
this.getAllowedNamespacesErrorCount = 0; // reset on success
return namespaces;
} catch (error) {
const ctx = (await this.getProxyKubeconfig()).getContextObject(this.contextName);
const namespaceList = [ctx.namespace].filter(Boolean);
if (namespaceList.length === 0 && error instanceof HttpError && error.statusCode === 403) {
logger.info("[CLUSTER]: listing namespaces is forbidden, broadcasting", { clusterId: this.id });
broadcastMessage(ClusterListNamespaceForbiddenChannel, this.id);
this.getAllowedNamespacesErrorCount += 1;
if (this.getAllowedNamespacesErrorCount > 3) {
// reset on send
this.getAllowedNamespacesErrorCount = 0;
// then broadcast, make sure it is 3 successive attempts
logger.info("[CLUSTER]: listing namespaces is forbidden, broadcasting", { clusterId: this.id, error });
broadcastMessage(ClusterListNamespaceForbiddenChannel, this.id);
}
}
return namespaceList;
-24
View File
@@ -5,7 +5,6 @@ import { appName, isMac, isWindows, isTestEnv, docsUrl, supportUrl } from "../co
import { addClusterURL } from "../renderer/components/+add-cluster/add-cluster.route";
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
import { whatsNewURL } from "../renderer/components/+whats-new/whats-new.route";
import { clusterSettingsURL } from "../renderer/components/+cluster-settings/cluster-settings.route";
import { extensionsURL } from "../renderer/components/+extensions/extensions.route";
import { catalogURL } from "../renderer/components/+catalog/catalog.route";
import { menuRegistry } from "../extensions/registries/menu-registry";
@@ -47,16 +46,6 @@ export function buildMenu(windowManager: WindowManager) {
return menuItems;
}
function activeClusterOnly(menuItems: MenuItemConstructorOptions[]) {
if (!windowManager.activeClusterId) {
menuItems.forEach(item => {
item.enabled = false;
});
}
return menuItems;
}
async function navigate(url: string) {
logger.info(`[MENU]: navigating to ${url}`);
await windowManager.navigate(url);
@@ -112,19 +101,6 @@ export function buildMenu(windowManager: WindowManager) {
navigate(addClusterURL());
}
},
...activeClusterOnly([
{
label: "Cluster Settings",
accelerator: "CmdOrCtrl+Shift+S",
click() {
navigate(clusterSettingsURL({
params: {
clusterId: windowManager.activeClusterId
}
}));
}
}
]),
...ignoreOnMac([
{ type: "separator" },
{
+91
View File
@@ -0,0 +1,91 @@
import { CustomResourceDefinition } from "../endpoints";
import { IKubeObjectMetadata } from "../kube-object";
describe("Crds", () => {
describe("getVersion", () => {
it("should get the first version name from the list of versions", () => {
const crd = new CustomResourceDefinition({
apiVersion: "foo",
kind: "CustomResourceDefinition",
metadata: {} as IKubeObjectMetadata,
});
crd.spec = {
versions: [
{
name: "123",
served: false,
storage: false,
}
]
} as any;
expect(crd.getVersion()).toBe("123");
});
it("should get the first version name from the list of versions (length 2)", () => {
const crd = new CustomResourceDefinition({
apiVersion: "foo",
kind: "CustomResourceDefinition",
metadata: {} as IKubeObjectMetadata,
});
crd.spec = {
versions: [
{
name: "123",
served: false,
storage: false,
},
{
name: "1234",
served: false,
storage: false,
}
]
} as any;
expect(crd.getVersion()).toBe("123");
});
it("should get the first version name from the list of versions (length 2) even with version field", () => {
const crd = new CustomResourceDefinition({
apiVersion: "foo",
kind: "CustomResourceDefinition",
metadata: {} as IKubeObjectMetadata,
});
crd.spec = {
version: "abc",
versions: [
{
name: "123",
served: false,
storage: false,
},
{
name: "1234",
served: false,
storage: false,
}
]
} as any;
expect(crd.getVersion()).toBe("123");
});
it("should get the first version name from the version field", () => {
const crd = new CustomResourceDefinition({
apiVersion: "foo",
kind: "CustomResourceDefinition",
metadata: {} as IKubeObjectMetadata,
});
crd.spec = {
version: "abc"
} as any;
expect(crd.getVersion()).toBe("abc");
});
});
});
@@ -44,6 +44,10 @@ export class CatalogEntityRegistry {
return this._items;
}
getById(id: string) {
return this._items.find((entity) => entity.metadata.uid === id);
}
getItemsForApiKind<T extends CatalogEntity>(apiVersion: string, kind: string): T[] {
const items = this._items.filter((item) => item.apiVersion === apiVersion && item.kind === kind);
+3 -3
View File
@@ -33,7 +33,7 @@ export class CustomResourceDefinition extends KubeObject {
};
scope: "Namespaced" | "Cluster" | string;
validation?: any;
versions: {
versions?: {
name: string;
served: boolean;
storage: boolean;
@@ -103,7 +103,7 @@ export class CustomResourceDefinition extends KubeObject {
getVersion() {
// v1 has removed the spec.version property, if it is present it must match the first version
return this.spec.versions[0]?.name ?? this.spec.version;
return this.spec.versions?.[0]?.name ?? this.spec.version;
}
isNamespaced() {
@@ -123,7 +123,7 @@ export class CustomResourceDefinition extends KubeObject {
}
getPrinterColumns(ignorePriority = true): AdditionalPrinterColumnsV1[] {
const columns = this.spec.versions.find(a => this.getVersion() == a.name)?.additionalPrinterColumns
const columns = this.spec.versions?.find(a => this.getVersion() == a.name)?.additionalPrinterColumns
?? this.spec.additionalPrinterColumns?.map(({ JSONPath, ...rest }) => ({ ...rest, jsonPath: JSONPath })) // map to V1 shape
?? [];
@@ -62,9 +62,11 @@ export class AddCluster extends React.Component {
this.kubeConfigPath = filePath;
userStore.kubeConfigPath = filePath; // save to store
} catch (err) {
Notifications.error(
<div>Can&apos;t setup <code>{filePath}</code> as kubeconfig: {String(err)}</div>
);
if (!userStore.isDefaultKubeConfigPath) {
Notifications.error(
<div>Can&apos;t setup <code>{filePath}</code> as kubeconfig: {String(err)}</div>
);
}
if (throwError) {
throw err;
@@ -343,7 +345,7 @@ export class AddCluster extends React.Component {
return (
<DropFileInput onDropFiles={this.onDropKubeConfig}>
<PageLayout className="AddClusters" header={<><Icon svg="logo-lens" big /> <h2>Add Clusters</h2></>} showOnTop={true}>
<PageLayout className="AddClusters" showOnTop={true}>
<h2>Add Clusters from Kubeconfig</h2>
{this.renderInfo()}
{this.renderKubeConfigSource()}
@@ -14,8 +14,18 @@ export interface IChartVersion {
export class HelmChartStore extends ItemStore<HelmChart> {
@observable versions = observable.map<string, IChartVersion[]>();
loadAll() {
return this.loadItems(() => helmChartsApi.list());
async loadAll() {
try {
const res = await this.loadItems(() => helmChartsApi.list());
this.failedLoading = false;
return res;
} catch (error) {
this.failedLoading = true;
throw error;
}
}
getByName(name: string, repo: string) {
@@ -1,5 +1,5 @@
import isEqual from "lodash/isEqual";
import { action, IReactionDisposer, observable, reaction, when } from "mobx";
import { action, observable, reaction, when } from "mobx";
import { autobind } from "../../utils";
import { HelmRelease, helmReleasesApi, IReleaseCreatePayload, IReleaseUpdatePayload } from "../../api/endpoints/helm-releases.api";
import { ItemStore } from "../../item.store";
@@ -10,64 +10,64 @@ import { Notifications } from "../notifications";
@autobind()
export class ReleaseStore extends ItemStore<HelmRelease> {
@observable releaseSecrets: Secret[] = [];
@observable secretWatcher: IReactionDisposer;
releaseSecrets = observable.map<string, Secret>();
constructor() {
super();
when(() => secretsStore.isLoaded, () => {
this.releaseSecrets = this.getReleaseSecrets();
this.releaseSecrets.replace(this.getReleaseSecrets());
});
}
watch() {
this.secretWatcher = reaction(() => secretsStore.items.toJS(), () => {
watchAssociatedSecrets(): (() => void) {
return reaction(() => secretsStore.items.toJS(), () => {
if (this.isLoading) return;
const secrets = this.getReleaseSecrets();
const amountChanged = secrets.length !== this.releaseSecrets.length;
const labelsChanged = this.releaseSecrets.some(item => {
const secret = secrets.find(secret => secret.getId() == item.getId());
if (!secret) return;
return !isEqual(item.getLabels(), secret.getLabels());
});
const newSecrets = this.getReleaseSecrets();
const amountChanged = newSecrets.length !== this.releaseSecrets.size;
const labelsChanged = newSecrets.some(([id, secret]) => (
!isEqual(secret.getLabels(), this.releaseSecrets.get(id)?.getLabels())
));
if (amountChanged || labelsChanged) {
this.loadFromContextNamespaces();
}
this.releaseSecrets = [...secrets];
this.releaseSecrets.replace(newSecrets);
});
}
unwatch() {
this.secretWatcher();
watchSelecteNamespaces(): (() => void) {
return reaction(() => namespaceStore.context.contextNamespaces, namespaces => {
this.loadAll(namespaces);
});
}
getReleaseSecrets() {
return secretsStore.getByLabel({ owner: "helm" });
private getReleaseSecrets() {
return secretsStore
.getByLabel({ owner: "helm" })
.map(s => [s.getId(), s] as const);
}
getReleaseSecret(release: HelmRelease) {
const labels = {
return secretsStore.getByLabel({
owner: "helm",
name: release.getName()
};
return secretsStore.getByLabel(labels)
.filter(secret => secret.getNs() == release.getNs())[0];
})
.find(secret => secret.getNs() == release.getNs());
}
@action
async loadAll(namespaces: string[]) {
this.isLoading = true;
this.isLoaded = false;
try {
const items = await this.loadItems(namespaces);
this.items.replace(this.sortItems(items));
this.isLoaded = true;
this.failedLoading = false;
} catch (error) {
this.failedLoading = true;
console.error("Loading Helm Chart releases has failed", error);
if (error.error) {
@@ -79,17 +79,18 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
}
async loadFromContextNamespaces(): Promise<void> {
return this.loadAll(namespaceStore.contextNamespaces);
return this.loadAll(namespaceStore.context.contextNamespaces);
}
async loadItems(namespaces: string[]) {
const isLoadingAll = namespaceStore.allowedNamespaces.every(ns => namespaces.includes(ns));
const noAccessibleNamespaces = namespaceStore.context.cluster.accessibleNamespaces.length === 0;
const isLoadingAll = namespaceStore.context.allNamespaces?.length > 1
&& namespaceStore.context.cluster.accessibleNamespaces.length === 0
&& namespaceStore.context.allNamespaces.every(ns => namespaces.includes(ns));
if (isLoadingAll && noAccessibleNamespaces) {
if (isLoadingAll) {
return helmReleasesApi.list();
} else {
return Promise
return Promise // load resources per namespace
.all(namespaces.map(namespace => helmReleasesApi.list(namespace)))
.then(items => items.flat());
}
@@ -2,7 +2,7 @@ import "./releases.scss";
import React, { Component } from "react";
import kebabCase from "lodash/kebabCase";
import { observer } from "mobx-react";
import { disposeOnUnmount, observer } from "mobx-react";
import { RouteComponentProps } from "react-router";
import { releaseStore } from "./release.store";
import { IReleaseRouteParams, releaseURL } from "./release.route";
@@ -30,14 +30,11 @@ interface Props extends RouteComponentProps<IReleaseRouteParams> {
@observer
export class HelmReleases extends Component<Props> {
componentDidMount() {
// Watch for secrets associated with releases and react to their changes
releaseStore.watch();
}
componentWillUnmount() {
releaseStore.unwatch();
disposeOnUnmount(this, [
releaseStore.watchAssociatedSecrets(),
releaseStore.watchSelecteNamespaces(),
]);
}
get selectedRelease() {
@@ -49,21 +46,16 @@ export class HelmReleases extends Component<Props> {
}
showDetails = (item: HelmRelease) => {
if (!item) {
navigation.merge(releaseURL());
}
else {
navigation.merge(releaseURL({
params: {
name: item.getName(),
namespace: item.getNs()
}
}));
}
navigation.merge(releaseURL({
params: {
name: item.getName(),
namespace: item.getNs()
}
}));
};
hideDetails = () => {
this.showDetails(null);
navigation.merge(releaseURL());
};
renderRemoveDialogMessage(selectedItems: HelmRelease[]) {
@@ -114,30 +106,22 @@ export class HelmReleases extends Component<Props> {
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
{ title: "Updated", className: "updated", sortBy: columnId.updated, id: columnId.updated },
]}
renderTableContents={(release: HelmRelease) => {
const version = release.getVersion();
return [
release.getName(),
release.getNs(),
release.getChart(),
release.getRevision(),
<>
{version}
</>,
release.appVersion,
{ title: release.getStatus(), className: kebabCase(release.getStatus()) },
release.getUpdated(),
];
}}
renderItemMenu={(release: HelmRelease) => {
return (
<HelmReleaseMenu
release={release}
removeConfirmationMessage={this.renderRemoveDialogMessage([release])}
/>
);
}}
renderTableContents={(release: HelmRelease) => [
release.getName(),
release.getNs(),
release.getChart(),
release.getRevision(),
release.getVersion(),
release.appVersion,
{ title: release.getStatus(), className: kebabCase(release.getStatus()) },
release.getUpdated(),
]}
renderItemMenu={(release: HelmRelease) => (
<HelmReleaseMenu
release={release}
removeConfirmationMessage={this.renderRemoveDialogMessage([release])}
/>
)}
customizeRemoveDialog={(selectedItems: HelmRelease[]) => ({
message: this.renderRemoveDialogMessage(selectedItems)
})}
@@ -1,12 +0,0 @@
import type { IClusterViewRouteParams } from "../cluster-manager/cluster-view.route";
import type { RouteProps } from "react-router";
import { buildURL } from "../../../common/utils/buildUrl";
export interface IClusterSettingsRouteParams extends IClusterViewRouteParams {
}
export const clusterSettingsRoute: RouteProps = {
path: `/cluster/:clusterId/settings`,
};
export const clusterSettingsURL = buildURL<IClusterSettingsRouteParams>(clusterSettingsRoute.path);
@@ -1,51 +0,0 @@
.ClusterSettings {
$spacing: $padding * 3;
> .content-wrapper {
--flex-gap: #{$spacing};
}
// TODO: move sub-component styles to separate files
.admin-note {
font-size: small;
opacity: 0.5;
margin-left: $margin;
}
.button-area {
margin-top: $margin * 2;
}
.file-loader {
margin-top: $margin * 2;
}
.status-table {
margin: $spacing 0;
.Table {
border: 1px solid var(--drawerSubtitleBackground);
border-radius: $radius;
.TableRow {
&:not(:last-of-type) {
border-bottom: 1px solid var(--drawerSubtitleBackground);
}
.value {
flex-grow: 2;
word-break: break-word;
color: var(--textColorSecondary);
}
.link {
@include pseudo-link;
}
}
}
}
.Input, .Select {
margin-top: $padding;
}
}
@@ -1,69 +0,0 @@
import "./cluster-settings.scss";
import React from "react";
import { reaction } from "mobx";
import { RouteComponentProps } from "react-router";
import { observer, disposeOnUnmount } from "mobx-react";
import { Status } from "./status";
import { General } from "./general";
import { Cluster } from "../../../main/cluster";
import { IClusterSettingsRouteParams } from "./cluster-settings.route";
import { clusterStore } from "../../../common/cluster-store";
import { PageLayout } from "../layout/page-layout";
import { requestMain } from "../../../common/ipc";
import { clusterActivateHandler, clusterRefreshHandler } from "../../../common/cluster-ipc";
import { navigation } from "../../navigation";
interface Props extends RouteComponentProps<IClusterSettingsRouteParams> {
}
@observer
export class ClusterSettings extends React.Component<Props> {
get clusterId() {
return this.props.match.params.clusterId;
}
get cluster(): Cluster {
return clusterStore.getById(this.clusterId);
}
componentDidMount() {
const { hash } = navigation.location;
document.getElementById(hash.slice(1))?.scrollIntoView();
disposeOnUnmount(this, [
reaction(() => this.cluster, this.refreshCluster, {
fireImmediately: true,
}),
reaction(() => this.clusterId, clusterId => clusterStore.setActive(clusterId), {
fireImmediately: true,
})
]);
}
refreshCluster = async () => {
if (this.cluster) {
await requestMain(clusterActivateHandler, this.cluster.id);
await requestMain(clusterRefreshHandler, this.cluster.id);
}
};
render() {
const cluster = this.cluster;
if (!cluster) return null;
const header = (
<>
<h2>{cluster.preferences.clusterName}</h2>
</>
);
return (
<PageLayout className="ClusterSettings" header={header} showOnTop={true}>
<Status cluster={cluster}></Status>
<General cluster={cluster}></General>
</PageLayout>
);
}
}
@@ -1,28 +0,0 @@
import React from "react";
import { Cluster } from "../../../main/cluster";
import { ClusterNameSetting } from "./components/cluster-name-setting";
import { ClusterProxySetting } from "./components/cluster-proxy-setting";
import { ClusterPrometheusSetting } from "./components/cluster-prometheus-setting";
import { ClusterHomeDirSetting } from "./components/cluster-home-dir-setting";
import { ClusterAccessibleNamespaces } from "./components/cluster-accessible-namespaces";
import { ClusterMetricsSetting } from "./components/cluster-metrics-setting";
import { ShowMetricsSetting } from "./components/show-metrics";
interface Props {
cluster: Cluster;
}
export class General extends React.Component<Props> {
render() {
return <div>
<h2>General</h2>
<ClusterNameSetting cluster={this.props.cluster} />
<ClusterProxySetting cluster={this.props.cluster} />
<ClusterPrometheusSetting cluster={this.props.cluster} />
<ClusterHomeDirSetting cluster={this.props.cluster} />
<ClusterAccessibleNamespaces cluster={this.props.cluster} />
<ClusterMetricsSetting cluster={this.props.cluster}/>
<ShowMetricsSetting cluster={this.props.cluster}/>
</div>;
}
}
@@ -1,61 +0,0 @@
import React from "react";
import { Cluster } from "../../../main/cluster";
import { SubTitle } from "../layout/sub-title";
import { Table, TableCell, TableRow } from "../table";
import { autobind } from "../../utils";
import { shell } from "electron";
interface Props {
cluster: Cluster;
}
export class Status extends React.Component<Props> {
@autobind()
openKubeconfig() {
const { cluster } = this.props;
shell.showItemInFolder(cluster.kubeConfigPath);
}
renderStatusRows() {
const { cluster } = this.props;
const rows = [
["Online Status", cluster.online ? "online" : `offline (${cluster.failureReason || "unknown reason"})`],
["Distribution", cluster.metadata.distribution ? String(cluster.metadata.distribution) : "N/A"],
["Kernel Version", cluster.metadata.version ? String(cluster.metadata.version) : "N/A"],
["API Address", cluster.apiUrl || "N/A"],
["Nodes Count", cluster.metadata.nodes ? String(cluster.metadata.nodes) : "N/A"]
];
return (
<Table scrollable={false}>
{rows.map(([name, value]) => {
return (
<TableRow key={name}>
<TableCell>{name}</TableCell>
<TableCell className="value">{value}</TableCell>
</TableRow>
);
})}
<TableRow>
<TableCell>Kubeconfig</TableCell>
<TableCell className="link value" onClick={this.openKubeconfig}>{cluster.kubeConfigPath}</TableCell>
</TableRow>
</Table>
);
}
render() {
return <div>
<h2>Status</h2>
<SubTitle title="Cluster Status"/>
<p>
Cluster status information including: detected distribution, kernel version, and online status.
</p>
<div className="status-table">
{this.renderStatusRows()}
</div>
</div>;
}
}
@@ -24,6 +24,7 @@ interface IWarning extends ItemObject {
message: string;
selfLink: string;
age: string | number;
timeDiffFromNow: number;
}
enum sortBy {
@@ -37,7 +38,7 @@ export class ClusterIssues extends React.Component<Props> {
private sortCallbacks = {
[sortBy.type]: (warning: IWarning) => warning.kind,
[sortBy.object]: (warning: IWarning) => warning.getName(),
[sortBy.age]: (warning: IWarning) => warning.age || "",
[sortBy.age]: (warning: IWarning) => warning.timeDiffFromNow,
};
@computed get warnings() {
@@ -45,13 +46,14 @@ export class ClusterIssues extends React.Component<Props> {
// Node bad conditions
nodesStore.items.forEach(node => {
const { kind, selfLink, getId, getName, getAge } = node;
const { kind, selfLink, getId, getName, getAge, getTimeDiffFromNow } = node;
node.getWarningConditions().forEach(({ message }) => {
warnings.push({
age: getAge(),
getId,
getName,
timeDiffFromNow: getTimeDiffFromNow(),
kind,
message,
selfLink,
@@ -63,12 +65,13 @@ export class ClusterIssues extends React.Component<Props> {
const events = eventStore.getWarnings();
events.forEach(error => {
const { message, involvedObject, getAge } = error;
const { message, involvedObject, getAge, getTimeDiffFromNow } = error;
const { uid, name, kind } = involvedObject;
warnings.push({
getId: () => uid,
getName: () => name,
timeDiffFromNow: getTimeDiffFromNow(),
age: getAge(),
message,
kind,
@@ -13,7 +13,7 @@ import { ClusterIssues } from "./cluster-issues";
import { ClusterMetrics } from "./cluster-metrics";
import { clusterOverviewStore } from "./cluster-overview.store";
import { ClusterPieCharts } from "./cluster-pie-charts";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
@observer
export class ClusterOverview extends React.Component {
@@ -0,0 +1,12 @@
import type { RouteProps } from "react-router";
import { buildURL } from "../../../common/utils/buildUrl";
export interface EntitySettingsRouteParams {
entityId: string;
}
export const entitySettingsRoute: RouteProps = {
path: `/entity/:entityId/settings`,
};
export const entitySettingsURL = buildURL<EntitySettingsRouteParams>(entitySettingsRoute.path);
@@ -0,0 +1,23 @@
.EntitySettings {
$spacing: $padding * 3;
// TODO: move sub-component styles to separate files
.admin-note {
font-size: small;
opacity: 0.5;
margin-left: $margin;
}
.button-area {
margin-top: $margin * 2;
}
.file-loader {
margin-top: $margin * 2;
}
.Input, .Select {
margin-top: $padding;
}
}
@@ -0,0 +1,99 @@
import "./entity-settings.scss";
import React from "react";
import { observable } from "mobx";
import { RouteComponentProps } from "react-router";
import { observer } from "mobx-react";
import { PageLayout } from "../layout/page-layout";
import { navigation } from "../../navigation";
import { Tabs, Tab } from "../tabs";
import { CatalogEntity } from "../../api/catalog-entity";
import { catalogEntityRegistry } from "../../api/catalog-entity-registry";
import { entitySettingRegistry } from "../../../extensions/registries";
import { EntitySettingsRouteParams } from "./entity-settings.route";
interface Props extends RouteComponentProps<EntitySettingsRouteParams> {
}
@observer
export class EntitySettings extends React.Component<Props> {
@observable activeTab: string;
get entityId() {
return this.props.match.params.entityId;
}
get entity(): CatalogEntity {
return catalogEntityRegistry.getById(this.entityId);
}
get menuItems() {
if (!this.entity) return [];
return entitySettingRegistry.getItemsForKind(this.entity.kind, this.entity.apiVersion, this.entity.metadata.source);
}
async componentDidMount() {
const { hash } = navigation.location;
this.ensureActiveTab();
document.getElementById(hash.slice(1))?.scrollIntoView();
}
onTabChange = (tabId: string) => {
this.activeTab = tabId;
};
renderNavigation() {
return (
<>
<h2>{this.entity.metadata.name}</h2>
<Tabs className="flex column" scrollable={false} onChange={this.onTabChange} value={this.activeTab}>
<div className="header">Settings</div>
{ this.menuItems.map((setting) => (
<Tab
key={setting.id}
value={setting.id}
label={setting.title}
data-testid={`${setting.id}-tab`}
/>
))}
</Tabs>
</>
);
}
ensureActiveTab() {
if (!this.activeTab) {
this.activeTab = this.menuItems[0]?.id;
}
}
render() {
if (!this.entity) {
console.error("entity not found", this.entityId);
return null;
}
this.ensureActiveTab();
const activeSetting = this.menuItems.find((setting) => setting.id === this.activeTab);
return (
<PageLayout
className="CatalogEntitySettings"
navigation={this.renderNavigation()}
showOnTop={true}
contentGaps={false}
>
<section>
<h2 data-testid={`${activeSetting.id}-header`}>{activeSetting.title}</h2>
<section>
<activeSetting.components.View entity={this.entity} />
</section>
</section>
</PageLayout>
);
}
}
@@ -0,0 +1,4 @@
import "../cluster-settings";
export * from "./entity-settings.route";
export * from "./entity-settings";
@@ -482,12 +482,11 @@ export class Extensions extends React.Component {
}
render() {
const topHeader = <h2>Manage Lens Extensions</h2>;
const { installPath } = this;
return (
<DropFileInput onDropFiles={this.installOnDrop}>
<PageLayout showOnTop className="Extensions" header={topHeader} contentGaps={false}>
<PageLayout showOnTop className="Extensions" contentGaps={false}>
<h2>Lens Extensions</h2>
<div>
Add new features and functionality via Lens Extensions.
@@ -14,7 +14,7 @@ import { IngressCharts } from "./ingress-charts";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { getBackendServiceNamePort } from "../../api/endpoints/ingress.api";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<Ingress> {
@@ -17,7 +17,7 @@ import { PodDetailsList } from "../+workloads-pods/pod-details-list";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { KubeEventDetails } from "../+events/kube-event-details";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<Node> {
@@ -125,9 +125,9 @@ export class Preferences extends React.Component {
/>
</section>
<hr className="small"/>
<hr/>
<section id="shell" className="small">
<section id="shell">
<SubTitle title="Terminal Shell Path"/>
<Input
theme="round-black"
@@ -14,7 +14,7 @@ import { VolumeClaimDiskChart } from "./volume-claim-disk-chart";
import { getDetailsUrl, KubeObjectDetailsProps, KubeObjectMeta } from "../kube-object";
import { PersistentVolumeClaim } from "../../api/endpoints";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<PersistentVolumeClaim> {
@@ -18,7 +18,7 @@ import { reaction } from "mobx";
import { PodDetailsList } from "../+workloads-pods/pod-details-list";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<DaemonSet> {
@@ -19,7 +19,7 @@ import { reaction } from "mobx";
import { PodDetailsList } from "../+workloads-pods/pod-details-list";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<Deployment> {
@@ -11,7 +11,7 @@ import { PodContainerPort } from "./pod-container-port";
import { ResourceMetrics } from "../resource-metrics";
import { IMetrics } from "../../api/endpoints/metrics.api";
import { ContainerCharts } from "./container-charts";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props {
@@ -22,7 +22,7 @@ import { getItemMetrics } from "../../api/endpoints/metrics.api";
import { PodCharts, podMetricTabs } from "./pod-charts";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<Pod> {
@@ -17,7 +17,7 @@ import { PodCharts, podMetricTabs } from "../+workloads-pods/pod-charts";
import { PodDetailsList } from "../+workloads-pods/pod-details-list";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<ReplicaSet> {
@@ -18,7 +18,7 @@ import { PodCharts, podMetricTabs } from "../+workloads-pods/pod-charts";
import { PodDetailsList } from "../+workloads-pods/pod-details-list";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { ResourceType } from "../+cluster-settings/components/cluster-metrics-setting";
import { ResourceType } from "../cluster-settings/components/cluster-metrics-setting";
import { clusterStore } from "../../../common/cluster-store";
interface Props extends KubeObjectDetailsProps<StatefulSet> {
@@ -4,7 +4,6 @@
overflow: hidden; // required for transition effect on hover
color: white;
font-family: var(--font-main);
font-weight: var(--font-weight-bold);
text-align: center;
text-decoration: none;
cursor: pointer;
@@ -1,51 +0,0 @@
import React from "react";
import uniqueId from "lodash/uniqueId";
import { clusterSettingsURL } from "../+cluster-settings";
import { catalogURL } from "../+catalog";
import { clusterStore } from "../../../common/cluster-store";
import { broadcastMessage, requestMain } from "../../../common/ipc";
import { clusterDisconnectHandler } from "../../../common/cluster-ipc";
import { ConfirmDialog } from "../confirm-dialog";
import { Cluster } from "../../../main/cluster";
import { Tooltip } from "../../components//tooltip";
import { IpcRendererNavigationEvents } from "../../navigation/events";
const navigate = (route: string) =>
broadcastMessage(IpcRendererNavigationEvents.NAVIGATE_IN_APP, route);
/**
* Creates handlers for high-level actions
* that could be performed on an individual cluster
* @param cluster Cluster
*/
export const ClusterActions = (cluster: Cluster) => ({
showSettings: () => navigate(clusterSettingsURL({
params: { clusterId: cluster.id }
})),
disconnect: async () => {
clusterStore.deactivate(cluster.id);
navigate(catalogURL());
await requestMain(clusterDisconnectHandler, cluster.id);
},
remove: () => {
const tooltipId = uniqueId("tooltip_target_");
return ConfirmDialog.open({
okButtonProps: {
primary: false,
accent: true,
label: "Remove"
},
ok: () => {
clusterStore.deactivate(cluster.id);
clusterStore.removeById(cluster.id);
navigate(catalogURL());
},
message: <p>
Are you sure want to remove cluster <b id={tooltipId}>{cluster.name}</b>?
<Tooltip targetId={tooltipId}>{cluster.id}</Tooltip>
</p>
});
}
});
@@ -9,7 +9,6 @@ import { Catalog, catalogRoute, catalogURL } from "../+catalog";
import { Preferences, preferencesRoute } from "../+preferences";
import { AddCluster, addClusterRoute } from "../+add-cluster";
import { ClusterView } from "./cluster-view";
import { ClusterSettings, clusterSettingsRoute } from "../+cluster-settings";
import { clusterViewRoute } from "./cluster-view.route";
import { clusterStore } from "../../../common/cluster-store";
import { hasLoadedView, initView, lensViews, refreshViews } from "./lens-views";
@@ -17,6 +16,7 @@ import { globalPageRegistry } from "../../../extensions/registries/page-registry
import { Extensions, extensionsRoute } from "../+extensions";
import { getMatchedClusterId } from "../../navigation";
import { HotbarMenu } from "../hotbar/hotbar-menu";
import { EntitySettings, entitySettingsRoute } from "../+entity-settings";
@observer
export class ClusterManager extends React.Component {
@@ -58,7 +58,7 @@ export class ClusterManager extends React.Component {
<Route component={Extensions} {...extensionsRoute} />
<Route component={AddCluster} {...addClusterRoute} />
<Route component={ClusterView} {...clusterViewRoute} />
<Route component={ClusterSettings} {...clusterSettingsRoute} />
<Route component={EntitySettings} {...entitySettingsRoute} />
{globalPageRegistry.getItems().map(({ url, components: { Page } }) => {
return <Route key={url} path={url} component={Page}/>;
})}
@@ -1,2 +1 @@
export * from "./cluster-manager";
export * from "./cluster-actions";
@@ -1,15 +1,15 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { clusterSettingsURL } from "./cluster-settings.route";
import { clusterStore } from "../../../common/cluster-store";
import { entitySettingsURL } from "../+entity-settings";
commandRegistry.add({
id: "cluster.viewCurrentClusterSettings",
title: "Cluster: View Settings",
scope: "global",
action: () => navigate(clusterSettingsURL({
action: () => navigate(entitySettingsURL({
params: {
clusterId: clusterStore.active.id
entityId: clusterStore.active.id
}
})),
isActive: (context) => !!context.entity
@@ -0,0 +1,141 @@
import React from "react";
import { clusterStore } from "../../../common/cluster-store";
import { ClusterProxySetting } from "./components/cluster-proxy-setting";
import { ClusterNameSetting } from "./components/cluster-name-setting";
import { ClusterHomeDirSetting } from "./components/cluster-home-dir-setting";
import { ClusterAccessibleNamespaces } from "./components/cluster-accessible-namespaces";
import { ClusterMetricsSetting } from "./components/cluster-metrics-setting";
import { ShowMetricsSetting } from "./components/show-metrics";
import { ClusterPrometheusSetting } from "./components/cluster-prometheus-setting";
import { ClusterKubeconfig } from "./components/cluster-kubeconfig";
import { entitySettingRegistry } from "../../../extensions/registries";
import { CatalogEntity } from "../../api/catalog-entity";
function getClusterForEntity(entity: CatalogEntity) {
const cluster = clusterStore.getById(entity.metadata.uid);
if (!cluster?.enabled) {
return null;
}
return cluster;
}
entitySettingRegistry.add([
{
apiVersions: ["entity.k8slens.dev/v1alpha1"],
kind: "KubernetesCluster",
source: "local",
title: "General",
components: {
View: (props: { entity: CatalogEntity }) => {
const cluster = getClusterForEntity(props.entity);
if (!cluster) {
return null;
}
return (
<section>
<section>
<ClusterNameSetting cluster={cluster} />
</section>
<section>
<ClusterKubeconfig cluster={cluster} />
</section>
</section>
);
}
}
},
{
apiVersions: ["entity.k8slens.dev/v1alpha1"],
kind: "KubernetesCluster",
title: "Proxy",
components: {
View: (props: { entity: CatalogEntity }) => {
const cluster = getClusterForEntity(props.entity);
if (!cluster) {
return null;
}
return (
<section>
<ClusterProxySetting cluster={cluster} />
</section>
);
}
}
},
{
apiVersions: ["entity.k8slens.dev/v1alpha1"],
kind: "KubernetesCluster",
title: "Terminal",
components: {
View: (props: { entity: CatalogEntity }) => {
const cluster = getClusterForEntity(props.entity);
if (!cluster) {
return null;
}
return (
<section>
<ClusterHomeDirSetting cluster={cluster} />
</section>
);
}
}
},
{
apiVersions: ["entity.k8slens.dev/v1alpha1"],
kind: "KubernetesCluster",
title: "Namespaces",
components: {
View: (props: { entity: CatalogEntity }) => {
const cluster = getClusterForEntity(props.entity);
if (!cluster) {
return null;
}
return (
<section>
<ClusterAccessibleNamespaces cluster={cluster} />
</section>
);
}
}
},
{
apiVersions: ["entity.k8slens.dev/v1alpha1"],
kind: "KubernetesCluster",
source: "local",
title: "Metrics",
components: {
View: (props: { entity: CatalogEntity }) => {
const cluster = getClusterForEntity(props.entity);
if (!cluster) {
return null;
}
return (
<section>
<section>
<ClusterPrometheusSetting cluster={cluster} />
</section>
<section>
<ClusterMetricsSetting cluster={cluster}/>
</section>
<section>
<ShowMetricsSetting cluster={cluster}/>
</section>
</section>
);
}
}
}
]);
@@ -17,7 +17,6 @@ export class ClusterAccessibleNamespaces extends React.Component<Props> {
return (
<>
<SubTitle title="Accessible Namespaces" id="accessible-namespaces" />
<p>This setting is useful for manually specifying which namespaces you have access to. This is useful when you do not have permissions to list namespaces.</p>
<EditableList
placeholder="Add new namespace..."
add={(newNamespace) => {
@@ -30,6 +29,9 @@ export class ClusterAccessibleNamespaces extends React.Component<Props> {
this.props.cluster.accessibleNamespaces = Array.from(this.namespaces);
}}
/>
<small className="hint">
This setting is useful for manually specifying which namespaces you have access to. This is useful when you do not have permissions to list namespaces.
</small>
</>
);
}
@@ -33,7 +33,6 @@ export class ClusterHomeDirSetting extends React.Component<Props> {
return (
<>
<SubTitle title="Working Directory"/>
<p>Terminal working directory.</p>
<Input
theme="round-black"
value={this.directory}
@@ -0,0 +1,34 @@
import React from "react";
import { Cluster } from "../../../../main/cluster";
import { observer } from "mobx-react";
import { SubTitle } from "../../layout/sub-title";
import { autobind } from "../../../../common/utils";
import { shell } from "electron";
interface Props {
cluster: Cluster;
}
@observer
export class ClusterKubeconfig extends React.Component<Props> {
@autobind()
openKubeconfig() {
const { cluster } = this.props;
shell.showItemInFolder(cluster.kubeConfigPath);
}
render() {
return (
<>
<SubTitle title="Kubeconfig" />
<span>
<a className="link value" onClick={this.openKubeconfig}>{this.props.cluster.kubeConfigPath}</a>
</span>
</>
);
}
}
@@ -34,7 +34,6 @@ export class ClusterNameSetting extends React.Component<Props> {
return (
<>
<SubTitle title="Cluster Name" />
<p>Define cluster name.</p>
<Input
theme="round-black"
validators={isRequired}
@@ -81,13 +81,12 @@ export class ClusterPrometheusSetting extends React.Component<Props> {
render() {
return (
<>
<SubTitle title="Prometheus"/>
<SubTitle title="Prometheus installation method"/>
<p>
Use pre-installed Prometheus service for metrics. Please refer to the{" "}
<a href="https://github.com/lensapp/lens/blob/master/troubleshooting/custom-prometheus.md" target="_blank" rel="noreferrer">guide</a>{" "}
for possible configuration changes.
</p>
<p>Prometheus installation method.</p>
<Select
value={this.provider}
onChange={({value}) => {
@@ -33,7 +33,6 @@ export class ClusterProxySetting extends React.Component<Props> {
return (
<>
<SubTitle title="HTTP Proxy" />
<p>HTTP Proxy server. Used for communicating with Kubernetes API.</p>
<Input
theme="round-black"
value={this.proxy}
@@ -42,6 +41,9 @@ export class ClusterProxySetting extends React.Component<Props> {
placeholder="http://<address>:<port>"
validators={this.proxy ? InputValidators.isUrl : undefined}
/>
<small className="hint">
HTTP Proxy server. Used for communicating with Kubernetes API.
</small>
</>
);
}
@@ -1,3 +1,2 @@
export * from "./cluster-settings.route";
export * from "./cluster-settings";
export * from "./cluster-settings.command";
+2 -2
View File
@@ -4,8 +4,8 @@ import { namespaceStore } from "./+namespaces/namespace.store";
export interface ClusterContext {
cluster?: Cluster;
allNamespaces?: string[]; // available / allowed namespaces from cluster.ts
contextNamespaces?: string[]; // selected by user (see: namespace-select.tsx)
allNamespaces: string[]; // available / allowed namespaces from cluster.ts
contextNamespaces: string[]; // selected by user (see: namespace-select.tsx)
}
export const clusterContext: ClusterContext = {
+2 -1
View File
@@ -98,8 +98,9 @@
label {
background: var(--inputControlBackground);
border: 1px solid var(--inputControlBorder);
border-radius: 4px;
border-radius: 5px;
padding: $padding;
color: var(--textColorTertiary);
&:hover {
border-color: var(--inputControlHoverBorder);
@@ -172,6 +172,10 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
return this.props.isReady ?? this.props.store.isLoaded;
}
@computed get failedToLoad() {
return this.props.store.failedLoading;
}
@computed get filters() {
let { activeFilters } = pageFilters;
const { isSearchable, searchFilters } = this.props;
@@ -281,6 +285,11 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
});
}
@autobind()
toggleFilters() {
this.showFilters = !this.showFilters;
}
renderFilters() {
const { hideFilters } = this.props;
const { isReady, filters } = this;
@@ -293,6 +302,14 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
renderNoItems() {
if (this.failedToLoad) {
return <NoItems>Failed to load items.</NoItems>;
}
if (!this.isReady) {
return <Spinner center />;
}
if (this.filters.length > 0) {
return (
<NoItems>
@@ -309,6 +326,14 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
return <NoItems/>;
}
renderItems() {
if (this.props.virtual) {
return null;
}
return this.items.map(item => this.getRow(item.getId()));
}
renderHeaderContent(placeholders: IHeaderPlaceholders): ReactNode {
const { isSearchable, searchFilters } = this.props;
const { title, filters, search, info } = placeholders;
@@ -317,7 +342,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
<>
{title}
<div className="info-panel box grow">
{this.isReady && info}
{info}
</div>
{filters}
{isSearchable && searchFilters && search}
@@ -326,20 +351,17 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
renderInfo() {
const { items, isReady, filters } = this;
const { items, filters } = this;
const allItemsCount = this.props.store.getTotalCount();
const itemsCount = items.length;
const isFiltered = isReady && filters.length > 0;
if (isFiltered) {
const toggleFilters = () => this.showFilters = !this.showFilters;
if (filters.length > 0) {
return (
<><a onClick={toggleFilters}>Filtered</a>: {itemsCount} / {allItemsCount}</>
<><a onClick={this.toggleFilters}>Filtered</a>: {itemsCount} / {allItemsCount}</>
);
}
return allItemsCount <= 1 ? `${allItemsCount} item` : `${allItemsCount} items`;
return allItemsCount === 1 ? `${allItemsCount} item` : `${allItemsCount} items`;
}
renderHeader() {
@@ -412,40 +434,31 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
renderList() {
const {
store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks, detailsItem,
tableProps = {}, tableId
store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks,
detailsItem, className, tableProps = {}, tableId,
} = this.props;
const { isReady, removeItemsDialog, items } = this;
const { removeItemsDialog, items } = this;
const { selectedItems } = store;
const selectedItemId = detailsItem && detailsItem.getId();
const classNames = cssNames(className, "box", "grow", themeStore.activeTheme.type);
return (
<div className="items box grow flex column">
{!isReady && (
<Spinner center/>
)}
{isReady && (
<Table
tableId={tableId}
virtual={virtual}
selectable={hasDetailsView}
sortable={sortingCallbacks}
getTableRow={this.getRow}
items={items}
selectedItemId={selectedItemId}
noItems={this.renderNoItems()}
{...({
...tableProps,
className: cssNames("box grow", tableProps.className, themeStore.activeTheme.type),
})}
>
{this.renderTableHeader()}
{
!virtual && items.map(item => this.getRow(item.getId()))
}
</Table>
)}
<Table
tableId={tableId}
virtual={virtual}
selectable={hasDetailsView}
sortable={sortingCallbacks}
getTableRow={this.getRow}
items={items}
selectedItemId={selectedItemId}
noItems={this.renderNoItems()}
className={classNames}
{...tableProps}
>
{this.renderTableHeader()}
{this.renderItems()}
</Table>
<AddRemoveButtons
onRemove={selectedItems.length ? removeItemsDialog : null}
removeTooltip={`Remove selected items (${selectedItems.length})`}
@@ -7,6 +7,7 @@
width: 100%;
height: 100%;
display: grid !important;
color: var(--settingsColor);
@include media("<1000px") {
--width: 85%;
@@ -40,7 +41,16 @@
.sidebar {
width: 218px;
padding: 60px 10px 60px 20px;
padding: 60px 0 60px 20px;
h2 {
margin-bottom: 10px;
font-size: 18px;
padding: 6px 10px;
overflow-wrap: anywhere;
color: var(--textColorAccent);
font-weight: 600;
}
.Tabs {
.header {
@@ -62,18 +72,18 @@
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
font-weight: 500;
font-size: 15px;
line-height: 20px;
cursor: pointer;
color: var(--textColorSecondary);
border-top-right-radius: 0;
border-bottom-right-radius: 0;
&::after {
content: none;
}
&:hover {
background-color: var(--navHoverBackground);
background-color: var(--navSelectedBackground);
color: var(--navHoverColor);
}
@@ -194,5 +204,9 @@
display: none;
}
}
.Checkbox .label {
color: var(--textColorTertiary);
}
}
}
@@ -8,8 +8,6 @@ import { Icon } from "../icon";
export interface PageLayoutProps extends React.DOMAttributes<any> {
className?: IClassName;
header?: React.ReactNode;
headerClass?: IClassName;
contentClass?: IClassName;
provideBackButtonNavigation?: boolean;
contentGaps?: boolean;
@@ -57,7 +55,7 @@ export class PageLayout extends React.Component<PageLayoutProps> {
render() {
const {
contentClass, headerClass, provideBackButtonNavigation,
contentClass, provideBackButtonNavigation,
contentGaps, showOnTop, navigation, children, ...elemProps
} = this.props;
const className = cssNames("PageLayout", { showOnTop, showNavigation: navigation }, this.props.className);
@@ -206,6 +206,11 @@ html {
&__control {
box-shadow: 0 0 0 1px var(--inputControlBorder);
background: var(--inputControlBackground);
border-radius: 5px;
}
&__single-value {
color: var(--textColorTertiary);
}
&__menu {
+2 -2
View File
@@ -7,7 +7,7 @@ import { isMac } from "../../common/vars";
import { invalidKubeconfigHandler } from "./invalid-kubeconfig-handler";
import { clusterStore } from "../../common/cluster-store";
import { navigate } from "../navigation";
import { clusterSettingsURL } from "../components/+cluster-settings";
import { entitySettingsURL } from "../components/+entity-settings";
function sendToBackchannel(backchannel: string, notificationId: string, data: BackchannelArg): void {
notificationsStore.remove(notificationId);
@@ -79,7 +79,7 @@ function ListNamespacesForbiddenHandler(event: IpcRendererEvent, ...[clusterId]:
<p>Cluster <b>{clusterStore.active.name}</b> does not have permissions to list namespaces. Please add the namespaces you have access to.</p>
<div className="flex gaps row align-left box grow">
<Button active outlined label="Go to Accessible Namespaces Settings" onClick={()=> {
navigate(clusterSettingsURL({ params: { clusterId }, fragment: "accessible-namespaces" }));
navigate(entitySettingsURL({ params: { entityId: clusterId }, fragment: "accessible-namespaces" }));
notificationsStore.remove(notificationId);
}} />
</div>
+1
View File
@@ -13,6 +13,7 @@ export abstract class ItemStore<T extends ItemObject = ItemObject> {
protected defaultSorting = (item: T) => item.getName();
@observable failedLoading = false;
@observable isLoading = false;
@observable isLoaded = false;
@observable items = observable.array<T>([], { deep: false });
+4 -2
View File
@@ -146,18 +146,20 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
const items = await this.loadItems({ namespaces, api: this.api });
this.isLoaded = true;
if (merge) {
this.mergeItems(items, { replace: false });
} else {
this.mergeItems(items, { replace: true });
}
this.isLoaded = true;
this.failedLoading = false;
return items;
} catch (error) {
console.error("Loading store items failed", { error, store: this });
this.resetOnError(error);
this.failedLoading = true;
} finally {
this.isLoading = false;
}
+16 -5
View File
@@ -1,5 +1,4 @@
import { addClusterURL } from "../components/+add-cluster";
import { clusterSettingsURL } from "../components/+cluster-settings";
import { extensionsURL } from "../components/+extensions";
import { catalogURL } from "../components/+catalog";
import { preferencesURL } from "../components/+preferences";
@@ -7,6 +6,8 @@ import { clusterViewURL } from "../components/cluster-manager/cluster-view.route
import { LensProtocolRouterRenderer } from "./router";
import { navigate } from "../navigation/helpers";
import { clusterStore } from "../../common/cluster-store";
import { entitySettingsURL } from "../components/+entity-settings";
import { catalogEntityRegistry } from "../api/catalog-entity-registry";
export function bindProtocolAddRouteHandlers() {
LensProtocolRouterRenderer
@@ -23,6 +24,19 @@ export function bindProtocolAddRouteHandlers() {
.addInternalHandler("/cluster", () => {
navigate(addClusterURL());
})
.addInternalHandler("/entity/:entityId/settings", ({ pathname: { entityId } }) => {
const entity = catalogEntityRegistry.getById(entityId);
if (entity) {
navigate(entitySettingsURL({ params: { entityId } }));
} else {
console.log("[APP-HANDLER]: catalog entity with given ID does not exist", { entityId });
}
})
.addInternalHandler("/extensions", () => {
navigate(extensionsURL());
})
// Handlers below are deprecated and only kept for backward compat purposes
.addInternalHandler("/cluster/:clusterId", ({ pathname: { clusterId } }) => {
const cluster = clusterStore.getById(clusterId);
@@ -36,12 +50,9 @@ export function bindProtocolAddRouteHandlers() {
const cluster = clusterStore.getById(clusterId);
if (cluster) {
navigate(clusterSettingsURL({ params: { clusterId } }));
navigate(entitySettingsURL({ params: { entityId: clusterId } }));
} else {
console.log("[APP-HANDLER]: cluster with given ID does not exist", { clusterId });
}
})
.addInternalHandler("/extensions", () => {
navigate(extensionsURL());
});
}
+8 -7
View File
@@ -11,12 +11,13 @@
"primary": "#3d90ce",
"textColorPrimary": "#8e9297",
"textColorSecondary": "#a0a0a0",
"textColorTertiary": "#909ba6",
"textColorAccent": "#ffffff",
"textColorDimmed": "#8e92978c",
"borderColor": "#4c5053",
"borderFaintColor": "#373a3e",
"mainBackground": "#1e2124",
"secondaryBackground": "#212427",
"secondaryBackground": "#1e2125",
"contentColor": "#262b2f",
"layoutBackground": "#2e3136",
"layoutTabsBackground": "#252729",
@@ -115,17 +116,17 @@
"chartCapacityColor": "#4c545f",
"pieChartDefaultColor": "#30353a",
"inputOptionHoverColor": "#87909c",
"inputControlBackground": "#00000021",
"inputControlBorder": "#202225bf",
"inputControlHoverBorder": "#07080880",
"inputControlBackground": "#1e2125",
"inputControlBorder": "#414448",
"inputControlHoverBorder": "#474a4f",
"lineProgressBackground": "#414448",
"radioActiveBackground": "#36393e",
"menuActiveBackground": "#36393e",
"menuSelectedOptionBgc": "#36393e",
"scrollBarColor": "#5f6064",
"settingsBackground": "#2b3035",
"navSelectedBackground": "#4f545c52",
"navHoverBackground": "#4f545c29",
"settingsBackground": "#262b2e",
"settingsColor": "#909ba6",
"navSelectedBackground": "#262b2e",
"navHoverColor": "#dcddde",
"hrColor": "#ffffff0f"
}
+3 -2
View File
@@ -11,6 +11,7 @@
"primary": "#3d90ce",
"textColorPrimary": "#555555",
"textColorSecondary": "#51575d",
"textColorTertiary": "#555555",
"textColorAccent": "#333333",
"textColorDimmed": "#5557598c",
"borderColor": "#c9cfd3",
@@ -126,8 +127,8 @@
"scrollBarColor": "#bbbbbb",
"canvasBackground": "#24292e",
"settingsBackground": "#ffffff",
"navSelectedBackground": "#747f8d3d",
"navHoverBackground": "#747f8d14",
"settingsColor": "#555555",
"navSelectedBackground": "#ffffff",
"navHoverColor": "#2e3135",
"hrColor": "#06060714"
}
@@ -26,7 +26,7 @@ describe("renderer/utils/StorageHelper", () => {
expect(storageHelper.defaultValue).toBe("test");
expect(storageHelper.get()).toBe("test");
await storageHelper.init();
storageHelper.init();
expect(storageHelper.key).toBe(storageKey);
expect(storageHelper.defaultValue).toBe("test");
+53 -68
View File
@@ -1,7 +1,7 @@
// Helper for working with storages (e.g. window.localStorage, NodeJS/file-system, etc.)
import type { CreateObservableOptions } from "mobx/lib/api/observable";
import { action, comparer, observable, toJS, when } from "mobx";
import { action, comparer, observable, toJS, when, IObservableValue } from "mobx";
import produce, { Draft, enableMapSet, setAutoFreeze } from "immer";
import { isEqual, isFunction, isPlainObject } from "lodash";
import logger from "../../main/logger";
@@ -25,7 +25,7 @@ export interface StorageHelperOptions<T> {
}
export class StorageHelper<T> {
static defaultOptions: Partial<StorageHelperOptions<any>> = {
static readonly defaultOptions: Partial<StorageHelperOptions<any>> = {
autoInit: true,
observable: {
deep: true,
@@ -33,83 +33,68 @@ export class StorageHelper<T> {
}
};
@observable private data = observable.box<T>();
private data: IObservableValue<T>;
@observable initialized = false;
whenReady = when(() => this.initialized);
get storage(): StorageAdapter<T> {
return this.options.storage;
}
get defaultValue(): T {
return this.options.defaultValue;
}
public readonly storage: StorageAdapter<T>;
public readonly defaultValue: T;
constructor(readonly key: string, private options: StorageHelperOptions<T>) {
this.options = { ...StorageHelper.defaultOptions, ...options };
this.configureObservable();
this.reset();
if (this.options.autoInit) {
this.init();
}
}
@action
init({ force = false } = {}) {
if (this.initialized && !force) return;
this.loadFromStorage({
onData: (data: T) => {
const notEmpty = data != null;
const notDefault = !this.isDefaultValue(data);
if (notEmpty && notDefault) {
this.merge(data);
}
this.initialized = true;
},
onError: (error?: any) => {
logger.error(`[init]: ${error}`, this);
},
});
}
private loadFromStorage(opts: { onData?(data: T): void, onError?(error?: any): void } = {}) {
let data: T | Promise<T>;
try {
data = this.storage.getItem(this.key); // sync reading from storage when exposed
if (data instanceof Promise) {
data.then(opts.onData, opts.onError);
} else {
opts?.onData(data);
}
} catch (error) {
logger.error(`[load]: ${error}`, this);
opts?.onError(error);
}
return data;
}
isDefaultValue(value: T): boolean {
return isEqual(value, this.defaultValue);
}
@action
private configureObservable(options = this.options.observable) {
this.data = observable.box<T>(this.data.get(), {
...StorageHelper.defaultOptions.observable, // inherit default observability options
...(options ?? {}),
this.data = observable.box<T>(this.options.defaultValue, {
...StorageHelper.defaultOptions.observable,
...(options.observable ?? {})
});
this.data.observe(change => {
const { newValue, oldValue } = toJS(change, { recurseEverything: true });
this.onChange(newValue, oldValue);
});
this.storage = options.storage;
this.defaultValue = options.defaultValue;
if (this.options.autoInit) {
this.init();
}
}
private onData = (data: T): void => {
const notEmpty = data != null;
const notDefault = !this.isDefaultValue(data);
if (notEmpty && notDefault) {
this.merge(data);
}
this.initialized = true;
};
private onError = (error: any): void => {
logger.error(`[load]: ${error}`, this);
};
@action
init({ force = false } = {}) {
if (this.initialized && !force) {
return;
}
try {
const data = this.storage.getItem(this.key);
if (data instanceof Promise) {
data.then(this.onData, this.onError);
} else {
this.onData(data);
}
} catch (error) {
this.onError(error);
}
}
isDefaultValue(value: T): boolean {
return isEqual(value, this.defaultValue);
}
protected onChange(value: T, oldValue?: T) {