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

persist local-storage in json-file due random port on app start

Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
Roman 2021-03-01 20:31:47 +02:00
parent 4f74b9aabe
commit 6cc83bd353
23 changed files with 724 additions and 508 deletions

View File

@ -210,6 +210,7 @@
"fs-extra": "^9.0.1", "fs-extra": "^9.0.1",
"handlebars": "^4.7.6", "handlebars": "^4.7.6",
"http-proxy": "^1.18.1", "http-proxy": "^1.18.1",
"immer": "^8.0.1",
"js-yaml": "^3.14.0", "js-yaml": "^3.14.0",
"jsdom": "^16.4.0", "jsdom": "^16.4.0",
"jsonpath": "^1.0.2", "jsonpath": "^1.0.2",

View File

@ -6,7 +6,7 @@ import * as MobxReact from "mobx-react";
import * as ReactRouter from "react-router"; import * as ReactRouter from "react-router";
import * as ReactRouterDom from "react-router-dom"; import * as ReactRouterDom from "react-router-dom";
import { render, unmountComponentAtNode } from "react-dom"; import { render, unmountComponentAtNode } from "react-dom";
import { clusterStore } from "../common/cluster-store"; import { clusterStore, getHostedClusterId } from "../common/cluster-store";
import { userStore } from "../common/user-store"; import { userStore } from "../common/user-store";
import { isMac } from "../common/vars"; import { isMac } from "../common/vars";
import { workspaceStore } from "../common/workspace-store"; import { workspaceStore } from "../common/workspace-store";
@ -18,6 +18,7 @@ import { filesystemProvisionerStore } from "../main/extension-filesystem";
import { App } from "./components/app"; import { App } from "./components/app";
import { LensApp } from "./lens-app"; import { LensApp } from "./lens-app";
import { themeStore } from "./theme.store"; import { themeStore } from "./theme.store";
import { lensLocalStorage } from "./local-storage";
type AppComponent = React.ComponentType & { type AppComponent = React.ComponentType & {
init?(): Promise<void>; init?(): Promise<void>;
@ -33,6 +34,7 @@ export {
}; };
export async function bootstrap(App: AppComponent) { export async function bootstrap(App: AppComponent) {
const clusterId = getHostedClusterId();
const rootElem = document.getElementById("app"); const rootElem = document.getElementById("app");
rootElem.classList.toggle("is-mac", isMac); rootElem.classList.toggle("is-mac", isMac);
@ -48,6 +50,7 @@ export async function bootstrap(App: AppComponent) {
extensionsStore.load(), extensionsStore.load(),
filesystemProvisionerStore.load(), filesystemProvisionerStore.load(),
themeStore.init(), themeStore.init(),
lensLocalStorage.init(clusterId),
]); ]);
// Register additional store listeners // Register additional store listeners

View File

@ -1,7 +1,8 @@
import { action, observable, reaction, when } from "mobx"; import { action, observable, reaction, when } from "mobx";
import { KubeObjectStore } from "../../kube-object.store"; import { KubeObjectStore } from "../../kube-object.store";
import { Cluster, clusterApi, IClusterMetrics } from "../../api/endpoints"; import { Cluster, clusterApi, IClusterMetrics } from "../../api/endpoints";
import { autobind, createStorage } from "../../utils"; import { autobind } from "../../utils";
import { createStorage } from "../../local-storage";
import { IMetricsReqParams, normalizeMetrics } from "../../api/endpoints/metrics.api"; import { IMetricsReqParams, normalizeMetrics } from "../../api/endpoints/metrics.api";
import { nodesStore } from "../+nodes/nodes.store"; import { nodesStore } from "../+nodes/nodes.store";
import { apiManager } from "../../api/api-manager"; import { apiManager } from "../../api/api-manager";
@ -16,36 +17,50 @@ export enum MetricNodeRole {
WORKER = "worker" WORKER = "worker"
} }
export interface ClusterOverviewStorageState {
metricType: MetricType;
metricNodeRole: MetricNodeRole,
}
const localStorage = createStorage<ClusterOverviewStorageState>("cluster_overview", {
metricType: MetricType.CPU, // setup defaults
metricNodeRole: MetricNodeRole.WORKER,
});
@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; get metricType(): MetricType {
return localStorage.get().metricType;
}
set metricType(value: MetricType) {
localStorage.merge({ metricType: value });
}
get metricNodeRole(): MetricNodeRole {
return localStorage.get().metricNodeRole;
}
set metricNodeRole(value: MetricNodeRole) {
localStorage.merge({ metricNodeRole: value });
}
constructor() { constructor() {
super(); super();
this.resetMetrics(); this.init();
}
// sync user setting with local storage private async 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 +94,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();
localStorage.reset();
} }
} }

