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

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

This commit is contained in:
Roman 2021-03-18 14:36:34 +02:00 committed by GitHub
parent da5a4bbdf4
commit aedcc6d70e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 1025 additions and 618 deletions

View File

@ -54,6 +54,15 @@ describe("Lens cluster pages", () => {
}
};
function getSidebarSelectors(itemId: string) {
const root = `.SidebarItem[data-test-id="${itemId}"]`;
return {
expandSubMenu: `${root} .nav-item`,
subMenuLink: (href: string) => `.Sidebar .sub-menu a[href^="/${href}"]`,
};
}
describe("cluster pages", () => {
beforeAll(appStartAddCluster, 40000);
@ -311,27 +320,35 @@ describe("Lens cluster pages", () => {
}];
tests.forEach(({ drawer = "", drawerId = "", pages }) => {
const selectors = getSidebarSelectors(drawerId);
if (drawer !== "") {
it(`shows ${drawer} drawer`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(`.sidebar-nav [data-test-id="${drawerId}"] span.link-text`);
await app.client.waitUntilTextExists(`a[href^="/${pages[0].href}"]`, pages[0].name);
await app.client.click(selectors.expandSubMenu);
await app.client.waitUntilTextExists(selectors.subMenuLink(pages[0].href), pages[0].name);
});
}
pages.forEach(({ name, href, expectedSelector, expectedText }) => {
it(`shows ${drawer}->${name} page`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(`a[href^="/${href}"]`);
await app.client.click(selectors.subMenuLink(href));
await app.client.waitUntilTextExists(expectedSelector, expectedText);
});
});
if (drawer !== "") {
// hide the drawer
it(`hides ${drawer} drawer`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(`.sidebar-nav [data-test-id="${drawerId}"] span.link-text`);
await expect(app.client.waitUntilTextExists(`a[href^="/${pages[0].href}"]`, pages[0].name, 100)).rejects.toThrow();
await app.client.click(selectors.expandSubMenu);
await expect(app.client.waitUntilTextExists(selectors.subMenuLink(pages[0].href), pages[0].name, 100)).rejects.toThrow();
});
} else {
const { href, name, expectedText, expectedSelector } = pages[0];
it(`shows page ${name}`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(`a[href^="/${href}"]`);
await app.client.waitUntilTextExists(expectedSelector, expectedText);
});
}
});
@ -349,7 +366,7 @@ describe("Lens cluster pages", () => {
it(`shows a log for a pod`, async () => {
expect(clusterAdded).toBe(true);
// Go to Pods page
await app.client.click(".sidebar-nav [data-test-id='workloads'] span.link-text");
await app.client.click(getSidebarSelectors("workloads").expandSubMenu);
await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods");
await app.client.click('a[href^="/pods"]');
await app.client.click(".NamespaceSelect");
@ -416,7 +433,7 @@ describe("Lens cluster pages", () => {
it(`creates a pod in ${TEST_NAMESPACE} namespace`, async () => {
expect(clusterAdded).toBe(true);
await app.client.click(".sidebar-nav [data-test-id='workloads'] span.link-text");
await app.client.click(getSidebarSelectors("workloads").expandSubMenu);
await app.client.waitUntilTextExists('a[href^="/pods"]', "Pods");
await app.client.click('a[href^="/pods"]');

View File

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

View File

@ -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();
}
}

View File

@ -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);

View File

@ -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) {

View File

@ -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];

View File

@ -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"
});
}
}

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();
}
}

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();
}
}

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

View File

@ -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;

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)}>

View File

@ -22,7 +22,7 @@ export class InstallChartStore extends DockTabStore<IChartInstallData> {
constructor() {
super({
storageName: "install_charts"
storageKey: "install_charts"
});
autorun(() => {
const { selectedTab, isOpen } = dockStore;

View File

@ -27,7 +27,7 @@ interface WorkloadLogsTabData {
export class LogTabStore extends DockTabStore<LogTabData> {
constructor() {
super({
storageName: "pod_logs"
storageKey: "pod_logs"
});
reaction(() => podsStore.items.length, () => {

View File

@ -16,7 +16,7 @@ export class UpgradeChartStore extends DockTabStore<IChartUpgradeData> {
constructor() {
super({
storageName: "chart_releases"
storageKey: "chart_releases"
});
autorun(() => {

View File

@ -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}</>

View File

@ -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);
&.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);

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,
onSidebarCompactModeChange = () => {
sidebarStorage.merge(draft => {
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 = () => {
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}>
<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}
/>

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

@ -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;
}
}
}
}
}

View File

@ -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>
);
}
}

View File

@ -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;
}
}
}
}
}

