Persist local-storage in external json-file (#2279)

This commit is contained in:
Roman authored and GitHub committed 2021-03-18 08:36:34 -04:00
1 parent da5a4bbdf4
commit aedcc6d70e
32 files changed
+1025 -618

No files matched your search

@@ -16,36 +16,50 @@ export enum MetricNodeRole {
WORKER = "worker"
}
export interface ClusterOverviewStorageState {
metricType: MetricType;
metricNodeRole: MetricNodeRole,
}
@autobind()
export class ClusterOverviewStore extends KubeObjectStore<Cluster> {
export class ClusterOverviewStore extends KubeObjectStore<Cluster> implements ClusterOverviewStorageState {
api = clusterApi;
@observable metrics: Partial<IClusterMetrics> = {};
@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() {
super();
this.resetMetrics();
this.init();
}
// sync user setting with local storage
const storage = createStorage("cluster_metric_switchers", {});
Object.assign(this, storage.get());
reaction(() => {
const { metricType, metricNodeRole } = this;
return { metricType, metricNodeRole };
},
settings => storage.set(settings)
);
// auto-update metrics
private init() {
// TODO: refactor, seems not a correct place to be
// auto-refresh metrics on user-action
reaction(() => this.metricNodeRole, () => {
if (!this.metricsLoaded) return;
this.metrics = {};
this.metricsLoaded = false;
this.resetMetrics();
this.loadMetrics();
});
@@ -79,16 +93,16 @@ export class ClusterOverviewStore extends KubeObjectStore<Cluster> {
}
}
@action
resetMetrics() {
this.metrics = {};
this.metricsLoaded = false;
this.metricType = MetricType.CPU;
this.metricNodeRole = MetricNodeRole.WORKER;
}
reset() {
super.reset();
this.resetMetrics();
this.storage?.reset();
}
}
@@ -29,23 +29,31 @@ enum columnId {
@observer
export class CrdList extends React.Component {
@computed get groups(): string[] {
get selectedGroups(): string[] {
return crdGroupsUrlParam.get();
}
onSelectGroup(group: string) {
const groups = new Set(this.groups);
@computed get items() {
if (this.selectedGroups.length) {
return crdStore.items.filter(item => this.selectedGroups.includes(item.getGroup()));
}
return crdStore.items; // show all by default
}
toggleSelection(group: string) {
const groups = new Set(crdGroupsUrlParam.get());
if (groups.has(group)) {
groups.delete(group); // toggle selection
groups.delete(group);
} else {
groups.add(group);
}
crdGroupsUrlParam.set(Array.from(groups));
crdGroupsUrlParam.set([...groups]);
}
render() {
const selectedGroups = this.groups;
const { items, selectedGroups } = this;
const sortingCallbacks = {
[columnId.kind]: (crd: CustomResourceDefinition) => crd.getResourceKind(),
[columnId.group]: (crd: CustomResourceDefinition) => crd.getGroup(),
@@ -60,13 +68,9 @@ export class CrdList extends React.Component {
className="CrdList"
isClusterScoped={true}
store={crdStore}
items={items}
sortingCallbacks={sortingCallbacks}
searchFilters={Object.values(sortingCallbacks)}
filterItems={[
(items: CustomResourceDefinition[]) => {
return selectedGroups.length ? items.filter(item => selectedGroups.includes(item.getGroup())) : items;
}
]}
renderHeaderTitle="Custom Resources"
customizeHeader={() => {
let placeholder = <>All groups</>;
@@ -81,7 +85,8 @@ export class CrdList extends React.Component {
className="group-select"
placeholder={placeholder}
options={Object.keys(crdStore.groups)}
onChange={({ value: group }: SelectOption) => this.onSelectGroup(group)}
onChange={({ value: group }: SelectOption) => this.toggleSelection(group)}
closeMenuOnSelect={false}
controlShouldRenderValue={false}
formatOptionLabel={({ value: group }: SelectOption) => {
const isSelected = selectedGroups.includes(group);
@@ -5,15 +5,13 @@ import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api";
import { createPageParam } from "../../navigation";
import { apiManager } from "../../api/api-manager";
const storage = createStorage<string[]>("context_namespaces");
const selectedNamespaces = createStorage<string[]>("selected_namespaces");
export const namespaceUrlParam = createPageParam<string[]>({
name: "namespaces",
isSystem: true,
multiValues: true,
get defaultValue() {
return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default)
}
defaultValue: [],
});
export function getDummyNamespace(name: string) {
@@ -42,6 +40,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
private async init() {
await this.contextReady;
await selectedNamespaces.whenReady;
this.setContext(this.initialNamespaces);
this.autoLoadAllowedNamespaces();
@@ -57,7 +56,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
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
}, {
fireImmediately: true,
@@ -71,10 +70,9 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
});
}
@computed
private get initialNamespaces(): string[] {
const namespaces = new Set(this.allowedNamespaces);
const prevSelectedNamespaces = storage.get();
const prevSelectedNamespaces = selectedNamespaces.get();
// return previously saved namespaces from local-storage (if any)
if (prevSelectedNamespaces) {
@@ -4,7 +4,6 @@ import "@testing-library/jest-dom/extend-expect";
import { DockTabs } from "../dock-tabs";
import { dockStore, IDockTab, TabKind } from "../dock.store";
import { observable } from "mobx";
const onChangeTab = jest.fn();
@@ -134,9 +133,9 @@ describe("<DockTabs />", () => {
});
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"
}]);
}];
const { container, getByText } = renderTabs();
const tab = container.querySelector(".Tab");
@@ -149,10 +148,10 @@ describe("<DockTabs />", () => {
});
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: "logs", kind: TabKind.POD_LOGS, title: "Pod Logs" },
]);
];
const { container, getByText } = renderTabs();
const tab = container.querySelectorAll(".Tab")[1];
@@ -6,7 +6,7 @@ import { dockStore, IDockTab, TabKind } from "./dock.store";
export class CreateResourceStore extends DockTabStore<string> {
constructor() {
super({
storageName: "create_resource"
storageKey: "create_resource"
});
}
}
+45 -21
View File
@@ -1,25 +1,40 @@
import { autorun, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils";
import { autorun, observable, reaction, toJS } from "mobx";
import { autobind, createStorage, StorageHelper } from "../../utils";
import { dockStore, TabId } from "./dock.store";
interface Options<T = any> {
storageName?: string; // name to sync data with localStorage
storageSerializer?: (data: T) => Partial<T>; // allow to customize data before saving to localStorage
export interface DockTabStoreOptions {
autoInit?: boolean; // load data from storage when `storageKey` is provided and bind events, default: true
storageKey?: string; // save data to persistent storage under the key
}
@autobind()
export class DockTabStore<T = any> {
protected data = observable.map<TabId, T>([]);
export type DockTabStorageState<T> = Record<TabId, T>;
constructor(protected options: Options<T> = {}) {
const { storageName } = options;
@autobind()
export class DockTabStore<T> {
protected storage?: StorageHelper<DockTabStorageState<T>>;
protected data = observable.map<TabId, T>();
constructor(protected options: DockTabStoreOptions = {}) {
this.options = {
autoInit: true,
...this.options,
};
if (this.options.autoInit) {
this.init();
}
}
protected init() {
const { storageKey } = this.options;
// auto-save to local-storage
if (storageName) {
const storage = createStorage<[TabId, T][]>(storageName, []);
this.data.replace(storage.get());
reaction(() => this.serializeData(), (data: T | any) => storage.set(data));
if (storageKey) {
this.storage = createStorage(storageKey, {});
this.storage.whenReady.then(() => {
this.data.replace(this.storage.get());
reaction(() => this.getStorableData(), data => this.storage.set(data));
});
}
// clear data for closed tabs
@@ -34,14 +49,22 @@ export class DockTabStore<T = any> {
});
}
protected serializeData() {
const { storageSerializer } = this.options;
protected finalizeDataForSave(data: T): T {
return data;
}
return Array.from(this.data).map(([tabId, tabData]) => {
if (storageSerializer) return [tabId, storageSerializer(tabData)];
protected getStorableData(): DockTabStorageState<T> {
const allTabsData = toJS(this.data, { recurseEverything: true });
return [tabId, tabData];
});
return Object.fromEntries(
Object.entries(allTabsData).map(([tabId, tabData]) => {
return [tabId, this.finalizeDataForSave(tabData)];
})
);
}
isReady(tabId: TabId): boolean {
return Boolean(this.getData(tabId) !== undefined);
}
getData(tabId: TabId) {
@@ -58,5 +81,6 @@ export class DockTabStore<T = any> {
reset() {
this.data.clear();
this.storage?.clear();
}
}
+67 -53
View File
@@ -21,28 +21,72 @@ export interface IDockTab {
pinned?: boolean; // not closable
}
export interface DockStorageState {
height: number;
tabs: IDockTab[];
selectedTabId?: TabId;
isOpen?: boolean;
}
@autobind()
export class DockStore {
protected initialTabs: IDockTab[] = [
{ 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;
export class DockStore implements DockStorageState {
readonly minHeight = 100;
@observable fullSize = false;
@observable height = this.defaultHeight;
@observable tabs = observable.array<IDockTab>(this.initialTabs);
@observable selectedTabId = this.defaultTabId;
private storage = createStorage<DockStorageState>("dock", {
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() {
return this.tabs.find(tab => tab.id === this.selectedTabId);
}
get defaultHeight() {
return Math.round(window.innerHeight / 2.5);
constructor() {
this.init();
}
private init() {
// adjust terminal height if window size changes
window.addEventListener("resize", throttle(this.adjustHeight, 250));
}
get maxHeight() {
@@ -50,35 +94,14 @@ export class DockStore {
const mainLayoutTabs = 33;
const mainLayoutMargin = 16;
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() {
Object.assign(this, this.storage.get());
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);
}
protected adjustHeight() {
if (this.height < this.minHeight) this.height = this.minHeight;
if (this.height > this.maxHeight) this.height = this.maxHeight;
}
onResize(callback: () => void, options?: IReactionOptions) {
@@ -165,7 +188,7 @@ export class DockStore {
if (!tab || tab.pinned) {
return;
}
this.tabs.remove(tab);
this.tabs = this.tabs.filter(tab => tab.id !== tabId);
if (this.selectedTabId === tab.id) {
if (this.tabs.length) {
@@ -178,8 +201,7 @@ export class DockStore {
if (!terminalStore.isConnected(newTab.id)) this.close();
}
this.selectTab(newTab.id);
}
else {
} else {
this.selectedTabId = null;
this.close();
}
@@ -219,17 +241,9 @@ export class DockStore {
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
reset() {
this.selectedTabId = this.defaultTabId;
this.tabs.replace(this.initialTabs);
this.setHeight(this.defaultHeight);
this.close();
this.storage?.reset();
}
}
+1 -1
View File
@@ -89,7 +89,7 @@ export class Dock extends React.Component<Props> {
onStart={dockStore.open}
onMinExtentSubceed={dockStore.close}
onMinExtentExceed={dockStore.open}
onDrag={dockStore.setHeight}
onDrag={extent => dockStore.height = extent}
/>
<div className="tabs-container flex align-center" onDoubleClick={prevDefault(toggle)}>
<DockTabs
@@ -1,24 +1,29 @@
import { autobind, noop } from "../../utils";
import { DockTabStore } from "./dock-tab.store";
import { autorun, IReactionDisposer } from "mobx";
import { dockStore, IDockTab, TabKind } from "./dock.store";
import { dockStore, IDockTab, TabId, TabKind } from "./dock.store";
import { KubeObject } from "../../api/kube-object";
import { apiManager } from "../../api/api-manager";
import { KubeObjectStore } from "../../kube-object.store";
export interface KubeEditResource {
export interface EditingResource {
resource: string; // resource path, e.g. /api/v1/namespaces/default
draft?: string; // edited draft in yaml
}
@autobind()
export class EditResourceStore extends DockTabStore<KubeEditResource> {
private watchers = new Map<string /*tabId*/, IReactionDisposer>();
export class EditResourceStore extends DockTabStore<EditingResource> {
private watchers = new Map<TabId, IReactionDisposer>();
constructor() {
super({
storageName: "edit_resource_store",
storageSerializer: ({ draft, ...data }) => data, // skip saving draft in local-storage
storageKey: "edit_resource_store",
});
}
protected async init() {
super.init();
await this.storage.whenReady;
autorun(() => {
Array.from(this.data).forEach(([tabId, { resource }]) => {
@@ -42,12 +47,34 @@ export class EditResourceStore extends DockTabStore<KubeEditResource> {
}
}
}, {
delay: 100 // make sure all stores initialized
delay: 100 // make sure all kube-object stores are initialized
}));
});
});
}
protected finalizeDataForSave({ draft, ...data }: EditingResource): EditingResource {
return data; // skip saving draft to local-storage
}
isReady(tabId: TabId) {
const tabDataReady = super.isReady(tabId);
return Boolean(tabDataReady && this.getResource(tabId)); // ready to edit resource
}
getStore(tabId: TabId): KubeObjectStore | undefined {
return apiManager.getStore(this.getResourcePath(tabId));
}
getResource(tabId: TabId): KubeObject | undefined {
return this.getStore(tabId)?.getByPath(this.getResourcePath(tabId));
}
getResourcePath(tabId: TabId): string | undefined {
return this.getData(tabId)?.resource;
}
getTabByResource(object: KubeObject): IDockTab {
const [tabId] = Array.from(this.data).find(([, { resource }]) => {
return object.selfLink === resource;
+20 -24
View File
@@ -1,8 +1,8 @@
import "./edit-resource.scss";
import React from "react";
import { autorun, observable } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { observable, when } from "mobx";
import { observer } from "mobx-react";
import jsYaml from "js-yaml";
import { IDockTab } from "./dock.store";
import { cssNames } from "../../utils";
@@ -11,8 +11,6 @@ import { InfoPanel } from "./info-panel";
import { Badge } from "../badge";
import { EditorPanel } from "./editor-panel";
import { Spinner } from "../spinner";
import { apiManager } from "../../api/api-manager";
import { KubeObject } from "../../api/kube-object";
interface Props {
className?: string;
@@ -23,30 +21,28 @@ interface Props {
export class EditResource extends React.Component<Props> {
@observable error = "";
@disposeOnUnmount
autoDumpResourceOnInit = autorun(() => {
if (!this.tabData) return;
async componentDidMount() {
await when(() => this.isReady);
if (this.tabData.draft === undefined && this.resource) {
this.saveDraft(this.resource);
if (!this.tabData.draft) {
this.saveDraft(this.resource); // make initial dump to editor
}
});
}
get tabId() {
return this.props.tab.id;
}
get isReady() {
return editResourceStore.isReady(this.tabId);
}
get tabData() {
return editResourceStore.getData(this.tabId);
}
get resource(): KubeObject {
const { resource } = this.tabData;
const store = apiManager.getStore(resource);
if (store) {
return store.getByPath(resource);
}
get resource() {
return editResourceStore.getResource(this.tabId);
}
saveDraft(draft: string | object) {
@@ -68,8 +64,8 @@ export class EditResource extends React.Component<Props> {
if (this.error) {
return;
}
const { resource, draft } = this.tabData;
const store = apiManager.getStore(resource);
const { draft } = this.tabData;
const store = editResourceStore.getStore(this.tabId);
const updatedResource = await store.update(this.resource, jsYaml.safeLoad(draft));
this.saveDraft(updatedResource); // update with new resourceVersion to avoid further errors on save
@@ -84,13 +80,13 @@ export class EditResource extends React.Component<Props> {
};
render() {
const { tabId, resource, tabData, error, onChange, save } = this;
const { draft } = tabData;
if (!resource || draft === undefined) {
if (!this.isReady) {
return <Spinner center/>;
}
const { kind, getNs, getName } = resource;
const { tabId, error, onChange, save } = this;
const { kind, getNs, getName } = this.resource;
const { draft } = this.tabData;
return (
<div className={cssNames("EditResource flex column", this.props.className)}>
@@ -22,7 +22,7 @@ export class InstallChartStore extends DockTabStore<IChartInstallData> {
constructor() {
super({
storageName: "install_charts"
storageKey: "install_charts"
});
autorun(() => {
const { selectedTab, isOpen } = dockStore;
@@ -27,7 +27,7 @@ interface WorkloadLogsTabData {
export class LogTabStore extends DockTabStore<LogTabData> {
constructor() {
super({
storageName: "pod_logs"
storageKey: "pod_logs"
});
reaction(() => podsStore.items.length, () => {
@@ -16,7 +16,7 @@ export class UpgradeChartStore extends DockTabStore<IChartUpgradeData> {
constructor() {
super({
storageName: "chart_releases"
storageKey: "chart_releases"
});
autorun(() => {
@@ -2,7 +2,7 @@ import "./item-list-layout.scss";
import groupBy from "lodash/groupBy";
import React, { ReactNode } from "react";
import { computed, observable, reaction, toJS } from "mobx";
import { computed } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { ConfirmDialog, ConfirmDialogParams } from "../confirm-dialog";
import { Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps, TableSortCallback } from "../table";
@@ -45,6 +45,7 @@ export interface ItemListLayoutProps<T extends ItemObject = ItemObject> {
isClusterScoped?: boolean;
hideFilters?: boolean;
searchFilters?: SearchFilter<T>[];
/** @deprecated */
filterItems?: ItemsFilter<T>[];
// header (title, filtering, searching, etc.)
@@ -93,29 +94,20 @@ const defaultProps: Partial<ItemListLayoutProps> = {
customizeTableRowProps: () => ({} as TableRowProps),
};
interface ItemListLayoutUserSettings {
showAppliedFilters?: boolean;
}
@observer
export class ItemListLayout extends React.Component<ItemListLayoutProps> {
static defaultProps = defaultProps as object;
@observable userSettings: ItemListLayoutUserSettings = {
showAppliedFilters: false,
};
private storage = createStorage("item_list_layout", {
showFilters: false, // setup defaults
});
constructor(props: ItemListLayoutProps) {
super(props);
get showFilters(): boolean {
return this.storage.get().showFilters;
}
// keep ui user settings in local storage
const defaultUserSettings = toJS(this.userSettings);
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)),
]);
set showFilters(showFilters: boolean) {
this.storage.merge({ showFilters });
}
async componentDidMount() {
@@ -291,9 +283,9 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
renderFilters() {
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;
}
@@ -334,13 +326,13 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
renderInfo() {
const { items, isReady, userSettings, filters } = this;
const { items, isReady, filters } = this;
const allItemsCount = this.props.store.getTotalCount();
const itemsCount = items.length;
const isFiltered = isReady && filters.length > 0;
if (isFiltered) {
const toggleFilters = () => userSettings.showAppliedFilters = !userSettings.showAppliedFilters;
const toggleFilters = () => this.showFilters = !this.showFilters;
return (
<><a onClick={toggleFilters}>Filtered</a>: {itemsCount} / {allItemsCount}</>
@@ -7,7 +7,6 @@
"aside footer";
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;
height: 100%;
> header {
@@ -22,18 +21,15 @@
background: $sidebarBackground;
white-space: nowrap;
transition: width 150ms cubic-bezier(0.4, 0, 0.2, 1);
width: var(--sidebar-width);
&.pinned {
width: var(--sidebar-width);
}
&:not(.pinned) {
&.compact {
position: absolute;
width: var(--main-layout-header);
height: 100%;
overflow: hidden;
&.accessible:hover {
&:hover {
width: var(--sidebar-width);
transition-delay: 750ms;
box-shadow: 3px 3px 16px rgba(0, 0, 0, 0.35);
+22 -46
View File
@@ -1,15 +1,15 @@
import "./main-layout.scss";
import React from "react";
import { observable, reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { observer } from "mobx-react";
import { getHostedCluster } from "../../../common/cluster-store";
import { autobind, createStorage, cssNames } from "../../utils";
import { cssNames } from "../../utils";
import { Dock } from "../dock";
import { ErrorBoundary } from "../error-boundary";
import { ResizeDirection, ResizeGrowthDirection, ResizeSide, ResizingAnchor } from "../resizing-anchor";
import { MainLayoutHeader } from "./main-layout-header";
import { Sidebar } from "./sidebar";
import { sidebarStorage } from "./sidebar-storage";
export interface MainLayoutProps {
className?: any;
@@ -20,65 +20,41 @@ export interface MainLayoutProps {
@observer
export class MainLayout extends React.Component<MainLayoutProps> {
public storage = createStorage("main_layout", {
pinnedSidebar: true,
sidebarWidth: 200,
});
@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);
onSidebarCompactModeChange = () => {
sidebarStorage.merge(draft => {
draft.compact = !draft.compact;
});
};
getSidebarSize = () => {
return {
"--sidebar-width": `${this.sidebarWidth}px`,
};
onSidebarResize = (width: number) => {
sidebarStorage.merge({ width });
};
@autobind()
adjustWidth(newWidth: number): void {
this.sidebarWidth = newWidth;
}
render() {
const { className, headerClass, footer, footerClass, children } = this.props;
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) {
return null; // fix: skip render when removing active (visible) cluster
}
return (
<div className={cssNames("MainLayout", className)} style={this.getSidebarSize() as any}>
<MainLayoutHeader className={headerClass} cluster={cluster} />
<div className={cssNames("MainLayout", className)} style={style}>
<MainLayoutHeader className={headerClass} cluster={cluster}/>
<aside className={cssNames("flex column", { pinned: this.isPinned, accessible: this.isAccessible })}>
<Sidebar className="box grow" isPinned={this.isPinned} toggle={this.toggleSidebar} />
<aside className={cssNames("flex column", { compact })}>
<Sidebar className="box grow" compact={compact} toggle={onSidebarCompactModeChange}/>
<ResizingAnchor
direction={ResizeDirection.HORIZONTAL}
placement={ResizeSide.TRAILING}
growthDirection={ResizeGrowthDirection.LEFT_TO_RIGHT}
getCurrentExtent={() => this.sidebarWidth}
onDrag={this.adjustWidth}
onDoubleClick={this.toggleSidebar}
disabled={!this.isPinned}
getCurrentExtent={() => sidebarWidth}
onDrag={onSidebarResize}
onDoubleClick={onSidebarCompactModeChange}
disabled={compact}
minExtent={120}
maxExtent={400}
/>
@@ -88,7 +64,7 @@ export class MainLayout extends React.Component<MainLayoutProps> {
<ErrorBoundary>{children}</ErrorBoundary>
</main>
<footer className={footerClass}>{footer ?? <Dock />}</footer>
<footer className={footerClass}>{footer ?? <Dock/>}</footer>
</div>
);
}
@@ -1,7 +0,0 @@
import React from "react";
export const SidebarContext = React.createContext<SidebarContextValue>({ pinned: false });
export type SidebarContextValue = {
pinned: boolean;
};
@@ -0,0 +1,63 @@
.SidebarItem {
$itemSpacing: floor($unit / 2.6) floor($unit / 1.6);
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 100%;
user-select: none;
> .nav-item {
text-decoration: none;
padding: $itemSpacing;
width: 100%;
height: 100%;
color: inherit;
cursor: pointer;
> .link-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
&.active, &:hover {
background: $lensBlue;
color: $sidebarActiveColor;
}
.expand-icon {
--size: 20px;
}
}
.sub-menu {
$borderSize: 4px;
border-left: $borderSize solid transparent;
&.active {
border-left-color: $lensBlue;
}
> .SidebarItem {
color: $textColorPrimary;
padding-left: 30px + $borderSize;
line-height: 22px;
.SidebarItem {
padding-left: $padding * 2; // 3rd+ menu level
}
.nav-item {
&.expandable {
font-weight: 500;
}
&.active, &:hover {
color: $sidebarSubmenuActiveColor;
background: none;
}
}
}
}
}
@@ -0,0 +1,98 @@
import "./sidebar-item.scss";
import React from "react";
import { computed } from "mobx";
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";
import { isActiveRoute } from "../../navigation";
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[];
}
@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 compact(): boolean {
return Boolean(sidebarStorage.get().compact);
}
get expanded(): boolean {
return Boolean(sidebarStorage.get().expanded[this.id]);
}
@computed get isExpandable(): boolean {
const { subMenus, children } = this.props;
const hasContent = subMenus?.length > 0 || children;
return Boolean(hasContent && !this.compact) /*not available in compact-mode*/;
}
toggleExpand = () => {
sidebarStorage.merge(draft => {
draft.expanded[this.id] = !draft.expanded[this.id];
});
};
render() {
const { isHidden, isActive, subMenus = [], icon, text, children, url, className } = this.props;
if (isHidden) return null;
const { id, compact, expanded, isExpandable, toggleExpand } = this;
const classNames = cssNames(SidebarItem.displayName, className, {
compact,
});
return (
<div className={classNames} data-test-id={id}>
<NavLink
to={url}
isActive={() => isActive}
className={cssNames("nav-item flex gaps align-center", { expandable: isExpandable })}
onClick={isExpandable ? prevDefault(toggleExpand) : undefined}>
{icon}
<span className="link-text box grow">{text}</span>
{isExpandable && <Icon
className="expand-icon box right"
material={expanded ? "keyboard_arrow_up" : "keyboard_arrow_down"}
/>}
</NavLink>
{isExpandable && expanded && (
<ul className={cssNames("sub-menu", { active: isActive })}>
{subMenus.map(({ title, routePath, url = routePath }) => {
const subItemId = `${id}${routePath}`;
return (
<SidebarItem
key={subItemId}
id={subItemId}
url={url}
text={title}
isActive={isActiveRoute({ path: url, exact: true })}
/>
);
})}
{children}
</ul>
)}
</div>
);
}
}
@@ -1,76 +0,0 @@
.SidebarNavItem {
$itemSpacing: floor($unit / 2.6) floor($unit / 1.6);
width: 100%;
user-select: none;
flex-shrink: 0;
.nav-item {
cursor: pointer;
width: inherit;
display: flex;
align-items: center;
text-decoration: none;
border: none;
padding: $itemSpacing;
&.active, &:hover {
background: $lensBlue;
color: $sidebarActiveColor;
}
}
.expand-icon {
--size: 20px;
}
.sub-menu {
border-left: 4px solid transparent;
&.active {
border-left-color: $lensBlue;
}
a, .SidebarNavItem {
display: block;
border: none;
text-decoration: none;
color: $textColorPrimary;
font-weight: normal;
padding-left: 40px; // parent icon width
overflow: hidden;
text-overflow: ellipsis;
line-height: 0px; // hidden by default
height: 0px;
opacity: 0;
transition: 125ms line-height ease-out, 200ms 100ms opacity;
&.visible {
line-height: 28px;
height: auto;
opacity: 1;
}
&.active, &:hover {
color: $sidebarSubmenuActiveColor;
}
}
.sub-menu-parent {
padding-left: 27px;
font-weight: 500;
.nav-item {
&:hover {
background: transparent;
}
}
.sub-menu {
a {
padding-left: $padding * 3;
}
}
}
}
}
@@ -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>
);
}
}
@@ -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: {},
});
+3 -22
View File
@@ -2,9 +2,9 @@
$iconSize: 24px;
$itemSpacing: floor($unit / 2.6) floor($unit / 1.6);
&.pinned {
&.compact {
.sidebar-nav {
overflow: auto;
@include hidden-scrollbar; // fix: scrollbar overlaps icons
}
}
@@ -45,6 +45,7 @@
.sidebar-nav {
padding: $padding / 1.5 0;
overflow: auto;
.Icon {
--size: #{$iconSize};
@@ -54,26 +55,6 @@
border-radius: 50%;
}
.link-text {
flex: 1;
margin-left: $margin;
overflow: hidden;
text-overflow: ellipsis;
}
> a {
display: flex;
align-items: center;
text-decoration: none;
border: none;
padding: $itemSpacing;
&.active, &:hover {
background: $lensBlue;
color: $sidebarActiveColor;
}
}
hr {
background-color: transparent;
}
+122 -123
View File
@@ -28,17 +28,18 @@ import { isActiveRoute } from "../../navigation";
import { isAllowedResource } from "../../../common/rbac";
import { Spinner } from "../spinner";
import { ClusterPageMenuRegistration, clusterPageMenuRegistry, clusterPageRegistry, getExtensionPageUrl } from "../../../extensions/registries";
import { SidebarNavItem } from "./sidebar-nav-item";
import { SidebarContext } from "./sidebar-context";
import { SidebarItem } from "./sidebar-item";
interface Props {
className?: string;
isPinned: boolean;
toggle(): void;
compact?: boolean; // compact-mode view: show only icons and expand on :hover
toggle(): void; // compact-mode updater
}
@observer
export class Sidebar extends React.Component<Props> {
static displayName = "Sidebar";
async componentDidMount() {
crdStore.reloadAll();
}
@@ -59,13 +60,13 @@ export class Sidebar extends React.Component<Props> {
});
return (
<SidebarNavItem
<SidebarItem
key={group}
id={`crd-${group}`}
className="sub-menu-parent"
id={`crd-group:${group}`}
url={crdURL({ query: { groups: group } })}
subMenus={submenus}
text={group}
isActive={false}
/>
);
});
@@ -117,7 +118,7 @@ export class Sidebar extends React.Component<Props> {
}
return (
<SidebarNavItem
<SidebarItem
key={id}
id={id}
url={pageUrl}
@@ -131,125 +132,123 @@ export class Sidebar extends React.Component<Props> {
}
render() {
const { toggle, isPinned, className } = this.props;
const { toggle, compact, className } = this.props;
const query = namespaceUrlParam.toObjectParam();
return (
<SidebarContext.Provider value={{ pinned: isPinned }}>
<div className={cssNames("Sidebar flex column", className, { pinned: isPinned })}>
<div className="header flex align-center">
<NavLink exact to="/" className="box grow">
<Icon svg="logo-lens" className="logo-icon"/>
<div className="logo-text">Lens</div>
</NavLink>
<Icon
className="pin-icon"
tooltip="Compact view"
material={isPinned ? "keyboard_arrow_left" : "keyboard_arrow_right"}
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 className={cssNames(Sidebar.displayName, "flex column", { compact }, className)}>
<div className="header flex align-center">
<NavLink exact to="/" className="box grow">
<Icon svg="logo-lens" className="logo-icon"/>
<div className="logo-text">Lens</div>
</NavLink>
<Icon
focusable={false}
className="pin-icon"
tooltip="Compact view"
material={compact ? "keyboard_arrow_right" : "keyboard_arrow_left"}
onClick={toggle}
/>
</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>
);
}
}