View File

@ -1,18 +1,19 @@
import { action, comparer, computed, IReactionDisposer, IReactionOptions, observable, reaction } from "mobx"; import { action, comparer, computed, IReactionDisposer, IReactionOptions, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils"; import { autobind } from "../../utils";
import { createStorage } from "../../local-storage";
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store"; import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api"; 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("selected_namespaces", ["default"]);
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();
} }
}); });
@ -41,6 +42,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
} }
private async init() { private async init() {
await selectedNamespaces.whenReady;
await this.contextReady; await this.contextReady;
this.setContext(this.initialNamespaces); this.setContext(this.initialNamespaces);
@ -57,8 +59,8 @@ 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);
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url namespaceUrlParam.set(namespaces, { replaceHistory: true });
}, { }, {
fireImmediately: true, fireImmediately: true,
}); });
@ -71,24 +73,11 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
}); });
} }
@computed
private get initialNamespaces(): string[] { private get initialNamespaces(): string[] {
const namespaces = new Set(this.allowedNamespaces); const namespaces = this.allowedNamespaces;
const prevSelectedNamespaces = storage.get();
// return previously saved namespaces from local-storage (if any) // return all namespaces (empty list) if "default" namespace doesn't exist
if (prevSelectedNamespaces) { return selectedNamespaces.get().filter(namespace => namespaces.includes(namespace));
return prevSelectedNamespaces.filter(namespace => namespaces.has(namespace));
}
// otherwise select "default" or first allowed namespace
if (namespaces.has("default")) {
return ["default"];
} else if (namespaces.size) {
return [Array.from(namespaces)[0]];
}
return [];
} }
@computed get allowedNamespaces(): string[] { @computed get allowedNamespaces(): string[] {

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,31 @@
import { autorun, observable, reaction } from "mobx"; import { autorun, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils"; import { createStorage, StorageHelper } from "../../local-storage";
import { autobind } 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: T | any) => this.storage.set(data));
} }
// clear data for closed tabs // clear data for closed tabs
@ -34,14 +40,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