View File

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

View File

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

View File

@ -2,9 +2,9 @@
$iconSize: 24px;
$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;
}

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,27 +132,26 @@ 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={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={isPinned ? "keyboard_arrow_left" : "keyboard_arrow_right"}
material={compact ? "keyboard_arrow_right" : "keyboard_arrow_left"}
onClick={toggle}
focusable={false}
/>
</div>
<div className="sidebar-nav flex column box grow-fixed">
<SidebarNavItem
<div className={cssNames("sidebar-nav flex column box grow-fixed", { compact })}>
<SidebarItem
id="cluster"
isActive={isActiveRoute(clusterRoute)}
isHidden={!isAllowedResource("nodes")}
@ -159,7 +159,7 @@ export class Sidebar extends React.Component<Props> {
text="Cluster"
icon={<Icon svg="kube"/>}
/>
<SidebarNavItem
<SidebarItem
id="nodes"
isActive={isActiveRoute(nodesRoute)}
isHidden={!isAllowedResource("nodes")}
@ -167,7 +167,7 @@ export class Sidebar extends React.Component<Props> {
text="Nodes"
icon={<Icon svg="nodes"/>}
/>
<SidebarNavItem
<SidebarItem
id="workloads"
isActive={isActiveRoute(workloadsRoute)}
isHidden={Workloads.tabRoutes.length == 0}
@ -176,7 +176,7 @@ export class Sidebar extends React.Component<Props> {
text="Workloads"
icon={<Icon svg="workloads"/>}
/>
<SidebarNavItem
<SidebarItem
id="config"
isActive={isActiveRoute(configRoute)}
isHidden={Config.tabRoutes.length == 0}
@ -185,7 +185,7 @@ export class Sidebar extends React.Component<Props> {
text="Configuration"
icon={<Icon material="list"/>}
/>
<SidebarNavItem
<SidebarItem
id="networks"
isActive={isActiveRoute(networkRoute)}
isHidden={Network.tabRoutes.length == 0}
@ -194,7 +194,7 @@ export class Sidebar extends React.Component<Props> {
text="Network"
icon={<Icon material="device_hub"/>}
/>
<SidebarNavItem
<SidebarItem
id="storage"
isActive={isActiveRoute(storageRoute)}
isHidden={Storage.tabRoutes.length == 0}
@ -203,7 +203,7 @@ export class Sidebar extends React.Component<Props> {
icon={<Icon svg="storage"/>}
text="Storage"
/>
<SidebarNavItem
<SidebarItem
id="namespaces"
isActive={isActiveRoute(namespacesRoute)}
isHidden={!isAllowedResource("namespaces")}
@ -211,7 +211,7 @@ export class Sidebar extends React.Component<Props> {
icon={<Icon material="layers"/>}
text="Namespaces"
/>
<SidebarNavItem
<SidebarItem
id="events"
isActive={isActiveRoute(eventRoute)}
isHidden={!isAllowedResource("events")}
@ -219,7 +219,7 @@ export class Sidebar extends React.Component<Props> {
icon={<Icon material="access_time"/>}
text="Events"
/>
<SidebarNavItem
<SidebarItem
id="apps"
isActive={isActiveRoute(appsRoute)}
url={appsURL({ query })}
@ -227,7 +227,7 @@ export class Sidebar extends React.Component<Props> {
icon={<Icon material="apps"/>}
text="Apps"
/>
<SidebarNavItem
<SidebarItem
id="users"
isActive={isActiveRoute(usersManagementRoute)}
url={usersManagementURL({ query })}
@ -235,7 +235,7 @@ export class Sidebar extends React.Component<Props> {
icon={<Icon material="security"/>}
text="Access Control"
/>
<SidebarNavItem
<SidebarItem
id="custom-resources"
isActive={isActiveRoute(crdRoute)}
isHidden={!isAllowedResource("customresourcedefinitions")}
@ -245,11 +245,10 @@ export class Sidebar extends React.Component<Props> {
text="Custom Resources"
>
{this.renderCustomResources()}
</SidebarNavItem>
</SidebarItem>
{this.renderRegisteredMenus()}
</div>
</div>
</SidebarContext.Provider>
);
}
}

View File

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

View File

@ -0,0 +1,190 @@
import { reaction } from "mobx";
import { StorageAdapter, StorageHelper } from "../storageHelper";
import { delay } from "../../../common/utils/delay";
describe("renderer/utils/StorageHelper", () => {
describe("window.localStorage might be used as StorageAdapter", () => {
type StorageModel = string;
const storageKey = "ui-settings";
let storageHelper: StorageHelper<StorageModel>;
beforeEach(() => {
localStorage.clear();
storageHelper = new StorageHelper<StorageModel>(storageKey, {
autoInit: false,
storage: localStorage,
defaultValue: "test",
});
});
it("initialized with default value", async () => {
localStorage.setItem(storageKey, "saved"); // pretending it was saved previously
expect(storageHelper.key).toBe(storageKey);
expect(storageHelper.defaultValue).toBe("test");
expect(storageHelper.get()).toBe("test");
await storageHelper.init();
expect(storageHelper.key).toBe(storageKey);
expect(storageHelper.defaultValue).toBe("test");
expect(storageHelper.get()).toBe("saved");
});
it("updates storage", async () => {
storageHelper.init();
storageHelper.set("test2");
expect(localStorage.getItem(storageKey)).toBe("test2");
localStorage.setItem(storageKey, "test3");
storageHelper.init({ force: true }); // reload from underlying storage and merge
expect(storageHelper.get()).toBe("test3");
});
});
describe("Using custom StorageAdapter", () => {
type SettingsStorageModel = {
[key: string]: any;
message: string;
};
const storageKey = "mySettings";
const storageMock: Record<string, any> = {};
let storageHelper: StorageHelper<SettingsStorageModel>;
let storageHelperAsync: StorageHelper<SettingsStorageModel>;
let storageAdapter: StorageAdapter<SettingsStorageModel>;
const storageHelperDefaultValue: SettingsStorageModel = {
message: "hello-world",
anyOtherStorableData: 123,
};
beforeEach(() => {
storageMock[storageKey] = {
message: "saved-before",
} as SettingsStorageModel;
storageAdapter = {
onChange: jest.fn(),
getItem: jest.fn((key: string) => {
return storageMock[key];
}),
setItem: jest.fn((key: string, value: any) => {
storageMock[key] = value;
}),
removeItem: jest.fn((key: string) => {
delete storageMock[key];
}),
};
storageHelper = new StorageHelper(storageKey, {
autoInit: false,
defaultValue: storageHelperDefaultValue,
storage: storageAdapter,
});
storageHelperAsync = new StorageHelper(storageKey, {
autoInit: false,
defaultValue: storageHelperDefaultValue,
storage: {
...storageAdapter,
async getItem(key: string): Promise<SettingsStorageModel> {
await delay(500); // fake loading timeout
return storageAdapter.getItem(key);
}
},
});
});
it("loads data from storage with fallback to default-value", () => {
expect(storageHelper.get()).toEqual(storageHelperDefaultValue);
storageHelper.init();
expect(storageHelper.get().message).toBe("saved-before");
expect(storageAdapter.getItem).toHaveBeenCalledWith(storageHelper.key);
});
it("async loading from storage supported too", async () => {
expect(storageHelperAsync.initialized).toBeFalsy();
storageHelperAsync.init();
await delay(300);
expect(storageHelperAsync.get()).toEqual(storageHelperDefaultValue);
await delay(200);
expect(storageHelperAsync.get().message).toBe("saved-before");
});
it("set() fully replaces data in storage", () => {
storageHelper.init();
storageHelper.set({ message: "test2" });
expect(storageHelper.get().message).toBe("test2");
expect(storageMock[storageKey]).toEqual({ message: "test2" });
expect(storageAdapter.setItem).toHaveBeenCalledWith(storageHelper.key, { message: "test2" });
});
it("merge() does partial data tree updates", () => {
storageHelper.init();
storageHelper.merge({ message: "updated" });
expect(storageHelper.get()).toEqual({ ...storageHelperDefaultValue, message: "updated" });
expect(storageAdapter.setItem).toHaveBeenCalledWith(storageHelper.key, { ...storageHelperDefaultValue, message: "updated" });
storageHelper.merge(draft => {
draft.message = "updated2";
});
expect(storageHelper.get()).toEqual({ ...storageHelperDefaultValue, message: "updated2" });
storageHelper.merge(draft => ({
message: draft.message.replace("2", "3")
}));
expect(storageHelper.get()).toEqual({ ...storageHelperDefaultValue, message: "updated3" });
});
it("clears data in storage", () => {
storageHelper.init();
expect(storageHelper.get()).toBeTruthy();
storageHelper.clear();
expect(storageHelper.get()).toBeFalsy();
expect(storageMock[storageKey]).toBeUndefined();
expect(storageAdapter.removeItem).toHaveBeenCalledWith(storageHelper.key);
});
});
describe("data in storage-helper is observable (mobx)", () => {
let storageHelper: StorageHelper<any>;
const defaultValue: any = { firstName: "Joe" };
const observedChanges: any[] = [];
beforeEach(() => {
observedChanges.length = 0;
storageHelper = new StorageHelper<typeof defaultValue>("some-key", {
autoInit: true,
defaultValue,
storage: {
getItem: jest.fn(),
setItem: jest.fn(),
removeItem: jest.fn(),
},
});
});
it("storage.get() is observable", () => {
expect(storageHelper.get()).toEqual(defaultValue);
reaction(() => storageHelper.toJS(), change => {
observedChanges.push(change);
});
storageHelper.merge({ lastName: "Black" });
storageHelper.set("whatever");
expect(observedChanges).toEqual([{ ...defaultValue, lastName: "Black" }, "whatever",]);
});
});
});

View File

@ -1,73 +1,72 @@
// Helper to work with browser's local/session storage api
// Keeps window.localStorage state in external JSON-files.
// Because app creates random port between restarts => storage session wiped out each time.
import type { CreateObservableOptions } from "mobx/lib/api/observable";
export interface IStorageHelperOptions {
addKeyPrefix?: boolean;
useSession?: boolean; // use `sessionStorage` instead of `localStorage`
}
import path from "path";
import { app, remote } from "electron";
import { observable, reaction, when } from "mobx";
import fse from "fs-extra";
import { StorageHelper } from "./storageHelper";
import { clusterStore, getHostedClusterId } from "../../common/cluster-store";
import logger from "../../main/logger";
export function createStorage<T>(key: string, defaultValue?: T, options?: IStorageHelperOptions) {
return new StorageHelper(key, defaultValue, options);
}
let initialized = false;
const loaded = observable.box(false);
const storage = observable.map<string/* key */, any /* serializable */>();
export class StorageHelper<T> {
static keyPrefix = "lens_";
export function createStorage<T>(key: string, defaultValue?: T, observableOptions?: CreateObservableOptions) {
const clusterId = getHostedClusterId();
const savingFolder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const jsonFilePath = path.resolve(savingFolder, `${clusterId ?? "app"}.json`);
static defaultOptions: IStorageHelperOptions = {
addKeyPrefix: true,
useSession: false,
};
if (!initialized) {
initialized = true;
constructor(protected key: string, protected defaultValue?: T, protected options?: IStorageHelperOptions) {
this.options = Object.assign({}, StorageHelper.defaultOptions, options);
// read once per cluster domain
fse.readJson(jsonFilePath)
.then((data = {}) => storage.merge(data))
.catch(() => null) // ignore empty / non-existing / invalid json files
.finally(() => loaded.set(true));
if (this.options.addKeyPrefix) {
this.key = StorageHelper.keyPrefix + key;
// bind auto-saving
reaction(() => storage.toJSON(), saveFile, { delay: 250 });
// remove json-file when cluster deleted
if (clusterId !== undefined) {
when(() => clusterStore.removedClusters.has(clusterId)).then(removeFile);
}
}
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) {
async function saveFile(json = {}) {
try {
return JSON.parse(strValue);
} catch (e) {
console.error(`Parsing json failed for pair: ${this.key}=${strValue}`);
await fse.ensureDir(savingFolder, { mode: 0o755 });
await fse.writeJson(jsonFilePath, json, { spaces: 2 });
} catch (error) {
logger.error(`[save]: ${error}`, { json, jsonFilePath });
}
}
return this.defaultValue;
function removeFile() {
logger.debug("[remove]:", jsonFilePath);
fse.unlink(jsonFilePath).catch(Function);
}
set(value: T) {
this.storage.setItem(this.key, JSON.stringify(value));
return new StorageHelper<T>(key, {
autoInit: true,
observable: observableOptions,
defaultValue,
storage: {
async getItem(key: string) {
await when(() => loaded.get());
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);
return storage.get(key);
},
setItem(key: string, value: any) {
storage.set(key, value);
},
removeItem(key: string) {
storage.delete(key);
}
},
});
}

View File

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

View File

@ -0,0 +1,162 @@
// Helper for working with storages (e.g. window.localStorage, NodeJS/file-system, etc.)
import type { CreateObservableOptions } from "mobx/lib/api/observable";
import { action, comparer, observable, toJS, when } from "mobx";
import produce, { Draft, enableMapSet, setAutoFreeze } from "immer";
import { isEqual, isFunction, isPlainObject } from "lodash";
import logger from "../../main/logger";
setAutoFreeze(false); // allow to merge observables
enableMapSet(); // allow merging maps and sets
export interface StorageAdapter<T> {
[metadata: string]: any;
getItem(key: string): T | Promise<T>;
setItem(key: string, value: T): void;
removeItem(key: string): void;
onChange?(change: { key: string, value: T, oldValue?: T }): void;
}
export interface StorageHelperOptions<T> {
autoInit?: boolean; // start preloading data immediately, default: true
observable?: CreateObservableOptions;
storage: StorageAdapter<T>;
defaultValue?: T;
}
export class StorageHelper<T> {
static defaultOptions: Partial<StorageHelperOptions<any>> = {
autoInit: true,
observable: {
deep: true,
equals: comparer.shallow,
}
};
@observable private data = observable.box<T>();
@observable initialized = false;
whenReady = when(() => this.initialized);
get storage(): StorageAdapter<T> {
return this.options.storage;
}
get defaultValue(): T {
return this.options.defaultValue;
}
constructor(readonly key: string, private options: StorageHelperOptions<T>) {
this.options = { ...StorageHelper.defaultOptions, ...options };
this.configureObservable();
this.reset();
if (this.options.autoInit) {
this.init();
}
}
@action
init({ force = false } = {}) {
if (this.initialized && !force) return;
this.loadFromStorage({
onData: (data: T) => {
const notEmpty = data != null;
const notDefault = !this.isDefaultValue(data);
if (notEmpty && notDefault) {
this.merge(data);
}
this.initialized = true;
},
onError: (error?: any) => {
logger.error(`[init]: ${error}`, this);
},
});
}
private loadFromStorage(opts: { onData?(data: T): void, onError?(error?: any): void } = {}) {
let data: T | Promise<T>;
try {
data = this.storage.getItem(this.key); // sync reading from storage when exposed
if (data instanceof Promise) {
data.then(opts.onData, opts.onError);
} else {
opts?.onData(data);
}
} catch (error) {
logger.error(`[load]: ${error}`, this);
opts?.onError(error);
}
return data;
}
isDefaultValue(value: T): boolean {
return isEqual(value, this.defaultValue);
}
@action
private configureObservable(options = this.options.observable) {
this.data = observable.box<T>(this.data.get(), {
...StorageHelper.defaultOptions.observable, // inherit default observability options
...(options ?? {}),
});
this.data.observe(change => {
const { newValue, oldValue } = toJS(change, { recurseEverything: true });
this.onChange(newValue, oldValue);
});
}
protected onChange(value: T, oldValue?: T) {
if (!this.initialized) return;
try {
if (value == null) {
this.storage.removeItem(this.key);
} else {
this.storage.setItem(this.key, value);
}
this.storage.onChange?.({ value, oldValue, key: this.key });
} catch (error) {
logger.error(`[change]: ${error}`, this, { value, oldValue });
}
}
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 nextValue = produce(this.get(), (state: Draft<T>) => {
const newValue = isFunction(value) ? value(state) : value;
return isPlainObject(newValue)
? Object.assign(state, newValue) // partial updates for returned plain objects
: newValue;
});
this.set(nextValue as T);
}
toJS() {
return toJS(this.get(), { recurseEverything: true });
}
}

View File

@ -6858,6 +6858,11 @@ immediate@~3.0.5:
resolved "https://registry.yarnpkg.com/immediate/-/immediate-3.0.6.tgz#9db1dbd0faf8de6fbe0f5dd5e56bb606280de69b"
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:
version "3.2.1"
resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.2.1.tgz#633ff618506e793af5ac91bf48b72677e15cbe66"