mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
1 parent
1044c544ad
commit
a0fb8b5933
47 files changed
+350
-317
No files matched your search
@@ -288,7 +288,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
|
||||
@action
|
||||
protected fromStore({ activeCluster, clusters = [] }: ClusterStoreModel = {}) {
|
||||
const currentClusters = this.clusters.toJS();
|
||||
const currentClusters = toJS(this.clusters);
|
||||
const newClusters = new Map<ClusterId, Cluster>();
|
||||
const removedClusters = new Map<ClusterId, Cluster>();
|
||||
|
||||
@@ -324,8 +324,6 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
return toJS({
|
||||
activeCluster: this.activeCluster,
|
||||
clusters: this.clustersList.map(cluster => cluster.toJSON()),
|
||||
}, {
|
||||
recurseEverything: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// Setup default configuration for external npm-packages.
|
||||
import * as Mobx from "mobx";
|
||||
import * as Immer from "immer";
|
||||
|
||||
const { isObservable, toJS, observable } = Mobx;
|
||||
|
||||
/**
|
||||
* Patch-fixing mobx@6.toJS() to support partially observable objects as data-input.
|
||||
* Otherwise it won't be recursively converted to corresponding non-observable plain JS-structure.
|
||||
* @example
|
||||
* data = {one: 1, two: observable.array([2])}; // "data" itself is non-observable
|
||||
*/
|
||||
Object.defineProperty(Mobx, "toJS", {
|
||||
value(data: any) {
|
||||
if (typeof data === "object" && !isObservable(data)) {
|
||||
return toJS(observable.box(data).get());
|
||||
}
|
||||
return toJS(data);
|
||||
}
|
||||
});
|
||||
|
||||
export default function configurePackages() {
|
||||
// Docs: https://mobx.js.org/configuration.html
|
||||
Mobx.configure({
|
||||
enforceActions: "never",
|
||||
isolateGlobalState: true,
|
||||
|
||||
// TODO: enable later (read more: https://mobx.js.org/migrating-from-4-or-5.html)
|
||||
// computedRequiresReaction: true,
|
||||
// reactionRequiresObservable: true,
|
||||
// observableRequiresReaction: true,
|
||||
});
|
||||
|
||||
// Docs: https://immerjs.github.io/immer/
|
||||
// Required for `storage-helper.ts`
|
||||
Immer.setAutoFreeze(false); // allow to merge mobx observables
|
||||
Immer.enableMapSet(); // allow to merge maps and sets
|
||||
}
|
||||
@@ -219,8 +219,6 @@ export class HotbarStore extends BaseStore<HotbarStoreModel> {
|
||||
activeHotbarId: this.activeHotbarId
|
||||
};
|
||||
|
||||
return toJS(model, {
|
||||
recurseEverything: true,
|
||||
});
|
||||
return toJS(model);
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export async function requestMain(channel: string, ...args: any[]) {
|
||||
}
|
||||
|
||||
function getSubFrames(): ClusterFrameInfo[] {
|
||||
return toJS(Array.from(clusterFrameMap.values()), { recurseEverything: true });
|
||||
return toJS(Array.from(clusterFrameMap.values()));
|
||||
}
|
||||
|
||||
export async function broadcastMessage(channel: string, ...args: any[]) {
|
||||
|
||||
@@ -285,9 +285,7 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
},
|
||||
};
|
||||
|
||||
return toJS(model, {
|
||||
recurseEverything: true,
|
||||
});
|
||||
return toJS(model);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,45 +1,10 @@
|
||||
// Decorator for binding class methods
|
||||
// Can be applied to class or single method as @autobind()
|
||||
type Constructor<T = {}> = new (...args: any[]) => T;
|
||||
// Decorator for binding class methods to proper "this"-context.
|
||||
// API: https://github.com/andreypopp/autobind-decorator
|
||||
import bindMethodOrClass from "autobind-decorator"
|
||||
|
||||
export function autobind() {
|
||||
return function (target: Constructor | object, prop?: string, descriptor?: PropertyDescriptor) {
|
||||
if (target instanceof Function) return bindClass(target);
|
||||
else return bindMethod(target, prop, descriptor);
|
||||
// TODO: unwrap, replace usages of @autobind() to @autobind
|
||||
export function autobind<T extends object>() {
|
||||
return function (target: { new(...args: any[]): T } | object, prop?: string, descriptor?: PropertyDescriptor) {
|
||||
return bindMethodOrClass(target, prop, descriptor) as any;
|
||||
};
|
||||
}
|
||||
|
||||
function bindClass<T extends Constructor>(constructor: T) {
|
||||
const proto = constructor.prototype;
|
||||
const descriptors = Object.getOwnPropertyDescriptors(proto);
|
||||
const skipMethod = (methodName: string) => {
|
||||
return methodName === "constructor"
|
||||
|| typeof descriptors[methodName].value !== "function";
|
||||
};
|
||||
|
||||
Object.keys(descriptors).forEach(prop => {
|
||||
if (skipMethod(prop)) return;
|
||||
const boundDescriptor = bindMethod(proto, prop, descriptors[prop]);
|
||||
|
||||
Object.defineProperty(proto, prop, boundDescriptor);
|
||||
});
|
||||
}
|
||||
|
||||
function bindMethod(target: object, prop?: string, descriptor?: PropertyDescriptor) {
|
||||
if (!descriptor || typeof descriptor.value !== "function") {
|
||||
throw new Error(`@autobind() must be used on class or method only`);
|
||||
}
|
||||
const { value: func, enumerable, configurable } = descriptor;
|
||||
const boundFunc = new WeakMap<object, Function>();
|
||||
|
||||
return Object.defineProperty(target, prop, {
|
||||
enumerable,
|
||||
configurable,
|
||||
get() {
|
||||
if (this === target) return func; // direct access from prototype
|
||||
if (!boundFunc.has(this)) boundFunc.set(this, func.bind(this));
|
||||
|
||||
return boundFunc.get(this);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -444,8 +444,6 @@ export class ExtensionDiscovery extends Singleton {
|
||||
toJSON(): ExtensionDiscoveryChannelMessage {
|
||||
return toJS({
|
||||
isLoaded: this.isLoaded
|
||||
}, {
|
||||
recurseEverything: true
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { app, ipcRenderer, remote } from "electron";
|
||||
import { EventEmitter } from "events";
|
||||
import { isEqual } from "lodash";
|
||||
import { action, computed, observable, reaction, toJS, when } from "mobx";
|
||||
import { action, computed, observable, reaction, when } from "mobx";
|
||||
import path from "path";
|
||||
import { getHostedCluster } from "../common/cluster-store";
|
||||
import { broadcastMessage, handleRequest, requestMain, subscribeToBroadcast } from "../common/ipc";
|
||||
@@ -40,7 +40,7 @@ export class ExtensionLoader extends Singleton {
|
||||
whenLoaded = when(() => this.isLoaded);
|
||||
|
||||
@computed get userExtensions(): Map<LensExtensionId, InstalledExtension> {
|
||||
const extensions = this.extensions.toJS();
|
||||
const extensions = this.toJSON();
|
||||
|
||||
extensions.forEach((ext, extId) => {
|
||||
if (ext.isBundled) {
|
||||
@@ -54,7 +54,7 @@ export class ExtensionLoader extends Singleton {
|
||||
@computed get userExtensionsByName(): Map<string, LensExtension> {
|
||||
const extensions = new Map();
|
||||
|
||||
for (const [, val] of this.instances.toJS()) {
|
||||
for (const [, val] of this.instances.toJSON()) {
|
||||
if (val.isBundled) {
|
||||
continue;
|
||||
}
|
||||
@@ -135,7 +135,7 @@ export class ExtensionLoader extends Singleton {
|
||||
}
|
||||
}
|
||||
|
||||
protected async initMain() {
|
||||
protected async initMain() {
|
||||
this.isLoaded = true;
|
||||
this.loadOnMain();
|
||||
|
||||
@@ -152,7 +152,7 @@ export class ExtensionLoader extends Singleton {
|
||||
});
|
||||
}
|
||||
|
||||
protected async initRenderer() {
|
||||
protected async initRenderer() {
|
||||
const extensionListHandler = (extensions: [LensExtensionId, InstalledExtension][]) => {
|
||||
this.isLoaded = true;
|
||||
this.syncExtensions(extensions);
|
||||
@@ -311,10 +311,7 @@ export class ExtensionLoader extends Singleton {
|
||||
}
|
||||
|
||||
toJSON(): Map<LensExtensionId, InstalledExtension> {
|
||||
return toJS(this.extensions, {
|
||||
exportMapsAsObjects: false,
|
||||
recurseEverything: true,
|
||||
});
|
||||
return new Map(this.extensions.toJSON());
|
||||
}
|
||||
|
||||
broadcastExtensions(main = true) {
|
||||
|
||||
@@ -47,9 +47,7 @@ export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
|
||||
toJSON(): LensExtensionsStoreModel {
|
||||
return toJS({
|
||||
extensions: this.state.toJSON(),
|
||||
}, {
|
||||
recurseEverything: true
|
||||
extensions: Object.fromEntries(this.state.toJSON()),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ describe("getPageUrl", () => {
|
||||
});
|
||||
|
||||
it("gets page url with custom params", () => {
|
||||
const params: PageParams<string> = { test1: "one", test2: "2" };
|
||||
const params: PageParams = { test1: "one", test2: "2" };
|
||||
const searchParams = new URLSearchParams(params);
|
||||
const pageUrl = getExtensionPageUrl({ extensionId: ext.name, pageId: "page-with-params", params });
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { LensExtension, sanitizeExtensionName } from "../lens-extension";
|
||||
import { LensExtension, LensExtensionId, sanitizeExtensionName } from "../lens-extension";
|
||||
import { PageParam, PageParamInit } from "../../renderer/navigation/page-param";
|
||||
import { createPageParam } from "../../renderer/navigation/helpers";
|
||||
|
||||
@@ -13,21 +13,18 @@ export interface PageRegistration {
|
||||
* When not provided, first registered page without "id" would be used for page-menus without target.pageId for same extension
|
||||
*/
|
||||
id?: string;
|
||||
params?: PageParams<string | ExtensionPageParamInit>;
|
||||
params?: PageParams<string | Omit<PageParamInit<any>, "name" | "prefix">>;
|
||||
components: PageComponents;
|
||||
}
|
||||
|
||||
// exclude "name" field since provided as key in page.params
|
||||
export type ExtensionPageParamInit = Omit<PageParamInit, "name" | "isSystem">;
|
||||
|
||||
export interface PageComponents {
|
||||
Page: React.ComponentType<any>;
|
||||
}
|
||||
|
||||
export interface PageTarget<P = PageParams> {
|
||||
export interface PageTarget {
|
||||
extensionId?: string;
|
||||
pageId?: string;
|
||||
params?: P;
|
||||
params?: PageParams;
|
||||
}
|
||||
|
||||
export interface PageParams<V = any> {
|
||||
@@ -62,13 +59,11 @@ export function getExtensionPageUrl(target: PageTarget): string {
|
||||
|
||||
if (registeredPage?.params) {
|
||||
Object.entries(registeredPage.params).forEach(([name, param]) => {
|
||||
const paramValue = param.stringify(targetParams[name]);
|
||||
pageUrl.searchParams.delete(name); // first off, clear existing value(s)
|
||||
|
||||
if (param.init.skipEmpty && param.isEmpty(paramValue)) {
|
||||
pageUrl.searchParams.delete(name);
|
||||
} else {
|
||||
pageUrl.searchParams.set(name, paramValue);
|
||||
}
|
||||
param.stringify(targetParams[name]).forEach(value => {
|
||||
pageUrl.searchParams.append(name, value);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -79,7 +74,7 @@ export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage>
|
||||
protected getRegisteredItem(page: PageRegistration, ext: LensExtension): RegisteredPage {
|
||||
const { id: pageId } = page;
|
||||
const extensionId = ext.name;
|
||||
const params = this.normalizeParams(page.params);
|
||||
const params = this.normalizeParams(extensionId, page.params);
|
||||
const components = this.normalizeComponents(page.components, params);
|
||||
const url = getExtensionPageUrl({ extensionId, pageId });
|
||||
|
||||
@@ -92,25 +87,48 @@ export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage>
|
||||
if (params) {
|
||||
const { Page } = components;
|
||||
|
||||
// inject extension's page component props.params
|
||||
components.Page = observer((props: object) => React.createElement(Page, { params, ...props }));
|
||||
}
|
||||
|
||||
return components;
|
||||
}
|
||||
|
||||
protected normalizeParams(params?: PageParams<string | ExtensionPageParamInit>): PageParams<PageParam> {
|
||||
if (!params) {
|
||||
return;
|
||||
}
|
||||
Object.entries(params).forEach(([name, value]) => {
|
||||
const paramInit: PageParamInit = typeof value === "object"
|
||||
? { name, ...value }
|
||||
: { name, defaultValue: value };
|
||||
protected normalizeParams(extensionId: LensExtensionId, params?: PageParams<string | Partial<PageParamInit>>): PageParams<PageParam> {
|
||||
if (!params) return;
|
||||
const normalizedParams: PageParams<PageParam> = {};
|
||||
|
||||
params[paramInit.name] = createPageParam(paramInit);
|
||||
Object.entries(params).forEach(([paramName, paramValue]) => {
|
||||
const paramInit: PageParamInit = {
|
||||
name: paramName,
|
||||
prefix: `${extensionId}:`,
|
||||
defaultValue: paramValue,
|
||||
};
|
||||
|
||||
// handle non-string params
|
||||
if (typeof paramValue !== "string") {
|
||||
const { defaultValue: value, parse, stringify } = paramValue;
|
||||
|
||||
const notAStringValue = typeof value !== "string" || (
|
||||
Array.isArray(value) && !value.every(value => typeof value === "string")
|
||||
);
|
||||
|
||||
if (notAStringValue && !(parse || stringify)) {
|
||||
throw new Error(
|
||||
`PageRegistry: param's "${paramName}" initialization has failed:
|
||||
paramInit.parse() and paramInit.stringify() are required for non string | string[] "defaultValue"`
|
||||
)
|
||||
}
|
||||
|
||||
paramInit.defaultValue = value;
|
||||
paramInit.parse = parse;
|
||||
paramInit.stringify = stringify;
|
||||
}
|
||||
|
||||
normalizedParams[paramName] = createPageParam(paramInit);
|
||||
});
|
||||
|
||||
return params as PageParams<PageParam>;
|
||||
return normalizedParams;
|
||||
}
|
||||
|
||||
getByPageTarget(target: PageTarget): RegisteredPage | null {
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { PageParam, PageParamInit } from "../../renderer/navigation/page-param";
|
||||
import { navigation } from "../../renderer/navigation";
|
||||
import { navigation, PageParam, PageParamInit } from "../../renderer/navigation";
|
||||
|
||||
export type { PageParamInit, PageParam } from "../../renderer/navigation/page-param";
|
||||
export { PageParamInit, PageParam } from "../../renderer/navigation/page-param";
|
||||
export { navigate, isActiveRoute } from "../../renderer/navigation/helpers";
|
||||
export { hideDetails, showDetails, getDetailsUrl } from "../../renderer/components/kube-object/kube-object-details";
|
||||
export { IURLParams } from "../../common/utils/buildUrl";
|
||||
|
||||
// exporting to extensions-api version of helper without `isSystem` flag
|
||||
export function createPageParam<V = string>(init: PageParamInit<V>) {
|
||||
export function createPageParam<V>(init: PageParamInit<V>) {
|
||||
return new PageParam<V>(init, navigation);
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import configurePackages from "./common/configure-packages";
|
||||
import fetchMock from "jest-fetch-mock";
|
||||
|
||||
// setup default configuration for external npm-packages
|
||||
configurePackages();
|
||||
|
||||
// rewire global.fetch to call 'fetchMock'
|
||||
fetchMock.enableMocks();
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ export class CatalogPusher {
|
||||
init() {
|
||||
const disposers: Disposer[] = [];
|
||||
|
||||
disposers.push(reaction(() => toJS(this.catalog.items, { recurseEverything: true }), (items) => {
|
||||
disposers.push(reaction(() => toJS(this.catalog.items), (items) => {
|
||||
broadcastMessage("catalog:items", items);
|
||||
}, {
|
||||
fireImmediately: true,
|
||||
}));
|
||||
|
||||
const listener = subscribeToBroadcast("catalog:broadcast", () => {
|
||||
broadcastMessage("catalog:items", toJS(this.catalog.items, { recurseEverything: true }));
|
||||
broadcastMessage("catalog:items", toJS(this.catalog.items));
|
||||
});
|
||||
|
||||
disposers.push(() => unsubscribeFromBroadcast("catalog:broadcast", listener));
|
||||
|
||||
@@ -47,7 +47,7 @@ export class KubeconfigSyncManager extends Singleton {
|
||||
this.startNewSync(filePath);
|
||||
}
|
||||
|
||||
this.syncListDisposer = UserStore.getInstance().syncKubeconfigEntries.observe(change => {
|
||||
this.syncListDisposer = UserStore.getInstance().syncKubeconfigEntries.observe_(change => {
|
||||
switch (change.type) {
|
||||
case "add":
|
||||
this.startNewSync(change.name);
|
||||
|
||||
@@ -14,7 +14,7 @@ export class ClusterManager extends Singleton {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
reaction(() => toJS(ClusterStore.getInstance().clustersList, { recurseEverything: true }), () => {
|
||||
reaction(() => toJS(ClusterStore.getInstance().clustersList), () => {
|
||||
this.updateCatalog(ClusterStore.getInstance().clustersList);
|
||||
}, { fireImmediately: true });
|
||||
|
||||
|
||||
+3
-9
@@ -206,9 +206,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
@computed get prometheusPreferences(): ClusterPrometheusPreferences {
|
||||
const { prometheus, prometheusProvider } = this.preferences;
|
||||
|
||||
return toJS({ prometheus, prometheusProvider }, {
|
||||
recurseEverything: true,
|
||||
});
|
||||
return toJS({ prometheus, prometheusProvider });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -549,9 +547,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
accessibleNamespaces: this.accessibleNamespaces,
|
||||
};
|
||||
|
||||
return toJS(model, {
|
||||
recurseEverything: true
|
||||
});
|
||||
return toJS(model);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -571,9 +567,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
isGlobalWatchEnabled: this.isGlobalWatchEnabled,
|
||||
};
|
||||
|
||||
return toJS(state, {
|
||||
recurseEverything: true
|
||||
});
|
||||
return toJS(state);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -50,9 +50,7 @@ export class FilesystemProvisionerStore extends BaseStore<FSProvisionModel> {
|
||||
|
||||
toJSON(): FSProvisionModel {
|
||||
return toJS({
|
||||
extensions: this.registeredExtensions.toJSON(),
|
||||
}, {
|
||||
recurseEverything: true
|
||||
extensions: Object.fromEntries(this.registeredExtensions.toJSON()),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ import { HotbarStore } from "../common/hotbar-store";
|
||||
import { HelmRepoManager } from "./helm/helm-repo-manager";
|
||||
import { KubeconfigSyncManager } from "./catalog-sources";
|
||||
import { handleWsUpgrade } from "./proxy/ws-upgrade";
|
||||
import configurePackages from "../common/configure-packages";
|
||||
|
||||
const workingDir = path.join(app.getPath("appData"), appName);
|
||||
|
||||
@@ -55,6 +56,7 @@ if (process.env.LENS_DISABLE_GPU) {
|
||||
app.disableHardwareAcceleration();
|
||||
}
|
||||
|
||||
configurePackages();
|
||||
mangleProxyEnv();
|
||||
|
||||
if (app.commandLine.getSwitchValue("proxy-server") !== "") {
|
||||
|
||||
@@ -22,6 +22,9 @@ import { ThemeStore } from "./theme.store";
|
||||
import { HelmRepoManager } from "../main/helm/helm-repo-manager";
|
||||
import { ExtensionInstallationStateStore } from "./components/+extensions/extension-install.store";
|
||||
import { DefaultProps } from "./mui-base-theme";
|
||||
import configurePackages from "../common/configure-packages";
|
||||
|
||||
configurePackages();
|
||||
|
||||
/**
|
||||
* If this is a development buid, wait a second to attach
|
||||
|
||||
@@ -51,7 +51,7 @@ export class ReleaseDetails extends Component<Props> {
|
||||
);
|
||||
|
||||
@disposeOnUnmount
|
||||
secretWatcher = reaction(() => secretsStore.items.toJS(), () => {
|
||||
secretWatcher = reaction(() => secretsStore.items.toJSON(), () => {
|
||||
if (!this.props.release) return;
|
||||
const { getReleaseSecret } = releaseStore;
|
||||
const { release } = this.props;
|
||||
|
||||
@@ -20,7 +20,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
}
|
||||
|
||||
watchAssociatedSecrets(): (() => void) {
|
||||
return reaction(() => secretsStore.items.toJS(), () => {
|
||||
return reaction(() => secretsStore.items.toJSON(), () => {
|
||||
if (this.isLoading) return;
|
||||
const newSecrets = this.getReleaseSecrets();
|
||||
const amountChanged = newSecrets.length !== this.releaseSecrets.size;
|
||||
|
||||
@@ -39,7 +39,7 @@ export class ConfigMapDetails extends React.Component<Props> {
|
||||
|
||||
try {
|
||||
this.isSaving = true;
|
||||
await configMapsStore.update(configMap, { ...configMap, data: this.data.toJSON() });
|
||||
await configMapsStore.update(configMap, { ...configMap, data: Object.fromEntries(this.data.toJSON()) });
|
||||
Notifications.ok(
|
||||
<p>
|
||||
<>ConfigMap <b>{configMap.getName()}</b> successfully updated.</>
|
||||
@@ -54,7 +54,7 @@ export class ConfigMapDetails extends React.Component<Props> {
|
||||
const { object: configMap } = this.props;
|
||||
|
||||
if (!configMap) return null;
|
||||
const data = Object.entries(this.data.toJSON());
|
||||
const data = this.data.toJSON();
|
||||
|
||||
return (
|
||||
<div className="ConfigMapDetails">
|
||||
|
||||
@@ -14,8 +14,6 @@ import { Icon } from "../icon";
|
||||
|
||||
export const crdGroupsUrlParam = createPageParam<string[]>({
|
||||
name: "groups",
|
||||
multiValues: true,
|
||||
isSystem: true,
|
||||
defaultValue: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ export class CRDStore extends KubeObjectStore<CustomResourceDefinition> {
|
||||
super();
|
||||
|
||||
// auto-init stores for crd-s
|
||||
reaction(() => this.items.toJS(), items => items.forEach(initStore));
|
||||
reaction(() => this.items.toJSON(), items => items.forEach(initStore));
|
||||
}
|
||||
|
||||
protected sortItems(items: CustomResourceDefinition[]) {
|
||||
|
||||
@@ -9,8 +9,6 @@ const selectedNamespaces = createStorage<string[] | undefined>("selected_namespa
|
||||
|
||||
export const namespaceUrlParam = createPageParam<string[]>({
|
||||
name: "namespaces",
|
||||
isSystem: true,
|
||||
multiValues: true,
|
||||
defaultValue: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ export class App extends React.Component {
|
||||
whatInput.ask(); // Start to monitor user input device
|
||||
|
||||
// Setup hosted cluster context
|
||||
KubeObjectStore.defaultContext = clusterContext;
|
||||
KubeObjectStore.defaultContext.set(clusterContext);
|
||||
kubeWatchApi.context = clusterContext;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ export class Dialog extends React.PureComponent<DialogProps, DialogState> {
|
||||
};
|
||||
|
||||
@disposeOnUnmount
|
||||
closeOnNavigate = reaction(() => navigation.getPath(), () => this.close());
|
||||
closeOnNavigate = reaction(() => navigation.toString(), () => this.close());
|
||||
|
||||
public state: DialogState = {
|
||||
isOpen: this.props.isOpen,
|
||||
|
||||
@@ -54,7 +54,7 @@ export class DockTabStore<T> {
|
||||
}
|
||||
|
||||
protected getStorableData(): DockTabStorageState<T> {
|
||||
const allTabsData = toJS(this.data, { recurseEverything: true });
|
||||
const allTabsData = toJS(this.data);
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(allTabsData).map(([tabId, tabData]) => {
|
||||
|
||||
@@ -21,7 +21,7 @@ export class ErrorBoundary extends React.Component<Props, State> {
|
||||
|
||||
@disposeOnUnmount
|
||||
resetOnNavigate = reaction(
|
||||
() => navigation.getPath(),
|
||||
() => navigation.toString(),
|
||||
() => this.setState({ error: null, errorInfo: null })
|
||||
);
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import { createPageParam } from "../../navigation";
|
||||
|
||||
export const searchUrlParam = createPageParam({
|
||||
name: "search",
|
||||
isSystem: true,
|
||||
defaultValue: "",
|
||||
});
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry"
|
||||
*/
|
||||
export const kubeDetailsUrlParam = createPageParam({
|
||||
name: "kube-details",
|
||||
isSystem: true,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -30,7 +29,6 @@ export const kubeDetailsUrlParam = createPageParam({
|
||||
*/
|
||||
export const kubeSelectedUrlParam = createPageParam({
|
||||
name: "kube-selected",
|
||||
isSystem: true,
|
||||
get defaultValue() {
|
||||
return kubeDetailsUrlParam.get();
|
||||
}
|
||||
@@ -49,12 +47,12 @@ export function hideDetails() {
|
||||
export function getDetailsUrl(selfLink: string, resetSelected = false, mergeGlobals = true) {
|
||||
const params = new URLSearchParams(mergeGlobals ? navigation.searchParams : "");
|
||||
|
||||
params.set(kubeDetailsUrlParam.urlName, selfLink);
|
||||
params.set(kubeDetailsUrlParam.name, selfLink);
|
||||
|
||||
if (resetSelected) {
|
||||
params.delete(kubeSelectedUrlParam.urlName);
|
||||
params.delete(kubeSelectedUrlParam.name);
|
||||
} else {
|
||||
params.set(kubeSelectedUrlParam.urlName, kubeSelectedUrlParam.get());
|
||||
params.set(kubeSelectedUrlParam.name, kubeSelectedUrlParam.get());
|
||||
}
|
||||
|
||||
return `?${params}`;
|
||||
|
||||
@@ -46,12 +46,10 @@ export interface TableProps extends React.DOMAttributes<HTMLDivElement> {
|
||||
|
||||
export const sortByUrlParam = createPageParam({
|
||||
name: "sort",
|
||||
isSystem: true,
|
||||
});
|
||||
|
||||
export const orderByUrlParam = createPageParam({
|
||||
name: "order",
|
||||
isSystem: true,
|
||||
});
|
||||
|
||||
@observer
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { createStorage } from "../utils";
|
||||
import { CreateObservableOptions } from "mobx/lib/api/observable";
|
||||
import { CreateObservableOptions } from "mobx";
|
||||
|
||||
export function useStorage<T>(key: string, initialValue: T, options?: CreateObservableOptions) {
|
||||
const storage = createStorage(key, initialValue, options);
|
||||
|
||||
@@ -24,7 +24,7 @@ export abstract class ItemStore<T extends ItemObject = ItemObject> {
|
||||
}
|
||||
|
||||
public getItems(): T[] {
|
||||
return this.items.toJS();
|
||||
return this.items.toJSON();
|
||||
}
|
||||
|
||||
public getTotalCount(): number {
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface KubeObjectStoreLoadingParams {
|
||||
|
||||
@autobind()
|
||||
export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemStore<T> {
|
||||
@observable static defaultContext: ClusterContext; // TODO: support multiple cluster contexts
|
||||
static defaultContext = observable.box<ClusterContext>(); // TODO: support multiple cluster contexts
|
||||
|
||||
abstract api: KubeApi<T>;
|
||||
public readonly limit?: number;
|
||||
@@ -34,7 +34,7 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
}
|
||||
|
||||
get context(): ClusterContext {
|
||||
return KubeObjectStore.defaultContext;
|
||||
return KubeObjectStore.defaultContext.get();
|
||||
}
|
||||
|
||||
@computed get contextItems(): T[] {
|
||||
@@ -350,7 +350,7 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
|
||||
@action
|
||||
protected updateFromEventsBuffer() {
|
||||
const items = this.items.toJS();
|
||||
const items = this.items.toJSON();
|
||||
|
||||
for (const { type, object } of this.eventsBuffer.clear()) {
|
||||
const index = items.findIndex(item => item.getId() === object.metadata?.uid);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { LocationDescriptor } from "history";
|
||||
import { matchPath, RouteProps } from "react-router";
|
||||
import { PageParam, PageSystemParamInit } from "./page-param";
|
||||
import { PageParam, PageParamInit } from "./page-param";
|
||||
import { clusterViewRoute, IClusterViewRouteParams } from "../components/cluster-manager/cluster-view.route";
|
||||
import { navigation } from "./history";
|
||||
|
||||
@@ -14,7 +14,7 @@ export function navigate(location: LocationDescriptor) {
|
||||
}
|
||||
}
|
||||
|
||||
export function createPageParam<V = string>(init: PageSystemParamInit<V>) {
|
||||
export function createPageParam<V = string>(init: PageParamInit<V>) {
|
||||
return new PageParam<V>(init, navigation);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,14 @@ import { createObservableHistory } from "mobx-observable-history";
|
||||
import logger from "../../main/logger";
|
||||
|
||||
export const history = ipcRenderer ? createBrowserHistory() : createMemoryHistory();
|
||||
export const navigation = createObservableHistory(history);
|
||||
|
||||
export const navigation = createObservableHistory(history, {
|
||||
searchParams: {
|
||||
skipEmpty: true, // skip empty params, e.g. "?x=&y2=" will be "?y=2"
|
||||
joinArrays: false, // join multiple params with same name, e.g. "?x=1&x=2" => "?x=1,2"
|
||||
joinArraysWith: ",", // param values splitter, applicable only with {joinArrays:true}
|
||||
}
|
||||
});
|
||||
|
||||
navigation.listen((location, action) => {
|
||||
const isClusterView = !process.isMainFrame;
|
||||
|
||||
@@ -4,5 +4,6 @@ import { bindEvents } from "./events";
|
||||
|
||||
export * from "./history";
|
||||
export * from "./helpers";
|
||||
export * from "./page-param";
|
||||
|
||||
bindEvents();
|
||||
@@ -1,135 +1,113 @@
|
||||
// Manage observable URL-param from document.location.search
|
||||
import { IObservableHistory } from "mobx-observable-history";
|
||||
// Manage observable param from document's location.search
|
||||
import type { ObservableHistory } from "mobx-observable-history";
|
||||
import { action, computed } from "mobx";
|
||||
|
||||
export interface PageParamInit<V = any> {
|
||||
name: string;
|
||||
defaultValue?: V;
|
||||
defaultValueStringified?: string | string[]; // serialized version of "defaultValue"
|
||||
multiValues?: boolean; // false == by default
|
||||
multiValueSep?: string; // joining multiple values with separator, default: ","
|
||||
skipEmpty?: boolean; // skip empty value(s), e.g. "?param=", default: true
|
||||
parse?(value: string[]): V; // deserialize from URL
|
||||
stringify?(value: V): string | string[]; // serialize params to URL
|
||||
}
|
||||
|
||||
export interface PageSystemParamInit<V = any> extends PageParamInit<V> {
|
||||
isSystem?: boolean;
|
||||
prefix?: string; // name prefix, for extensions it's `${extension.id}:`
|
||||
parse?(value: string | string[]): V; // from URL
|
||||
stringify?(value: V): string | string[]; // to URL
|
||||
}
|
||||
|
||||
// TODO: write tests
|
||||
export class PageParam<V = any> {
|
||||
static SYSTEM_PREFIX = "lens-";
|
||||
|
||||
readonly name: string;
|
||||
readonly urlName: string;
|
||||
readonly isMulti: boolean;
|
||||
|
||||
constructor(readonly init: PageParamInit<V> | PageSystemParamInit<V>, protected history: IObservableHistory) {
|
||||
const { isSystem, name } = init as PageSystemParamInit;
|
||||
constructor(private init: PageParamInit<V>, private history: ObservableHistory) {
|
||||
const { prefix, name, defaultValue } = init;
|
||||
|
||||
this.name = name;
|
||||
this.init.skipEmpty ??= true;
|
||||
this.init.multiValueSep ??= ",";
|
||||
|
||||
// prefixing to avoid collisions with extensions
|
||||
this.urlName = `${isSystem ? PageParam.SYSTEM_PREFIX : ""}${name}`;
|
||||
this.name = `${prefix ?? ""}${name}`; // actual prefixed URL-name
|
||||
this.isMulti = Array.isArray(defaultValue); // multi-values param
|
||||
}
|
||||
|
||||
isEmpty(value: V | any) {
|
||||
return [value].flat().every(value => value == "" || value == null);
|
||||
// should be a getter since `init.defaultValue` could be a getter too
|
||||
get defaultValue(): V | undefined {
|
||||
return this.init.defaultValue;
|
||||
}
|
||||
|
||||
parse(values: string[]): V {
|
||||
const { parse, multiValues } = this.init;
|
||||
parse(values: string | string[]): V {
|
||||
const { parse } = this.init;
|
||||
|
||||
if (!multiValues) values.splice(1); // reduce values to single item
|
||||
const parsedValues = [parse ? parse(values) : values].flat();
|
||||
|
||||
return multiValues ? parsedValues : parsedValues[0] as any;
|
||||
}
|
||||
|
||||
stringify(value: V = this.get()): string {
|
||||
const { stringify, multiValues, multiValueSep, skipEmpty } = this.init;
|
||||
|
||||
if (skipEmpty && this.isEmpty(value)) {
|
||||
return "";
|
||||
if (parse) {
|
||||
return parse(values);
|
||||
}
|
||||
|
||||
if (multiValues) {
|
||||
const values = [value].flat();
|
||||
const stringValues = [stringify ? stringify(value) : values.map(String)].flat();
|
||||
// return as-is ("string"-value based params)
|
||||
return values as any as V;
|
||||
}
|
||||
|
||||
return stringValues.join(multiValueSep);
|
||||
stringify(value: V = this.get()): string[] {
|
||||
const { stringify } = this.init;
|
||||
|
||||
if (stringify) {
|
||||
return [stringify(value)].flat();
|
||||
}
|
||||
|
||||
return [stringify ? stringify(value) : String(value)].flat()[0];
|
||||
return [value].flat().map(String);
|
||||
}
|
||||
|
||||
get(): V {
|
||||
const value = this.parse(this.getRaw());
|
||||
|
||||
if (this.init.skipEmpty && this.isEmpty(value)) {
|
||||
return this.getDefaultValue();
|
||||
}
|
||||
|
||||
return value;
|
||||
return this.parse(this.getRaw()) ?? this.defaultValue;
|
||||
}
|
||||
|
||||
set(value: V, { mergeGlobals = true, replaceHistory = false } = {}) {
|
||||
const search = this.toSearchString({ mergeGlobals, value });
|
||||
@action
|
||||
set(value: V, { mergeGlobals = true, replaceHistory = false } = {}): void {
|
||||
const search = this.toString({ mergeGlobals, value });
|
||||
|
||||
this.history.merge({ search }, replaceHistory);
|
||||
}
|
||||
|
||||
setRaw(value: string | string[]) {
|
||||
const { history, urlName } = this;
|
||||
const { multiValues, multiValueSep, skipEmpty } = this.init;
|
||||
const paramValue = multiValues ? [value].flat().join(multiValueSep) : String(value);
|
||||
/**
|
||||
* Set stringified raw value(s) and update `document.location.search`
|
||||
* @param {string | string[]} value
|
||||
*/
|
||||
@action
|
||||
setRaw(value: string | string[]): void {
|
||||
const values: string[] = [value].flat();
|
||||
|
||||
if (skipEmpty && this.isEmpty(paramValue)) {
|
||||
history.searchParams.delete(urlName);
|
||||
} else {
|
||||
history.searchParams.set(urlName, paramValue);
|
||||
}
|
||||
}
|
||||
|
||||
getRaw(): string[] {
|
||||
const { history, urlName } = this;
|
||||
const { multiValueSep } = this.init;
|
||||
|
||||
return history.searchParams.getAsArray(urlName, multiValueSep);
|
||||
}
|
||||
|
||||
getDefaultValue() {
|
||||
const { defaultValue, defaultValueStringified } = this.init;
|
||||
|
||||
return defaultValueStringified ? this.parse([defaultValueStringified].flat()) : defaultValue;
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.history.searchParams.delete(this.urlName);
|
||||
}
|
||||
|
||||
toSearchString({ withPrefix = true, mergeGlobals = true, value = this.get() } = {}): string {
|
||||
const { history, urlName, init: { skipEmpty } } = this;
|
||||
const searchParams = new URLSearchParams(mergeGlobals ? history.location.search : "");
|
||||
|
||||
searchParams.set(urlName, this.stringify(value));
|
||||
|
||||
if (skipEmpty) {
|
||||
searchParams.forEach((value: any, paramName) => {
|
||||
if (this.isEmpty(value)) searchParams.delete(paramName);
|
||||
if (this.isMulti) {
|
||||
this.clear();
|
||||
values.forEach(value => {
|
||||
this.history.searchParams.append(this.name, value);
|
||||
});
|
||||
} else {
|
||||
this.history.searchParams.set(this.name, values[0]);
|
||||
}
|
||||
|
||||
if (Array.from(searchParams).length > 0) {
|
||||
return `${withPrefix ? "?" : ""}${searchParams}`;
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
toObjectParam(value = this.get()): Record<string, V> {
|
||||
/**
|
||||
* Get stringified raw value(s) from `document.location.search`
|
||||
*/
|
||||
@computed getRaw(): string | string[] {
|
||||
const values: string[] = this.history.searchParams.getAll(this.name);
|
||||
|
||||
return this.isMulti ? values : values[0];
|
||||
}
|
||||
|
||||
@action
|
||||
clear() {
|
||||
this.history.searchParams.delete(this.name);
|
||||
}
|
||||
|
||||
toString({ withPrefix = true, mergeGlobals = true, value = this.get() } = {}): string {
|
||||
let searchParams = new URLSearchParams();
|
||||
|
||||
if (mergeGlobals) {
|
||||
searchParams = new URLSearchParams(this.history.searchParams);
|
||||
searchParams.delete(this.name);
|
||||
}
|
||||
|
||||
this.stringify(value).forEach(value => {
|
||||
searchParams.append(this.name, value);
|
||||
});
|
||||
return `${withPrefix ? "?" : ""}${searchParams}`;
|
||||
}
|
||||
|
||||
toObjectParam(): Record<string, V> {
|
||||
return {
|
||||
[this.urlName]: value,
|
||||
[this.name]: this.get(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ describe("renderer/utils/StorageHelper", () => {
|
||||
it("storage.get() is observable", () => {
|
||||
expect(storageHelper.get()).toEqual(defaultValue);
|
||||
|
||||
reaction(() => storageHelper.toJS(), change => {
|
||||
reaction(() => storageHelper.toJSON(), change => {
|
||||
observedChanges.push(change);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
// 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";
|
||||
|
||||
import path from "path";
|
||||
import { app, remote } from "electron";
|
||||
import { observable, reaction, when } from "mobx";
|
||||
import { observable, reaction, when, CreateObservableOptions } from "mobx";
|
||||
import fse from "fs-extra";
|
||||
import { StorageHelper } from "./storageHelper";
|
||||
import { ClusterStore, getHostedClusterId } from "../../common/cluster-store";
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
// 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, IObservableValue } from "mobx";
|
||||
import produce, { Draft, enableMapSet, setAutoFreeze } from "immer";
|
||||
import { action, comparer, CreateObservableOptions, IObservableValue, observable, toJS, when } from "mobx";
|
||||
import produce, { Draft } 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>;
|
||||
@@ -45,10 +41,8 @@ export class StorageHelper<T> {
|
||||
...StorageHelper.defaultOptions.observable,
|
||||
...(options.observable ?? {})
|
||||
});
|
||||
this.data.observe(change => {
|
||||
const { newValue, oldValue } = toJS(change, { recurseEverything: true });
|
||||
|
||||
this.onChange(newValue, oldValue);
|
||||
this.data.observe_(({ newValue, oldValue }) => {
|
||||
this.onChange(newValue as T, oldValue as T);
|
||||
});
|
||||
|
||||
this.storage = options.storage;
|
||||
@@ -117,17 +111,18 @@ export class StorageHelper<T> {
|
||||
return this.data.get();
|
||||
}
|
||||
|
||||
@action
|
||||
set(value: T) {
|
||||
if (value == null) {
|
||||
// This cannot use recursion because defaultValue might be null or undefined
|
||||
this.data.set(this.defaultValue);
|
||||
this.reset();
|
||||
} else {
|
||||
this.data.set(value);
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
reset() {
|
||||
this.set(this.defaultValue);
|
||||
this.data.set(this.defaultValue);
|
||||
}
|
||||
|
||||
merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) {
|
||||
@@ -142,7 +137,7 @@ export class StorageHelper<T> {
|
||||
this.set(nextValue as T);
|
||||
}
|
||||
|
||||
toJS() {
|
||||
return toJS(this.get(), { recurseEverything: true });
|
||||
toJSON(): T {
|
||||
return toJS(this.get());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user