@ -1,6 +1,7 @@
import MD5 from "crypto-js/md5"; import MD5 from "crypto-js/md5";
import { action, computed, IReactionOptions, observable, reaction } from "mobx"; import { action, computed, IReactionOptions, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils"; import { createStorage } from "../../local-storage";
import { autobind } from "../../utils";
import throttle from "lodash/throttle"; import throttle from "lodash/throttle";
export type TabId = string; export type TabId = string;
@ -21,28 +22,68 @@ export interface IDockTab {
pinned?: boolean; // not closable pinned?: boolean; // not closable
} }
@autobind() export interface DockStorageState {
export class DockStore { height: number;
protected initialTabs: IDockTab[] = [ tabs: IDockTab[];
selectedTabId?: TabId;
isOpen?: boolean;
}
const localStorage = createStorage<DockStorageState>("dock", {
height: 300,
tabs: [
{ id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" }, { id: "terminal", kind: TabKind.TERMINAL, title: "Terminal" },
]; ],
});
protected storage = createStorage("dock", {}); // keep settings in localStorage @autobind()
public readonly defaultTabId = this.initialTabs[0].id; export class DockStore implements DockStorageState {
public readonly minHeight = 100; readonly minHeight = 100;
@observable isOpen = false;
@observable fullSize = false; @observable fullSize = false;
@observable height = this.defaultHeight;
@observable tabs = observable.array<IDockTab>(this.initialTabs); get isOpen(): boolean {
@observable selectedTabId = this.defaultTabId; return localStorage.get().isOpen;
}
set isOpen(value: boolean) {
localStorage.merge({ isOpen: value });
}
get height(): number {
return localStorage.get().height;
}
set height(value: number) {
localStorage.merge({ height: value });
}
get tabs(): IDockTab[] {
return localStorage.get().tabs;
}
set tabs(value: IDockTab[]) {
localStorage.merge({ tabs: value });
}
get selectedTabId(): TabId {
return localStorage.get().selectedTabId || this.tabs[0]?.id;
}
set selectedTabId(value: TabId) {
localStorage.merge({ selectedTabId: value });
}
@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 async init() {
// adjust terminal height if window size changes
window.addEventListener("resize", throttle(this.adjustHeight, 250));
} }
get maxHeight() { get maxHeight() {
@ -50,35 +91,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.setHeight(this.minHeight);
if (this.height > this.maxHeight) this.setHeight(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 +185,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 +198,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();
} }
@ -226,10 +245,7 @@ export class DockStore {
@action @action
reset() { reset() {
this.selectedTabId = this.defaultTabId; localStorage.reset();
this.tabs.replace(this.initialTabs);
this.setHeight(this.defaultHeight);
this.close();
} }
} }

View File

@ -2,11 +2,12 @@ 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 { createStorage } from "../../local-storage";
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";
import { autobind, createStorage, cssNames, IClassName, isReactNode, noop, prevDefault, stopPropagation } from "../../utils"; import { autobind, cssNames, IClassName, isReactNode, noop, prevDefault, stopPropagation } from "../../utils";
import { AddRemoveButtons, AddRemoveButtonsProps } from "../add-remove-buttons"; import { AddRemoveButtons, AddRemoveButtonsProps } from "../add-remove-buttons";
import { NoItems } from "../no-items"; import { NoItems } from "../no-items";
import { Spinner } from "../spinner"; import { Spinner } from "../spinner";
@ -93,29 +94,20 @@ const defaultProps: Partial<ItemListLayoutProps> = {
customizeTableRowProps: () => ({} as TableRowProps), customizeTableRowProps: () => ({} as TableRowProps),
}; };
interface ItemListLayoutUserSettings { const localStorage = createStorage("item_list_layout", {
showAppliedFilters?: boolean; showFilters: false, // setup defaults
} });
@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;
get showFilters(): boolean {
return localStorage.get().showFilters;
}
@observable userSettings: ItemListLayoutUserSettings = { set showFilters(showFilters: boolean) {
showAppliedFilters: false, localStorage.merge({ showFilters });
};
constructor(props: ItemListLayoutProps) {
super(props);
// 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)),
]);
} }
async componentDidMount() { async componentDidMount() {
@ -296,9 +288,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 +330,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 { sidebarLocalStorage } 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, sidebarLocalStorage.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 { sidebarLocalStorage.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 } = sidebarLocalStorage.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,92 @@
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 { sidebarLocalStorage } 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 sidebarLocalStorage.get().expanded[this.id];
}
get compact(): boolean {
return sidebarLocalStorage.get().compact;
}
toggleExpand = (event: React.MouseEvent) => {
sidebarLocalStorage.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 } = this.props;
if (isHidden) return null;
const { id, expanded, compact } = this;
const isExpandable = (subMenus.length > 0 || children) && !compact;
const className = cssNames(SidebarItem.displayName, this.props.className, {
compact,
});
return (
<div className={className} 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 "../../local-storage";
export interface SidebarLocalStorageModel {
width: number;
compact: boolean;
expanded: {
[itemId: string]: boolean;
}
}
export const sidebarLocalStorage = createStorage<SidebarLocalStorageModel>("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

@ -1,7 +1,7 @@
import { useState } from "react"; import { useState } from "react";
import { createStorage, IStorageHelperOptions } from "../utils"; import { createStorage, StorageHelperOptions } from "../local-storage";
export function useStorage<T>(key: string, initialValue?: T, options?: IStorageHelperOptions) { export function useStorage<T>(key: string, initialValue?: T, options?: StorageHelperOptions) {
const storage = createStorage(key, initialValue, options); const storage = createStorage(key, initialValue, options);
const [storageValue, setStorageValue] = useState(storage.get()); const [storageValue, setStorageValue] = useState(storage.get());
const setValue = (value: T) => { const setValue = (value: T) => {

View File

@ -0,0 +1,86 @@
import path from "path";
import fse from "fs-extra";
import { isEmpty } from "lodash";
import { app, remote } from "electron";
import { action, observable, reaction, when, } from "mobx";
import { StorageHelper, StorageHelperOptions } from "./utils/storageHelper";
export * from "./utils/storageHelper";
export class LensLocalStorage {
private folderPath = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
private filePath: string;
@observable state = observable.map<string, any>();
@observable isLoaded = false;
whenReady = when(() => this.isLoaded);
getPath(fileName: string): string {
return path.resolve(this.folderPath, `${fileName}.json`);
}
async init(clusterId?: string) {
this.filePath = this.getPath(clusterId ?? "app");
try {
await this.load();
this.bindAutoSave();
} catch (error) {
console.error(`[init]: ${error}`, this);
}
}
private bindAutoSave() {
return reaction(() => this.state.toJSON(), state => this.save(state), {
delay: 500, // lazy backup
});
}
@action
async load() {
try {
await fse.ensureDir(this.folderPath, { mode: 0o755 });
const state = await fse.readJson(this.filePath);
this.state.replace(state);
} catch (error) {
}
this.isLoaded = true;
}
private async save(state: object) {
if (isEmpty(state)) {
return; // skip empty state on clear
}
try {
await fse.writeJson(this.filePath, state, { spaces: 2 });
} catch (error) {
console.error(`[save]: ${error}`, this);
}
}
@action
clear() {
this.state.clear();
fse.unlink(this.filePath).catch(() => null);
}
}
export const lensLocalStorage = new LensLocalStorage();
export function createStorage<T>(key: string, defaultValue?: T, options: StorageHelperOptions<T> = {}) {
return new StorageHelper(key, defaultValue, {
...options,
storage: {
async getItem(key: string) {
await lensLocalStorage.whenReady;
return lensLocalStorage.state.get(key);
},
async setItem(key: string, value: any) {
lensLocalStorage.state.set(key, value);
},
},
});
}

View File

@ -1,73 +0,0 @@
// Helper to work with browser's local/session storage api
export interface IStorageHelperOptions {
addKeyPrefix?: boolean;
useSession?: boolean; // use `sessionStorage` instead of `localStorage`
}
export function createStorage<T>(key: string, defaultValue?: T, options?: IStorageHelperOptions) {
return new StorageHelper(key, defaultValue, options);
}
export class StorageHelper<T> {
static keyPrefix = "lens_";
static defaultOptions: IStorageHelperOptions = {
addKeyPrefix: true,
useSession: false,
};
constructor(protected key: string, protected defaultValue?: T, protected options?: IStorageHelperOptions) {
this.options = Object.assign({}, StorageHelper.defaultOptions, options);
if (this.options.addKeyPrefix) {
this.key = StorageHelper.keyPrefix + key;
}
}
protected get storage() {
if (this.options.useSession) return window.sessionStorage;
return window.localStorage;
}
get(): T {
const strValue = this.storage.getItem(this.key);
if (strValue != null) {
try {
return JSON.parse(strValue);
} catch (e) {
console.error(`Parsing json failed for pair: ${this.key}=${strValue}`);
}
}
return this.defaultValue;
}
set(value: T) {
this.storage.setItem(this.key, JSON.stringify(value));
return this;
}
merge(value: Partial<T>) {
const currentValue = this.get();
return this.set(Object.assign(currentValue, value));
}
clear() {
this.storage.removeItem(this.key);
return this;
}
getDefaultValue() {
return this.defaultValue;
}
restoreDefaultValue() {
return this.set(this.defaultValue);
}
}

View File

@ -7,7 +7,7 @@ export * from "./cssNames";
export * from "../../common/event-emitter"; export * from "../../common/event-emitter";
export * from "./saveFile"; export * from "./saveFile";
export * from "./prevDefault"; export * from "./prevDefault";
export * from "./createStorage"; export * from "./storageHelper";
export * from "./interval"; export * from "./interval";
export * from "./copyToClipboard"; export * from "./copyToClipboard";
export * from "./formatDuration"; export * from "./formatDuration";

View File

@ -0,0 +1,170 @@
// Helper for work with persistent local storage (default: window.localStorage)
// TODO: write unit/integration tests
import type { CreateObservableOptions } from "mobx/lib/api/observable";
import { action, comparer, observable, toJS, when } from "mobx";
import produce, { Draft, setAutoFreeze } from "immer";
import { isEmpty, isEqual, isFunction } from "lodash";
setAutoFreeze(false); // allow to merge observables
export interface StorageHelperOptions<T = any> extends StorageConfiguration<T> {
autoInit?: boolean; // default: true
}
export interface StorageConfiguration<T = any> {
storage?: StorageAdapter<T>;
observable?: CreateObservableOptions;
}
export interface StorageAdapter<T = any, C = StorageHelper<T>> {
getItem(this: C, key: string): T | Promise<T>; // import
setItem(this: C, key: string, value: T): void; // export
onChange?(this: C, value: T, oldValue?: T): void;
}
export const localStorageAdapter: StorageAdapter = {
getItem(key: string) {
return JSON.parse(localStorage.getItem(key));
},
setItem(key: string, value: any) {
if (value != null) {
localStorage.setItem(key, JSON.stringify(value));
} else {
localStorage.removeItem(key);
}
}
};
export class StorageHelper<T = any> {
static defaultOptions: StorageHelperOptions = {
autoInit: true,
storage: localStorageAdapter,
observable: {
deep: true,
equals: comparer.shallow,
}
};
private data = observable.box<T>();
@observable.ref storage: StorageAdapter<T, ThisType<this>>;
@observable initialized = false;
whenReady = when(() => this.initialized);
constructor(readonly key: string, readonly defaultValue?: T, readonly options: StorageHelperOptions = {}) {
this.options = { ...StorageHelper.defaultOptions, ...options };
this.configure();
this.reset();
if (this.options.autoInit) {
this.init();
}
}
@action
async init() {
if (this.initialized) return;
try {
const value = await this.load();
const notEmpty = this.hasValue(value);
const notDefault = !this.isDefaultValue(value);
if (notEmpty && notDefault) {
this.merge(value);
}
this.initialized = true;
} catch (error) {
console.error(`[init]: ${error}`, this);
}
}
hasValue(value: T) {
return !isEmpty(value);
}
isDefaultValue(value: T) {
return isEqual(value, this.defaultValue);
}
@action
configure({ storage, observable }: StorageConfiguration<T> = this.options): this {
if (storage) this.configureStorage(storage);
if (observable) this.configureObservable(observable);
return this;
}
@action
configureStorage(storage: StorageAdapter<T>) {
this.storage = Object.getOwnPropertyNames(storage).reduce((storage, name: keyof StorageAdapter) => {
storage[name] = storage[name]?.bind(this); // bind storage-adapter methods to "this"-context
return storage;
}, { ...storage });
}
@action
configureObservable(options: CreateObservableOptions = {}) {
this.data = observable.box<T>(this.data.get(), {
...StorageHelper.defaultOptions.observable, // inherit default observability options
...options,
});
this.data.observe(change => {
const { newValue, oldValue } = toJS(change, { recurseEverything: true });
this.onChange(newValue, oldValue);
});
}
protected onChange(value: T, oldValue?: T) {
if (!this.initialized) return;
this.storage.onChange?.(value, oldValue);
this.storage.setItem(this.key, value);
}
async load(): Promise<T> {
return this.storage.getItem(this.key);
}
get(): T {
return this.data.get();
}
set(value: T) {
this.data.set(value);
}
reset() {
this.set(this.defaultValue);
}
clear() {
this.data.set(null);
}
merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) {
const updater = isFunction(value) ? value : (state: Draft<T>) => Object.assign(state, value);
const currentValue = this.toJS();
const nextValue = produce(currentValue, updater) as T;
this.set(nextValue);
}
// TODO: experiment / proxy to target object
proxyTo(object: object) {
return new Proxy(object, {
get: (target: object, prop: PropertyKey, receiver: any) => {
return Reflect.get(target, prop, receiver);
},
set: (target: object, prop: PropertyKey, value: any, receiver: any) => {
return Reflect.set(target, prop, value, receiver);
}
});
}
toJS() {
return toJS(this.get(), { recurseEverything: true });
}
}

View File

@ -6830,6 +6830,11 @@ immediate@~3.0.5:
resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b" resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b"
integrity sha1-nbHb0Pr43m++D13V5Wu2BigN5ps= integrity sha1-nbHb0Pr43m++D13V5Wu2BigN5ps=
immer@^8.0.1:
version "8.0.1"
resolved "https://registry.yarnpkg.com/immer/-/immer-8.0.1.tgz#9c73db683e2b3975c424fb0572af5889877ae656"
integrity sha512-aqXhGP7//Gui2+UrEtvxZxSquQVXTpZ7KDxfCcKAF3Vysvw0CViVaW9RZ1j1xlIYqaaaipBoqdqeibkc18PNvA==
import-fresh@^3.0.0, import-fresh@^3.1.0: import-fresh@^3.0.0, import-fresh@^3.1.0:
version "3.2.1" version "3.2.1"
resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66" resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66"