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

- refactoring: usages of renderer/utils/createStorage

- refactoring: Sidebar, SidebarItem and MainLayout
- ux-fix: expanding sidebar by clicking to the arrow-icon (for consistency with compact mode where no sub-menus)

Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
Roman 2021-03-04 18:47:13 +02:00
parent 63f0d918db
commit be8fd7ed45
20 changed files with 676 additions and 694 deletions

View File

@ -3,10 +3,8 @@ import * as utils from "../helpers/utils";
import { listHelmRepositories } from "../helpers/utils"; import { listHelmRepositories } from "../helpers/utils";
import { fail } from "assert"; import { fail } from "assert";
jest.setTimeout(60000); jest.setTimeout(60000);
// FIXME (!): improve / simplify all css-selectors + use [data-test-id="some-id"] (already used in some tests below)
describe("Lens integration tests", () => { describe("Lens integration tests", () => {
let app: Application; let app: Application;

View File

@ -7,14 +7,9 @@
import { Application } from "spectron"; import { Application } from "spectron";
import * as utils from "../helpers/utils"; import * as utils from "../helpers/utils";
import { addMinikubeCluster, minikubeReady, waitForMinikubeDashboard } from "../helpers/minikube"; import { addMinikubeCluster, minikubeReady, waitForMinikubeDashboard } from "../helpers/minikube";
import { exec } from "child_process";
import * as util from "util";
export const promiseExec = util.promisify(exec);
jest.setTimeout(60000); jest.setTimeout(60000);
// FIXME (!): improve / simplify all css-selectors + use [data-test-id="some-id"] (already used in some tests below)
describe("Lens cluster pages", () => { describe("Lens cluster pages", () => {
const TEST_NAMESPACE = "integration-tests"; const TEST_NAMESPACE = "integration-tests";
const BACKSPACE = "\uE003"; const BACKSPACE = "\uE003";
@ -53,6 +48,18 @@ describe("Lens cluster pages", () => {
} }
}; };
function getMainMenuSelectors(itemId: string) {
const baseSelector = `.Sidebar [data-test-id="${itemId}"]`;
return {
sidebarItemRoot: baseSelector,
expandIcon: `${baseSelector} .expand-icon`,
pageLink(href: string) {
return `${baseSelector} a[href^="/${href}"]`;
}
};
}
describe("cluster pages", () => { describe("cluster pages", () => {
beforeAll(appStartAddCluster, 40000); beforeAll(appStartAddCluster, 40000);
@ -63,275 +70,228 @@ describe("Lens cluster pages", () => {
} }
}); });
const tests: { type SidebarItem = {
drawer?: string testId: string;
drawerId?: string expectedSelector?: string;
pages: { expectedText?: string;
name: string, subMenu?: {
href: string, href: string;
expectedSelector: string, expectedSelector: string;
expectedText: string expectedText: string;
}[] }[];
}[] = [{ };
drawer: "",
drawerId: "", const sidebarMenu: SidebarItem[] = [
pages: [{ {
name: "Cluster", testId: "cluster",
href: "cluster",
expectedSelector: "div.ClusterOverview div.label", expectedSelector: "div.ClusterOverview div.label",
expectedText: "Master" expectedText: "Master",
}] },
}, {
{ testId: "nodes",
drawer: "",
drawerId: "",
pages: [{
name: "Nodes",
href: "nodes",
expectedSelector: "h5.title", expectedSelector: "h5.title",
expectedText: "Nodes" expectedText: "Nodes"
}]
},
{
drawer: "Workloads",
drawerId: "workloads",
pages: [{
name: "Overview",
href: "workloads",
expectedSelector: "h5.box",
expectedText: "Overview"
}, },
{ {
name: "Pods", testId: "workloads",
href: "pods", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Pods" href: "workloads",
expectedSelector: "h5",
expectedText: "Overview",
},
{
href: "pods",
expectedSelector: "h5.title",
expectedText: "Pods"
},
{
href: "deployments",
expectedSelector: "h5.title",
expectedText: "Deployments"
},
{
href: "daemonsets",
expectedSelector: "h5.title",
expectedText: "Daemon Sets"
},
{
href: "statefulsets",
expectedSelector: "h5.title",
expectedText: "Stateful Sets"
},
{
href: "replicasets",
expectedSelector: "h5.title",
expectedText: "Replica Sets"
},
{
href: "jobs",
expectedSelector: "h5.title",
expectedText: "Jobs"
},
{
href: "cronjobs",
expectedSelector: "h5.title",
expectedText: "Cron Jobs"
}]
}, },
{ {
name: "Deployments", testId: "config",
href: "deployments", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Deployments" href: "configmaps",
expectedSelector: "h5.title",
expectedText: "Config Maps"
},
{
href: "secrets",
expectedSelector: "h5.title",
expectedText: "Secrets"
},
{
href: "resourcequotas",
expectedSelector: "h5.title",
expectedText: "Resource Quotas"
},
{
href: "limitranges",
expectedSelector: "h5.title",
expectedText: "Limit Ranges"
},
{
href: "hpa",
expectedSelector: "h5.title",
expectedText: "Horizontal Pod Autoscalers"
},
{
href: "poddisruptionbudgets",
expectedSelector: "h5.title",
expectedText: "Pod Disruption Budgets"
}]
}, },
{ {
name: "DaemonSets", testId: "networks",
href: "daemonsets", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Daemon Sets" href: "services",
expectedSelector: "h5.title",
expectedText: "Services"
},
{
href: "endpoints",
expectedSelector: "h5.title",
expectedText: "Endpoints"
},
{
href: "ingresses",
expectedSelector: "h5.title",
expectedText: "Ingresses"
},
{
href: "network-policies",
expectedSelector: "h5.title",
expectedText: "Network Policies"
}]
}, },
{ {
name: "StatefulSets", testId: "storage",
href: "statefulsets", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Stateful Sets" href: "persistent-volume-claims",
expectedSelector: "h5.title",
expectedText: "Persistent Volume Claims"
},
{
href: "persistent-volumes",
expectedSelector: "h5.title",
expectedText: "Persistent Volumes"
},
{
href: "storage-classes",
expectedSelector: "h5.title",
expectedText: "Storage Classes"
}]
}, },
{ {
name: "ReplicaSets", testId: "namespaces",
href: "replicasets",
expectedSelector: "h5.title", expectedSelector: "h5.title",
expectedText: "Replica Sets" expectedText: "Namespaces",
}, },
{ {
name: "Jobs", testId: "events",
href: "jobs",
expectedSelector: "h5.title", expectedSelector: "h5.title",
expectedText: "Jobs" expectedText: "Events",
}, },
{ {
name: "CronJobs", testId: "apps",
href: "cronjobs", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Cron Jobs" href: "apps/charts",
}] expectedSelector: "div.HelmCharts input",
}, expectedText: ""
{ },
drawer: "Configuration", {
drawerId: "config", href: "apps/releases",
pages: [{ expectedSelector: "h5.title",
name: "ConfigMaps", expectedText: "Releases"
href: "configmaps", }]
expectedSelector: "h5.title",
expectedText: "Config Maps"
}, },
{ {
name: "Secrets", testId: "users",
href: "secrets", subMenu: [
expectedSelector: "h5.title", {
expectedText: "Secrets" href: "service-accounts",
expectedSelector: "h5.title",
expectedText: "Service Accounts"
},
{
href: "role-bindings",
expectedSelector: "h5.title",
expectedText: "Role Bindings"
},
{
href: "roles",
expectedSelector: "h5.title",
expectedText: "Roles"
},
{
href: "pod-security-policies",
expectedSelector: "h5.title",
expectedText: "Pod Security Policies"
}]
}, },
{ {
name: "Resource Quotas", testId: "custom-resources",
href: "resourcequotas", subMenu: [{
expectedSelector: "h5.title", href: "crd/definitions",
expectedText: "Resource Quotas" expectedSelector: "h5.title",
}, expectedText: "Custom Resources"
{ }]
name: "Limit Ranges", }];
href: "limitranges",
expectedSelector: "h5.title",
expectedText: "Limit Ranges"
},
{
name: "HPA",
href: "hpa",
expectedSelector: "h5.title",
expectedText: "Horizontal Pod Autoscalers"
},
{
name: "Pod Disruption Budgets",
href: "poddisruptionbudgets",
expectedSelector: "h5.title",
expectedText: "Pod Disruption Budgets"
}]
},
{
drawer: "Network",
drawerId: "networks",
pages: [{
name: "Services",
href: "services",
expectedSelector: "h5.title",
expectedText: "Services"
},
{
name: "Endpoints",
href: "endpoints",
expectedSelector: "h5.title",
expectedText: "Endpoints"
},
{
name: "Ingresses",
href: "ingresses",
expectedSelector: "h5.title",
expectedText: "Ingresses"
},
{
name: "Network Policies",
href: "network-policies",
expectedSelector: "h5.title",
expectedText: "Network Policies"
}]
},
{
drawer: "Storage",
drawerId: "storage",
pages: [{
name: "Persistent Volume Claims",
href: "persistent-volume-claims",
expectedSelector: "h5.title",
expectedText: "Persistent Volume Claims"
},
{
name: "Persistent Volumes",
href: "persistent-volumes",
expectedSelector: "h5.title",
expectedText: "Persistent Volumes"
},
{
name: "Storage Classes",
href: "storage-classes",
expectedSelector: "h5.title",
expectedText: "Storage Classes"
}]
},
{
drawer: "",
drawerId: "",
pages: [{
name: "Namespaces",
href: "namespaces",
expectedSelector: "h5.title",
expectedText: "Namespaces"
}]
},
{
drawer: "",
drawerId: "",
pages: [{
name: "Events",
href: "events",
expectedSelector: "h5.title",
expectedText: "Events"
}]
},
{
drawer: "Apps",
drawerId: "apps",
pages: [{
name: "Charts",
href: "apps/charts",
expectedSelector: "div.HelmCharts input",
expectedText: ""
},
{
name: "Releases",
href: "apps/releases",
expectedSelector: "h5.title",
expectedText: "Releases"
}]
},
{
drawer: "Access Control",
drawerId: "users",
pages: [{
name: "Service Accounts",
href: "service-accounts",
expectedSelector: "h5.title",
expectedText: "Service Accounts"
},
{
name: "Role Bindings",
href: "role-bindings",
expectedSelector: "h5.title",
expectedText: "Role Bindings"
},
{
name: "Roles",
href: "roles",
expectedSelector: "h5.title",
expectedText: "Roles"
},
{
name: "Pod Security Policies",
href: "pod-security-policies",
expectedSelector: "h5.title",
expectedText: "Pod Security Policies"
}]
},
{
drawer: "Custom Resources",
drawerId: "custom-resources",
pages: [{
name: "Definitions",
href: "crd/definitions",
expectedSelector: "h5.title",
expectedText: "Custom Resources"
}]
}];
tests.forEach(({ drawer = "", drawerId = "", pages }) => { sidebarMenu.forEach(({ testId, expectedSelector, expectedText, subMenu }) => {
if (drawer !== "") { const { sidebarItemRoot, expandIcon, pageLink } = getMainMenuSelectors(testId);
it(`shows ${drawer} drawer`, async () => {
if (subMenu) {
it(`expands submenu for pages in "${testId}"`, async () => {
expect(clusterAdded).toBe(true); expect(clusterAdded).toBe(true);
await app.client.click(`.sidebar-nav [data-test-id="${drawerId}"] span.link-text`); await app.client.click(expandIcon);
await app.client.waitUntilTextExists(`a[href^="/${pages[0].href}"]`, pages[0].name); await app.client.waitForExist(pageLink(subMenu[0].href));
}); });
} subMenu.forEach(({ href, expectedText, expectedSelector }) => {
pages.forEach(({ name, href, expectedSelector, expectedText }) => { it(`opens page "${expectedText.toLowerCase() || href}"`, async () => {
it(`shows ${drawer}->${name} page`, async () => { expect(clusterAdded).toBe(true);
await app.client.click(pageLink(href));
await app.client.waitUntilTextExists(expectedSelector, expectedText);
});
});
} else {
it(`opens page "${testId}"`, async () => {
expect(clusterAdded).toBe(true); expect(clusterAdded).toBe(true);
await app.client.click(`a[href^="/${href}"]`); await app.client.click(sidebarItemRoot);
await app.client.waitUntilTextExists(expectedSelector, expectedText); await app.client.waitUntilTextExists(expectedSelector, expectedText);
}); });
});
if (drawer !== "") {
// hide the drawer
it(`hides ${drawer} drawer`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(`.sidebar-nav [data-test-id="${drawerId}"] span.link-text`);
await expect(app.client.waitUntilTextExists(`a[href^="/${pages[0].href}"]`, pages[0].name, 100)).rejects.toThrow();
});
} }
}); });
}); });
@ -348,7 +308,7 @@ describe("Lens cluster pages", () => {
it(`shows a logs for a pod`, async () => { it(`shows a logs for a pod`, async () => {
expect(clusterAdded).toBe(true); expect(clusterAdded).toBe(true);
// Go to Pods page // Go to Pods page
await app.client.click(".sidebar-nav [data-test-id='workloads'] span.link-text"); await app.client.click(getMainMenuSelectors("workloads").expandIcon);
await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods"); await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods");
await app.client.click('a[href^="/pods"]'); await app.client.click('a[href^="/pods"]');
await app.client.click(".NamespaceSelect"); await app.client.click(".NamespaceSelect");
@ -415,7 +375,7 @@ describe("Lens cluster pages", () => {
it(`creates a pod in ${TEST_NAMESPACE} namespace`, async () => { it(`creates a pod in ${TEST_NAMESPACE} namespace`, async () => {
expect(clusterAdded).toBe(true); expect(clusterAdded).toBe(true);
await app.client.click(".sidebar-nav [data-test-id='workloads'] span.link-text"); await app.client.click(getMainMenuSelectors("workloads").expandIcon);
await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods"); await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods");
await app.client.click('a[href^="/pods"]'); await app.client.click('a[href^="/pods"]');

View File

@ -1,14 +1,10 @@
import { Application } from "spectron"; import { Application } from "spectron";
import * as utils from "../helpers/utils"; import * as utils from "../helpers/utils";
import { addMinikubeCluster, minikubeReady } from "../helpers/minikube"; import { addMinikubeCluster, minikubeReady } from "../helpers/minikube";
import { exec } from "child_process";
import * as util from "util";
export const promiseExec = util.promisify(exec);
jest.setTimeout(60000); jest.setTimeout(60000);
describe("Lens integration tests", () => { describe("Lens workspace tests", () => {
let app: Application; let app: Application;
const ready = minikubeReady("workspace-int-tests"); const ready = minikubeReady("workspace-int-tests");

View File

@ -16,36 +16,50 @@ export enum MetricNodeRole {
WORKER = "worker" WORKER = "worker"
} }
export interface ClusterOverviewStorageState {
metricType: MetricType;
metricNodeRole: MetricNodeRole,
}
@autobind() @autobind()
export class ClusterOverviewStore extends KubeObjectStore<Cluster> { export class ClusterOverviewStore extends KubeObjectStore<Cluster> implements ClusterOverviewStorageState {
api = clusterApi; api = clusterApi;
@observable metrics: Partial<IClusterMetrics> = {}; @observable metrics: Partial<IClusterMetrics> = {};
@observable metricsLoaded = false; @observable metricsLoaded = false;
@observable metricType: MetricType;
@observable metricNodeRole: MetricNodeRole; private storage = createStorage<ClusterOverviewStorageState>("cluster_overview", {
metricType: MetricType.CPU, // setup defaults
metricNodeRole: MetricNodeRole.WORKER,
});
get metricType(): MetricType {
return this.storage.get().metricType;
}
set metricType(value: MetricType) {
this.storage.merge({ metricType: value });
}
get metricNodeRole(): MetricNodeRole {
return this.storage.get().metricNodeRole;
}
set metricNodeRole(value: MetricNodeRole) {
this.storage.merge({ metricNodeRole: value });
}
constructor() { constructor() {
super(); super();
this.resetMetrics(); this.init();
}
// sync user setting with local storage private init() {
const storage = createStorage("cluster_metric_switchers", {}); // TODO: refactor, seems not a correct place to be
// auto-refresh metrics on user-action
Object.assign(this, storage.get());
reaction(() => {
const { metricType, metricNodeRole } = this;
return { metricType, metricNodeRole };
},
settings => storage.set(settings)
);
// auto-update metrics
reaction(() => this.metricNodeRole, () => { reaction(() => this.metricNodeRole, () => {
if (!this.metricsLoaded) return; if (!this.metricsLoaded) return;
this.metrics = {}; this.resetMetrics();
this.metricsLoaded = false;
this.loadMetrics(); this.loadMetrics();
}); });
@ -79,16 +93,16 @@ export class ClusterOverviewStore extends KubeObjectStore<Cluster> {
} }
} }
@action
resetMetrics() { resetMetrics() {
this.metrics = {}; this.metrics = {};
this.metricsLoaded = false; this.metricsLoaded = false;
this.metricType = MetricType.CPU;
this.metricNodeRole = MetricNodeRole.WORKER;
} }
reset() { reset() {
super.reset(); super.reset();
this.resetMetrics(); this.resetMetrics();
this.storage?.reset();
} }
} }

View File

@ -5,14 +5,14 @@ import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api";
import { createPageParam } from "../../navigation"; import { createPageParam } from "../../navigation";
import { apiManager } from "../../api/api-manager"; import { apiManager } from "../../api/api-manager";
const storage = createStorage<string[]>("context_namespaces"); const selectedNamespaces = createStorage<string[]>("selected_namespaces");
export const namespaceUrlParam = createPageParam<string[]>({ export const namespaceUrlParam = createPageParam<string[]>({
name: "namespaces", name: "namespaces",
isSystem: true, isSystem: true,
multiValues: true, multiValues: true,
get defaultValue() { get defaultValue() {
return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default) return selectedNamespaces.get() ?? []; // initial namespaces coming from URL or local-storage (default)
} }
}); });
@ -42,6 +42,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
private async init() { private async init() {
await this.contextReady; await this.contextReady;
await selectedNamespaces.whenReady;
this.setContext(this.initialNamespaces); this.setContext(this.initialNamespaces);
this.autoLoadAllowedNamespaces(); this.autoLoadAllowedNamespaces();
@ -57,7 +58,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
private autoUpdateUrlAndLocalStorage(): IReactionDisposer { private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
return this.onContextChange(namespaces => { return this.onContextChange(namespaces => {
storage.set(namespaces); // save to local-storage selectedNamespaces.set(namespaces); // save to local-storage
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url
}, { }, {
fireImmediately: true, fireImmediately: true,
@ -71,10 +72,9 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
}); });
} }
@computed
private get initialNamespaces(): string[] { private get initialNamespaces(): string[] {
const namespaces = new Set(this.allowedNamespaces); const namespaces = new Set(this.allowedNamespaces);
const prevSelectedNamespaces = storage.get(); const prevSelectedNamespaces = selectedNamespaces.get();
// return previously saved namespaces from local-storage (if any) // return previously saved namespaces from local-storage (if any)
if (prevSelectedNamespaces) { if (prevSelectedNamespaces) {

View File

@ -4,7 +4,6 @@ import "@testing-library/jest-dom/extend-expect";
import { DockTabs } from "../dock-tabs"; import { DockTabs } from "../dock-tabs";
import { dockStore, IDockTab, TabKind } from "../dock.store"; import { dockStore, IDockTab, TabKind } from "../dock.store";
import { observable } from "mobx";
const onChangeTab = jest.fn(); const onChangeTab = jest.fn();
@ -134,9 +133,9 @@ describe("<DockTabs />", () => {
}); });
it("disables 'Close All' & 'Close Other' items if only 1 tab available", () => { it("disables 'Close All' & 'Close Other' items if only 1 tab available", () => {
dockStore.tabs = observable.array<IDockTab>([{ dockStore.tabs = [{
id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" id: "terminal", kind: TabKind.TERMINAL, title: "Terminal"
}]); }];
const { container, getByText } = renderTabs(); const { container, getByText } = renderTabs();
const tab = container.querySelector(".Tab"); const tab = container.querySelector(".Tab");
@ -149,10 +148,10 @@ describe("<DockTabs />", () => {
}); });
it("disables 'Close To The Right' item if last tab clicked", () => { it("disables 'Close To The Right' item if last tab clicked", () => {
dockStore.tabs = observable.array<IDockTab>([ dockStore.tabs = [
{ id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" }, { id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" },
{ id: "logs", kind: TabKind.POD_LOGS, title: "Pod Logs" }, { id: "logs", kind: TabKind.POD_LOGS, title: "Pod Logs" },
]); ];
const { container, getByText } = renderTabs(); const { container, getByText } = renderTabs();
const tab = container.querySelectorAll(".Tab")[1]; const tab = container.querySelectorAll(".Tab")[1];

View File

@ -1,25 +1,30 @@
import { autorun, observable, reaction } from "mobx"; import { autorun, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils"; import { autobind, createStorage, StorageHelper } from "../../utils";
import { dockStore, TabId } from "./dock.store"; import { dockStore, TabId } from "./dock.store";
interface Options<T = any> { interface Options<T = any> {
storageName?: string; // name to sync data with localStorage storageName?: string; // persistent key
storageSerializer?: (data: T) => Partial<T>; // allow to customize data before saving to localStorage storageSerializer?: (data: T) => Partial<T>; // allow to customize data before saving
} }
@autobind() @autobind()
export class DockTabStore<T = any> { export class DockTabStore<T = any> {
protected data = observable.map<TabId, T>([]); private storage?: StorageHelper<Record<TabId, T>>;
protected data = observable.map<TabId, T>();
constructor(protected options: Options<T> = {}) { constructor(protected options: Options<T> = {}) {
const { storageName } = options; this.init();
}
protected async init() {
const { storageName: storageKey } = this.options;
// auto-save to local-storage // auto-save to local-storage
if (storageName) { if (storageKey) {
const storage = createStorage<[TabId, T][]>(storageName, []); this.storage = createStorage(storageKey, {});
await this.storage.whenReady;
this.data.replace(storage.get()); this.data.replace(this.storage.get());
reaction(() => this.serializeData(), (data: T | any) => storage.set(data)); reaction(() => this.serializeData(), data => this.storage.set(data));
} }
// clear data for closed tabs // clear data for closed tabs
@ -34,14 +39,19 @@ export class DockTabStore<T = any> {
}); });
} }
protected serializeData() { protected serializeData(): Record<TabId, T> {
const data = this.data.toJSON();
const { storageSerializer } = this.options; const { storageSerializer } = this.options;
return Array.from(this.data).map(([tabId, tabData]) => { if (storageSerializer) {
if (storageSerializer) return [tabId, storageSerializer(tabData)]; return Object.entries(data).reduce((data, [tabId, tabData]) => {
data[tabId] = storageSerializer(tabData) as T;
return [tabId, tabData]; return data;
}); }, data);
}
return data;
} }
getData(tabId: TabId) { getData(tabId: TabId) {

View File

@ -21,28 +21,72 @@ export interface IDockTab {
pinned?: boolean; // not closable pinned?: boolean; // not closable
} }
export interface DockStorageState {
height: number;
tabs: IDockTab[];
selectedTabId?: TabId;
isOpen?: boolean;
}
@autobind() @autobind()
export class DockStore { export class DockStore implements DockStorageState {
protected initialTabs: IDockTab[] = [ readonly minHeight = 100;
{ id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" },
];
protected storage = createStorage("dock", {}); // keep settings in localStorage
public readonly defaultTabId = this.initialTabs[0].id;
public readonly minHeight = 100;
@observable isOpen = false;
@observable fullSize = false; @observable fullSize = false;
@observable height = this.defaultHeight;
@observable tabs = observable.array<IDockTab>(this.initialTabs); private storage = createStorage<DockStorageState>("dock", {
@observable selectedTabId = this.defaultTabId; height: 300,
tabs: [
{ id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" },
],
});
get isOpen(): boolean {
return this.storage.get().isOpen;
}
set isOpen(isOpen: boolean) {
this.storage.merge({ isOpen });
}
get height(): number {
return this.storage.get().height;
}
set height(height: number) {
this.storage.merge({
height: Math.max(this.minHeight, Math.min(height || this.minHeight, this.maxHeight)),
});
}
get tabs(): IDockTab[] {
return this.storage.get().tabs;
}
set tabs(tabs: IDockTab[]) {
this.storage.merge({ tabs });
}
get selectedTabId(): TabId | undefined {
return this.storage.get().selectedTabId || this.tabs[0]?.id;
}
set selectedTabId(tabId: TabId) {
if (tabId && !this.getTabById(tabId)) return; // skip invalid ids
this.storage.merge({ selectedTabId: tabId });
}
@computed get selectedTab() { @computed get selectedTab() {
return this.tabs.find(tab => tab.id === this.selectedTabId); return this.tabs.find(tab => tab.id === this.selectedTabId);
} }
get defaultHeight() { constructor() {
return Math.round(window.innerHeight / 2.5); this.init();
}
private init() {
// adjust terminal height if window size changes
window.addEventListener("resize", throttle(this.adjustHeight, 250));
} }
get maxHeight() { get maxHeight() {
@ -50,35 +94,14 @@ export class DockStore {
const mainLayoutTabs = 33; const mainLayoutTabs = 33;
const mainLayoutMargin = 16; const mainLayoutMargin = 16;
const dockTabs = 33; const dockTabs = 33;
const preferedMax = window.innerHeight - mainLayoutHeader - mainLayoutTabs - mainLayoutMargin - dockTabs; const preferredMax = window.innerHeight - mainLayoutHeader - mainLayoutTabs - mainLayoutMargin - dockTabs;
return Math.max(preferedMax, this.minHeight); // don't let max < min return Math.max(preferredMax, this.minHeight); // don't let max < min
} }
constructor() { protected adjustHeight() {
Object.assign(this, this.storage.get()); if (this.height < this.minHeight) this.height = this.minHeight;
if (this.height > this.maxHeight) this.height = this.maxHeight;
reaction(() => ({
isOpen: this.isOpen,
selectedTabId: this.selectedTabId,
height: this.height,
tabs: this.tabs.slice(),
}), data => {
this.storage.set(data);
});
// adjust terminal height if window size changes
window.addEventListener("resize", throttle(this.checkMaxHeight, 250));
}
protected checkMaxHeight() {
if (!this.height) {
this.setHeight(this.defaultHeight || this.minHeight);
}
if (this.height > this.maxHeight) {
this.setHeight(this.maxHeight);
}
} }
onResize(callback: () => void, options?: IReactionOptions) { onResize(callback: () => void, options?: IReactionOptions) {
@ -165,7 +188,7 @@ export class DockStore {
if (!tab || tab.pinned) { if (!tab || tab.pinned) {
return; return;
} }
this.tabs.remove(tab); this.tabs = this.tabs.filter(tab => tab.id !== tabId);
if (this.selectedTabId === tab.id) { if (this.selectedTabId === tab.id) {
if (this.tabs.length) { if (this.tabs.length) {
@ -178,8 +201,7 @@ export class DockStore {
if (!terminalStore.isConnected(newTab.id)) this.close(); if (!terminalStore.isConnected(newTab.id)) this.close();
} }
this.selectTab(newTab.id); this.selectTab(newTab.id);
} } else {
else {
this.selectedTabId = null; this.selectedTabId = null;
this.close(); this.close();
} }
@ -219,17 +241,9 @@ export class DockStore {
this.selectedTabId = this.getTabById(tabId)?.id ?? null; this.selectedTabId = this.getTabById(tabId)?.id ?? null;
} }
@action
setHeight(height?: number) {
this.height = Math.max(this.minHeight, Math.min(height || this.minHeight, this.maxHeight));
}
@action @action
reset() { reset() {
this.selectedTabId = this.defaultTabId; this.storage?.reset();
this.tabs.replace(this.initialTabs);
this.setHeight(this.defaultHeight);
this.close();
} }
} }

View File

@ -89,7 +89,7 @@ export class Dock extends React.Component<Props> {
onStart={dockStore.open} onStart={dockStore.open}
onMinExtentSubceed={dockStore.close} onMinExtentSubceed={dockStore.close}
onMinExtentExceed={dockStore.open} onMinExtentExceed={dockStore.open}
onDrag={dockStore.setHeight} onDrag={extent => dockStore.height = extent}
/> />
<div className="tabs-container flex align-center" onDoubleClick={prevDefault(toggle)}> <div className="tabs-container flex align-center" onDoubleClick={prevDefault(toggle)}>
<DockTabs <DockTabs

View File

@ -2,7 +2,7 @@ import "./item-list-layout.scss";
import groupBy from "lodash/groupBy"; import groupBy from "lodash/groupBy";
import React, { ReactNode } from "react"; import React, { ReactNode } from "react";
import { computed, observable, reaction, toJS } from "mobx"; import { computed } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react"; import { disposeOnUnmount, observer } from "mobx-react";
import { ConfirmDialog, ConfirmDialogParams } from "../confirm-dialog"; import { ConfirmDialog, ConfirmDialogParams } from "../confirm-dialog";
import { Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps, TableSortCallback } from "../table"; import { Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps, TableSortCallback } from "../table";
@ -93,29 +93,20 @@ const defaultProps: Partial<ItemListLayoutProps> = {
customizeTableRowProps: () => ({} as TableRowProps), customizeTableRowProps: () => ({} as TableRowProps),
}; };
interface ItemListLayoutUserSettings {
showAppliedFilters?: boolean;
}
@observer @observer
export class ItemListLayout extends React.Component<ItemListLayoutProps> { export class ItemListLayout extends React.Component<ItemListLayoutProps> {
static defaultProps = defaultProps as object; static defaultProps = defaultProps as object;
@observable userSettings: ItemListLayoutUserSettings = { private storage = createStorage("item_list_layout", {
showAppliedFilters: false, showFilters: false, // setup defaults
}; });
constructor(props: ItemListLayoutProps) { get showFilters(): boolean {
super(props); return this.storage.get().showFilters;
}
// keep ui user settings in local storage set showFilters(showFilters: boolean) {
const defaultUserSettings = toJS(this.userSettings); this.storage.merge({ showFilters });
const storage = createStorage<ItemListLayoutUserSettings>("items_list_layout", defaultUserSettings);
Object.assign(this.userSettings, storage.get()); // restore
disposeOnUnmount(this, [
reaction(() => toJS(this.userSettings), settings => storage.set(settings)),
]);
} }
async componentDidMount() { async componentDidMount() {
@ -296,9 +287,9 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
renderFilters() { renderFilters() {
const { hideFilters } = this.props; const { hideFilters } = this.props;
const { isReady, userSettings, filters } = this; const { isReady, filters } = this;
if (!isReady || !filters.length || hideFilters || !userSettings.showAppliedFilters) { if (!isReady || !filters.length || hideFilters || !this.showFilters) {
return; return;
} }
@ -338,13 +329,13 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
} }
renderInfo() { renderInfo() {
const { items, isReady, userSettings, filters } = this; const { items, isReady, filters } = this;
const allItemsCount = this.props.store.getTotalCount(); const allItemsCount = this.props.store.getTotalCount();
const itemsCount = items.length; const itemsCount = items.length;
const isFiltered = isReady && filters.length > 0; const isFiltered = isReady && filters.length > 0;
if (isFiltered) { if (isFiltered) {
const toggleFilters = () => userSettings.showAppliedFilters = !userSettings.showAppliedFilters; const toggleFilters = () => this.showFilters = !this.showFilters;
return ( return (
<><a onClick={toggleFilters}>Filtered</a>: {itemsCount} / {allItemsCount}</> <><a onClick={toggleFilters}>Filtered</a>: {itemsCount} / {allItemsCount}</>

View File

@ -7,7 +7,6 @@
"aside footer"; "aside footer";
grid-template-rows: [header] var(--main-layout-header) [tabs] min-content [main] 1fr [footer] auto; grid-template-rows: [header] var(--main-layout-header) [tabs] min-content [main] 1fr [footer] auto;
grid-template-columns: [sidebar] minmax(var(--main-layout-header), min-content) [main] 1fr; grid-template-columns: [sidebar] minmax(var(--main-layout-header), min-content) [main] 1fr;
height: 100%; height: 100%;
> header { > header {
@ -22,18 +21,15 @@
background: $sidebarBackground; background: $sidebarBackground;
white-space: nowrap; white-space: nowrap;
transition: width 150ms cubic-bezier(0.4, 0, 0.2, 1); transition: width 150ms cubic-bezier(0.4, 0, 0.2, 1);
width: var(--sidebar-width);
&.pinned { &.compact {
width: var(--sidebar-width);
}
&:not(.pinned) {
position: absolute; position: absolute;
width: var(--main-layout-header); width: var(--main-layout-header);
height: 100%; height: 100%;
overflow: hidden; overflow: hidden;
&.accessible:hover { &:hover {
width: var(--sidebar-width); width: var(--sidebar-width);
transition-delay: 750ms; transition-delay: 750ms;
box-shadow: 3px 3px 16px rgba(0, 0, 0, 0.35); box-shadow: 3px 3px 16px rgba(0, 0, 0, 0.35);

View File

@ -1,15 +1,15 @@
import "./main-layout.scss"; import "./main-layout.scss";
import React from "react"; import React from "react";
import { observable, reaction } from "mobx"; import { observer } from "mobx-react";
import { disposeOnUnmount, observer } from "mobx-react";
import { getHostedCluster } from "../../../common/cluster-store"; import { getHostedCluster } from "../../../common/cluster-store";
import { autobind, createStorage, cssNames } from "../../utils"; import { cssNames } from "../../utils";
import { Dock } from "../dock"; import { Dock } from "../dock";
import { ErrorBoundary } from "../error-boundary"; import { ErrorBoundary } from "../error-boundary";
import { ResizeDirection, ResizeGrowthDirection, ResizeSide, ResizingAnchor } from "../resizing-anchor"; import { ResizeDirection, ResizeGrowthDirection, ResizeSide, ResizingAnchor } from "../resizing-anchor";
import { MainLayoutHeader } from "./main-layout-header"; import { MainLayoutHeader } from "./main-layout-header";
import { Sidebar } from "./sidebar"; import { Sidebar } from "./sidebar";
import { sidebarStorage } from "./sidebar-storage";
export interface MainLayoutProps { export interface MainLayoutProps {
className?: any; className?: any;
@ -20,65 +20,41 @@ export interface MainLayoutProps {
@observer @observer
export class MainLayout extends React.Component<MainLayoutProps> { export class MainLayout extends React.Component<MainLayoutProps> {
public storage = createStorage("main_layout", { onSidebarCompactModeChange = () => {
pinnedSidebar: true, sidebarStorage.merge(draft => {
sidebarWidth: 200, draft.compact = !draft.compact;
}); });
@observable isPinned = this.storage.get().pinnedSidebar;
@observable isAccessible = true;
@observable sidebarWidth = this.storage.get().sidebarWidth;
@disposeOnUnmount syncPinnedStateWithStorage = reaction(
() => this.isPinned,
(isPinned) => this.storage.merge({ pinnedSidebar: isPinned })
);
@disposeOnUnmount syncWidthStateWithStorage = reaction(
() => this.sidebarWidth,
(sidebarWidth) => this.storage.merge({ sidebarWidth })
);
toggleSidebar = () => {
this.isPinned = !this.isPinned;
this.isAccessible = false;
setTimeout(() => (this.isAccessible = true), 250);
}; };
getSidebarSize = () => { onSidebarResize = (width: number) => {
return { sidebarStorage.merge({ width });
"--sidebar-width": `${this.sidebarWidth}px`,
};
}; };
@autobind()
adjustWidth(newWidth: number): void {
this.sidebarWidth = newWidth;
}
render() { render() {
const { className, headerClass, footer, footerClass, children } = this.props;
const cluster = getHostedCluster(); const cluster = getHostedCluster();
const { onSidebarCompactModeChange, onSidebarResize } = this;
const { className, headerClass, footer, footerClass, children } = this.props;
const { compact, width: sidebarWidth } = sidebarStorage.get();
const style = { "--sidebar-width": `${sidebarWidth}px` } as React.CSSProperties;
if (!cluster) { if (!cluster) {
return null; // fix: skip render when removing active (visible) cluster return null; // fix: skip render when removing active (visible) cluster
} }
return ( return (
<div className={cssNames("MainLayout", className)} style={this.getSidebarSize() as any}> <div className={cssNames("MainLayout", className)} style={style}>
<MainLayoutHeader className={headerClass} cluster={cluster} /> <MainLayoutHeader className={headerClass} cluster={cluster}/>
<aside className={cssNames("flex column", { pinned: this.isPinned, accessible: this.isAccessible })}> <aside className={cssNames("flex column", { compact })}>
<Sidebar className="box grow" isPinned={this.isPinned} toggle={this.toggleSidebar} /> <Sidebar className="box grow" compact={compact} toggle={onSidebarCompactModeChange}/>
<ResizingAnchor <ResizingAnchor
direction={ResizeDirection.HORIZONTAL} direction={ResizeDirection.HORIZONTAL}
placement={ResizeSide.TRAILING} placement={ResizeSide.TRAILING}
growthDirection={ResizeGrowthDirection.LEFT_TO_RIGHT} growthDirection={ResizeGrowthDirection.LEFT_TO_RIGHT}
getCurrentExtent={() => this.sidebarWidth} getCurrentExtent={() => sidebarWidth}
onDrag={this.adjustWidth} onDrag={onSidebarResize}
onDoubleClick={this.toggleSidebar} onDoubleClick={onSidebarCompactModeChange}
disabled={!this.isPinned} disabled={compact}
minExtent={120} minExtent={120}
maxExtent={400} maxExtent={400}
/> />
@ -88,7 +64,7 @@ export class MainLayout extends React.Component<MainLayoutProps> {
<ErrorBoundary>{children}</ErrorBoundary> <ErrorBoundary>{children}</ErrorBoundary>
</main> </main>
<footer className={footerClass}>{footer ?? <Dock />}</footer> <footer className={footerClass}>{footer ?? <Dock/>}</footer>
</div> </div>
); );
} }

View File

@ -1,7 +0,0 @@
import React from "react";
export const SidebarContext = React.createContext<SidebarContextValue>({ pinned: false });
export type SidebarContextValue = {
pinned: boolean;
};

View File

@ -1,37 +1,48 @@
.SidebarNavItem { .SidebarItem {
$itemSpacing: floor($unit / 2.6) floor($unit / 1.6); $itemSpacing: floor($unit / 2.6) floor($unit / 1.6);
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 100%; width: 100%;
user-select: none; user-select: none;
flex-shrink: 0;
.nav-item { .nav-item {
cursor: pointer;
width: inherit;
display: flex;
align-items: center;
text-decoration: none;
border: none;
padding: $itemSpacing; padding: $itemSpacing;
border: none;
cursor: pointer;
a {
overflow: hidden;
text-overflow: ellipsis;
text-decoration: none;
vertical-align: middle;
flex-grow: 1;
min-width: 100px;
}
&.active, &:hover { &.active, &:hover {
background: $lensBlue; background: $lensBlue;
color: $sidebarActiveColor; color: $sidebarActiveColor;
} }
}
.expand-icon { .expand-icon {
--size: 20px; --size: 20px;
}
} }
.sub-menu { .sub-menu {
border-left: 4px solid transparent; border-left: 4px solid transparent;
&:empty, .compact & {
display: none;
}
&.active { &.active {
border-left-color: $lensBlue; border-left-color: $lensBlue;
} }
a, .SidebarNavItem { a, .SidebarItem {
display: block; display: block;
border: none; border: none;
text-decoration: none; text-decoration: none;
@ -55,22 +66,5 @@
color: $sidebarSubmenuActiveColor; color: $sidebarSubmenuActiveColor;
} }
} }
.sub-menu-parent {
padding-left: 27px;
font-weight: 500;
.nav-item {
&:hover {
background: transparent;
}
}
.sub-menu {
a {
padding-left: $padding * 3;
}
}
}
} }
} }

View File

@ -0,0 +1,90 @@
import "./sidebar-item.scss";
import React from "react";
import { cssNames, prevDefault } from "../../utils";
import { observer } from "mobx-react";
import { NavLink } from "react-router-dom";
import { Icon } from "../icon";
import { TabLayoutRoute } from "./tab-layout";
import { sidebarStorage } from "./sidebar-storage";
interface SidebarItemProps {
id: string; // Used to save nav item collapse/expand state in local storage
url: string;
text: React.ReactNode | string;
className?: string;
icon?: React.ReactNode;
isHidden?: boolean;
isActive?: boolean;
subMenus?: TabLayoutRoute[];
onToggle?(id: string, meta: { props: SidebarItemProps, event: React.MouseEvent }): void;
}
@observer
export class SidebarItem extends React.Component<SidebarItemProps> {
static displayName = "SidebarItem";
get id(): string {
return this.props.id; // unique id, used in storage and integration tests
}
get expanded(): boolean {
return Boolean(sidebarStorage.get().expanded[this.id]);
}
get compact(): boolean {
return Boolean(sidebarStorage.get().compact);
}
toggleExpand = (event: React.MouseEvent) => {
sidebarStorage.merge(draft => {
draft.expanded[this.id] = !draft.expanded[this.id];
});
this.props.onToggle?.(this.id, {
props: this.props,
event,
});
};
render() {
const { isHidden, isActive, subMenus = [], icon, text, children, url, className } = this.props;
if (isHidden) return null;
const { id, expanded, compact } = this;
const isExpandable = (subMenus.length > 0 || children) && !compact;
const classNames = cssNames(SidebarItem.displayName, className, { compact });
return (
<div className={classNames} data-test-id={id}>
<div className={cssNames("nav-item flex align-center", { active: isActive })}>
<NavLink to={url} isActive={() => isActive}>
{icon} <span className="link-text">{text}</span>
</NavLink>
{isExpandable && (
<Icon
className="expand-icon box right"
material={expanded ? "keyboard_arrow_up" : "keyboard_arrow_down"}
onClick={prevDefault(this.toggleExpand)}
/>
)}
</div>
{isExpandable && (
<ul className={cssNames("sub-menu", { active: isActive })}>
{subMenus.map(({ title, url }) => (
<NavLink key={url} to={url} className={cssNames({ visible: expanded })}>
{title}
</NavLink>
))}
{React.Children.toArray(children).map((child: React.ReactElement<any>) => {
return React.cloneElement(child, {
className: cssNames(child.props.className, { visible: expanded }),
});
})}
</ul>
)}
</div>
);
}
}

View File

@ -1,83 +0,0 @@
import "./sidebar-nav-item.scss";
import React from "react";
import { computed, observable, reaction } from "mobx";
import { observer } from "mobx-react";
import { NavLink } from "react-router-dom";
import { createStorage, cssNames } from "../../utils";
import { Icon } from "../icon";
import { SidebarContext } from "./sidebar-context";
import type { TabLayoutRoute } from "./tab-layout";
import type { SidebarContextValue } from "./sidebar-context";
interface SidebarNavItemProps {
id: string; // Used to save nav item collapse/expand state in local storage
url: string;
text: React.ReactNode | string;
className?: string;
icon?: React.ReactNode;
isHidden?: boolean;
isActive?: boolean;
subMenus?: TabLayoutRoute[];
}
const navItemStorage = createStorage<[string, boolean][]>("sidebar_menu_item", []);
const navItemState = observable.map<string, boolean>(navItemStorage.get());
reaction(() => [...navItemState], (value) => navItemStorage.set(value));
@observer
export class SidebarNavItem extends React.Component<SidebarNavItemProps> {
static contextType = SidebarContext;
public context: SidebarContextValue;
@computed get isExpanded() {
return navItemState.get(this.props.id);
}
toggleSubMenu = () => {
navItemState.set(this.props.id, !this.isExpanded);
};
render() {
const { isHidden, isActive, subMenus = [], icon, text, url, children, className, id } = this.props;
if (isHidden) {
return null;
}
const extendedView = (subMenus.length > 0 || children) && this.context.pinned;
if (extendedView) {
return (
<div className={cssNames("SidebarNavItem", className)} data-test-id={id}>
<div className={cssNames("nav-item", { active: isActive })} onClick={this.toggleSubMenu}>
{icon}
<span className="link-text">{text}</span>
<Icon className="expand-icon" material={this.isExpanded ? "keyboard_arrow_up" : "keyboard_arrow_down"}/>
</div>
<ul className={cssNames("sub-menu", { active: isActive })}>
{subMenus.map(({ title, url }) => (
<NavLink key={url} to={url} className={cssNames({ visible: this.isExpanded })}>
{title}
</NavLink>
))}
{React.Children.toArray(children).map((child: React.ReactElement<any>) => {
return React.cloneElement(child, {
className: cssNames(child.props.className, { visible: this.isExpanded }),
});
})}
</ul>
</div>
);
}
return (
<NavLink className={cssNames("SidebarNavItem", className)} to={url} isActive={() => isActive}>
{icon}
<span className="link-text">{text}</span>
</NavLink>
);
}
}

View File

@ -0,0 +1,15 @@
import { createStorage } from "../../utils";
export interface SidebarStorageState {
width: number;
compact: boolean;
expanded: {
[itemId: string]: boolean;
}
}
export const sidebarStorage = createStorage<SidebarStorageState>("sidebar", {
width: 200, // sidebar size in non-compact mode
compact: false, // compact-mode (icons only)
expanded: {},
});

View File

@ -2,9 +2,9 @@
$iconSize: 24px; $iconSize: 24px;
$itemSpacing: floor($unit / 2.6) floor($unit / 1.6); $itemSpacing: floor($unit / 2.6) floor($unit / 1.6);
&.pinned { &.compact {
.sidebar-nav { .sidebar-nav {
overflow: auto; @include hidden-scrollbar; // fix: scrollbar overlaps icons
} }
} }
@ -45,6 +45,7 @@
.sidebar-nav { .sidebar-nav {
padding: $padding / 1.5 0; padding: $padding / 1.5 0;
overflow: auto;
.Icon { .Icon {
--size: #{$iconSize}; --size: #{$iconSize};
@ -79,6 +80,25 @@
} }
} }
.SidebarItem {
&.crd-group {
padding-left: 27px;
font-weight: 500;
.nav-item {
&:hover {
background: transparent;
}
}
.sub-menu {
a {
padding-left: $padding * 3;
}
}
}
}
.loading { .loading {
padding: $padding; padding: $padding;
text-align: center; text-align: center;

View File

@ -28,17 +28,18 @@ import { isActiveRoute } from "../../navigation";
import { isAllowedResource } from "../../../common/rbac"; import { isAllowedResource } from "../../../common/rbac";
import { Spinner } from "../spinner"; import { Spinner } from "../spinner";
import { ClusterPageMenuRegistration, clusterPageMenuRegistry, clusterPageRegistry, getExtensionPageUrl } from "../../../extensions/registries"; import { ClusterPageMenuRegistration, clusterPageMenuRegistry, clusterPageRegistry, getExtensionPageUrl } from "../../../extensions/registries";
import { SidebarNavItem } from "./sidebar-nav-item"; import { SidebarItem } from "./sidebar-item";
import { SidebarContext } from "./sidebar-context";
interface Props { interface Props {
className?: string; className?: string;
isPinned: boolean; compact?: boolean; // compact-mode view: show only icons and expand on :hover
toggle(): void; toggle(): void; // compact-mode updater
} }
@observer @observer
export class Sidebar extends React.Component<Props> { export class Sidebar extends React.Component<Props> {
static displayName = "Sidebar";
async componentDidMount() { async componentDidMount() {
crdStore.reloadAll(); crdStore.reloadAll();
} }
@ -59,10 +60,10 @@ export class Sidebar extends React.Component<Props> {
}); });
return ( return (
<SidebarNavItem <SidebarItem
key={group} key={group}
id={`crd-${group}`} id={`crd-${group}`}
className="sub-menu-parent" className="crd-group"
url={crdURL({ query: { groups: group } })} url={crdURL({ query: { groups: group } })}
subMenus={submenus} subMenus={submenus}
text={group} text={group}
@ -117,7 +118,7 @@ export class Sidebar extends React.Component<Props> {
} }
return ( return (
<SidebarNavItem <SidebarItem
key={id} key={id}
id={id} id={id}
url={pageUrl} url={pageUrl}
@ -131,125 +132,123 @@ export class Sidebar extends React.Component<Props> {
} }
render() { render() {
const { toggle, isPinned, className } = this.props; const { toggle, compact, className } = this.props;
const query = namespaceUrlParam.toObjectParam(); const query = namespaceUrlParam.toObjectParam();
return ( return (
<SidebarContext.Provider value={{ pinned: isPinned }}> <div className={cssNames(Sidebar.displayName, "flex column", { compact }, className)}>
<div className={cssNames("Sidebar flex column", className, { pinned: isPinned })}> <div className="header flex align-center">
<div className="header flex align-center"> <NavLink exact to="/" className="box grow">
<NavLink exact to="/" className="box grow"> <Icon svg="logo-lens" className="logo-icon"/>
<Icon svg="logo-lens" className="logo-icon"/> <div className="logo-text">Lens</div>
<div className="logo-text">Lens</div> </NavLink>
</NavLink> <Icon
<Icon focusable={false}
className="pin-icon" className="pin-icon"
tooltip="Compact view" tooltip="Compact view"
material={isPinned ? "keyboard_arrow_left" : "keyboard_arrow_right"} material={compact ? "keyboard_arrow_left" : "keyboard_arrow_right"}
onClick={toggle} onClick={toggle}
focusable={false} />
/>
</div>
<div className="sidebar-nav flex column box grow-fixed">
<SidebarNavItem
id="cluster"
isActive={isActiveRoute(clusterRoute)}
isHidden={!isAllowedResource("nodes")}
url={clusterURL()}
text="Cluster"
icon={<Icon svg="kube"/>}
/>
<SidebarNavItem
id="nodes"
isActive={isActiveRoute(nodesRoute)}
isHidden={!isAllowedResource("nodes")}
url={nodesURL()}
text="Nodes"
icon={<Icon svg="nodes"/>}
/>
<SidebarNavItem
id="workloads"
isActive={isActiveRoute(workloadsRoute)}
isHidden={Workloads.tabRoutes.length == 0}
url={workloadsURL({ query })}
subMenus={Workloads.tabRoutes}
text="Workloads"
icon={<Icon svg="workloads"/>}
/>
<SidebarNavItem
id="config"
isActive={isActiveRoute(configRoute)}
isHidden={Config.tabRoutes.length == 0}
url={configURL({ query })}
subMenus={Config.tabRoutes}
text="Configuration"
icon={<Icon material="list"/>}
/>
<SidebarNavItem
id="networks"
isActive={isActiveRoute(networkRoute)}
isHidden={Network.tabRoutes.length == 0}
url={networkURL({ query })}
subMenus={Network.tabRoutes}
text="Network"
icon={<Icon material="device_hub"/>}
/>
<SidebarNavItem
id="storage"
isActive={isActiveRoute(storageRoute)}
isHidden={Storage.tabRoutes.length == 0}
url={storageURL({ query })}
subMenus={Storage.tabRoutes}
icon={<Icon svg="storage"/>}
text="Storage"
/>
<SidebarNavItem
id="namespaces"
isActive={isActiveRoute(namespacesRoute)}
isHidden={!isAllowedResource("namespaces")}
url={namespacesURL()}
icon={<Icon material="layers"/>}
text="Namespaces"
/>
<SidebarNavItem
id="events"
isActive={isActiveRoute(eventRoute)}
isHidden={!isAllowedResource("events")}
url={eventsURL({ query })}
icon={<Icon material="access_time"/>}
text="Events"
/>
<SidebarNavItem
id="apps"
isActive={isActiveRoute(appsRoute)}
url={appsURL({ query })}
subMenus={Apps.tabRoutes}
icon={<Icon material="apps"/>}
text="Apps"
/>
<SidebarNavItem
id="users"
isActive={isActiveRoute(usersManagementRoute)}
url={usersManagementURL({ query })}
subMenus={UserManagement.tabRoutes}
icon={<Icon material="security"/>}
text="Access Control"
/>
<SidebarNavItem
id="custom-resources"
isActive={isActiveRoute(crdRoute)}
isHidden={!isAllowedResource("customresourcedefinitions")}
url={crdURL()}
subMenus={CustomResources.tabRoutes}
icon={<Icon material="extension"/>}
text="Custom Resources"
>
{this.renderCustomResources()}
</SidebarNavItem>
{this.renderRegisteredMenus()}
</div>
</div> </div>
</SidebarContext.Provider> <div className={cssNames("sidebar-nav flex column box grow-fixed", { compact })}>
<SidebarItem
id="cluster"
isActive={isActiveRoute(clusterRoute)}
isHidden={!isAllowedResource("nodes")}
url={clusterURL()}
text="Cluster"
icon={<Icon svg="kube"/>}
/>
<SidebarItem
id="nodes"
isActive={isActiveRoute(nodesRoute)}
isHidden={!isAllowedResource("nodes")}
url={nodesURL()}
text="Nodes"
icon={<Icon svg="nodes"/>}
/>
<SidebarItem
id="workloads"
isActive={isActiveRoute(workloadsRoute)}
isHidden={Workloads.tabRoutes.length == 0}
url={workloadsURL({ query })}
subMenus={Workloads.tabRoutes}
text="Workloads"
icon={<Icon svg="workloads"/>}
/>
<SidebarItem
id="config"
isActive={isActiveRoute(configRoute)}
isHidden={Config.tabRoutes.length == 0}
url={configURL({ query })}
subMenus={Config.tabRoutes}
text="Configuration"
icon={<Icon material="list"/>}
/>
<SidebarItem
id="networks"
isActive={isActiveRoute(networkRoute)}
isHidden={Network.tabRoutes.length == 0}
url={networkURL({ query })}
subMenus={Network.tabRoutes}
text="Network"
icon={<Icon material="device_hub"/>}
/>
<SidebarItem
id="storage"
isActive={isActiveRoute(storageRoute)}
isHidden={Storage.tabRoutes.length == 0}
url={storageURL({ query })}
subMenus={Storage.tabRoutes}
icon={<Icon svg="storage"/>}
text="Storage"
/>
<SidebarItem
id="namespaces"
isActive={isActiveRoute(namespacesRoute)}
isHidden={!isAllowedResource("namespaces")}
url={namespacesURL()}
icon={<Icon material="layers"/>}
text="Namespaces"
/>
<SidebarItem
id="events"
isActive={isActiveRoute(eventRoute)}
isHidden={!isAllowedResource("events")}
url={eventsURL({ query })}
icon={<Icon material="access_time"/>}
text="Events"
/>
<SidebarItem
id="apps"
isActive={isActiveRoute(appsRoute)}
url={appsURL({ query })}
subMenus={Apps.tabRoutes}
icon={<Icon material="apps"/>}
text="Apps"
/>
<SidebarItem
id="users"
isActive={isActiveRoute(usersManagementRoute)}
url={usersManagementURL({ query })}
subMenus={UserManagement.tabRoutes}
icon={<Icon material="security"/>}
text="Access Control"
/>
<SidebarItem
id="custom-resources"
isActive={isActiveRoute(crdRoute)}
isHidden={!isAllowedResource("customresourcedefinitions")}
url={crdURL()}
subMenus={CustomResources.tabRoutes}
icon={<Icon material="extension"/>}
text="Custom Resources"
>
{this.renderCustomResources()}
</SidebarItem>
{this.renderRegisteredMenus()}
</div>
</div>
); );
} }
} }

View File

@ -3,11 +3,11 @@
import { app, remote } from "electron"; import { app, remote } from "electron";
import path from "path"; import path from "path";
import { ensureDirSync, readJsonSync, writeJson } from "fs-extra"; import { ensureDir, readJson, writeJson } from "fs-extra";
import type { CreateObservableOptions } from "mobx/lib/api/observable"; import type { CreateObservableOptions } from "mobx/lib/api/observable";
import { action, comparer, observable, reaction, toJS, when } from "mobx"; import { action, comparer, observable, reaction, toJS, when } from "mobx";
import produce, { Draft, setAutoFreeze } from "immer"; import produce, { Draft, setAutoFreeze } from "immer";
import { isEqual, isFunction, isObject } from "lodash"; import { isEqual, isFunction, isObject, noop } from "lodash";
setAutoFreeze(false); // allow to merge observables setAutoFreeze(false); // allow to merge observables
@ -26,17 +26,17 @@ export interface StorageConfiguration<T> {
export interface StorageAdapter<T> { export interface StorageAdapter<T> {
[metadata: string]: any; [metadata: string]: any;
getItem(key: string): T; // import getItem(key: string): T | Promise<T>; // import
setItem(key: string, value: T): void; // export setItem(key: string, value: T): void; // export
removeItem?(key: string): void; // if not provided setItem(key,undefined) will be used removeItem?(key: string): void; // if not provided setItem(key,undefined) will be used
onChange?(data: { key: string, value: T, oldValue?: T }): void; onChange?(change: { key: string, value: T, oldValue?: T }): void;
} }
export class StorageHelper<T> { export class StorageHelper<T> {
static defaultOptions: StorageHelperOptions<any> = { static defaultOptions: StorageHelperOptions<any> = {
autoInit: true, autoInit: true,
get storage() { get storage() {
return jsonFileSyncStorageAdapter; return jsonFileStorageAdapter;
}, },
observable: { observable: {
deep: true, deep: true,
@ -60,11 +60,11 @@ export class StorageHelper<T> {
} }
@action @action
init() { async init() {
if (this.initialized) return; if (this.initialized) return;
try { try {
const value = this.load(); const value = await this.load();
const notEmpty = value != null; const notEmpty = value != null;
const notDefault = !this.isDefaultValue(value); const notDefault = !this.isDefaultValue(value);
@ -109,7 +109,7 @@ export class StorageHelper<T> {
this.storage.setItem(this.key, value); this.storage.setItem(this.key, value);
} }
load(): T { async load(): Promise<T> {
return this.storage.getItem(this.key); return this.storage.getItem(this.key);
} }
@ -158,8 +158,11 @@ export const localStorageAdapter: StorageAdapter<object> = {
} }
}; };
// TODO: remove after merge https://github.com/lensapp/lens/pull/2269 /**
export const jsonFileSyncStorageAdapter: StorageAdapter<object> = { * Keep intended window.localStorage state in external JSON-file.
* Reason: app creates random ports between restarts and as a result storage not persistent.
*/
export const jsonFileStorageAdapter: StorageAdapter<object> = {
cwd: path.resolve((app || remote.app).getPath("userData"), "lens-local-storage"), cwd: path.resolve((app || remote.app).getPath("userData"), "lens-local-storage"),
data: observable.map<string, any>([], { deep: false }), data: observable.map<string, any>([], { deep: false }),
initialized: false, initialized: false,
@ -170,34 +173,31 @@ export const jsonFileSyncStorageAdapter: StorageAdapter<object> = {
return path.resolve(this.cwd, `${clusterId ?? "app"}.json`); return path.resolve(this.cwd, `${clusterId ?? "app"}.json`);
}, },
init() { async init() {
if (this.initialized) return; if (this.initialized) return;
try { const data = await readJson(this.filePath).catch(noop);
ensureDirSync(this.cwd, { mode: 0o755 });
const data = readJsonSync(this.filePath, { throws: false }) || {};
if (data) {
this.data.replace(data); this.data.replace(data);
this.bindAutoSave();
} catch (error) {
console.error(`[init]: ${this.filePath} failed: ${error}`, this);
} finally {
this.initialized = true;
} }
this.bindAutoSave();
this.initialized = true;
}, },
bindAutoSave() { bindAutoSave() {
return reaction(() => this.data.toJSON(), async (data) => { return reaction(() => this.data.toJSON(), async (data) => {
try { try {
await ensureDir(this.cwd, { mode: 0o755 });
await writeJson(this.filePath, data, { spaces: 2 }); await writeJson(this.filePath, data, { spaces: 2 });
} catch (error) { } catch (error) {
console.error(`[save]: ${this.filePath} failed: ${error}`, this); console.error(`[save]: ${this.filePath}: ${error}`, this);
} }
}); });
}, },
getItem(key: string) { async getItem(key: string) {
this.init(); await this.init();
return this.data.get(key); return this.data.get(key);
}, },