Mobx-6 migration (#2718)

* mobx-6 migration -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* mobx-6 migration -- part 2 (npx mobx-undecorate --keepDecorators)

Signed-off-by: Roman <ixrock@gmail.com>

* mobx-6 migration -- part 3 (more fixes)

Signed-off-by: Roman <ixrock@gmail.com>

* unwrap possible observables from IPC-messaging

Signed-off-by: Roman <ixrock@gmail.com>

* mobx-6 migration -- remove @autobind as class-decorator

Signed-off-by: Roman <ixrock@gmail.com>

* mobx-6: replacing @autobind() as method-decorator to @boundMethod

Signed-off-by: Roman <ixrock@gmail.com>

* mobx-6: use toJS()-wrapper since monkey-patching require(mobx).toJS doesn't work

Signed-off-by: Roman <ixrock@gmail.com>

* removed `@observable static`

Signed-off-by: Roman <ixrock@gmail.com>

* use {useDefineForClassFields: true} in tsconfig.json

Signed-off-by: Roman <ixrock@gmail.com>

* remove ExtendedObservableMap

Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>

* fix: removed makeObservable(this) from "terminal-tab.tsx"

Signed-off-by: Roman <ixrock@gmail.com>

* storage-helper refactoring

Signed-off-by: Roman <ixrock@gmail.com>

* normalize usages of #observable-value.toJSON() / attempt to catch the wind

Signed-off-by: Roman <ixrock@gmail.com>

* refactoring, more possible branch fixes + lint

Signed-off-by: Roman <ixrock@gmail.com>

* debugging cluster-view error -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* fix: refreshing cluster-view on ready

Signed-off-by: Roman <ixrock@gmail.com>

* fix: various app-crashes related to KubeObject.spec.* access from "undefined"
fix: config-map-details crash

Signed-off-by: Roman <ixrock@gmail.com>

* fix: namespace-store refactoring / saving selected-namespaces to external json-file

Signed-off-by: Roman <ixrock@gmail.com>

* fix: don't cache mobx.when(() => this.someObservable) cause might not work as expected due later call of makeObservable(this) in constructor

Signed-off-by: Roman <ixrock@gmail.com>

* fix: app-crash on editing k8s resource

Signed-off-by: Roman <ixrock@gmail.com>

* fix: restore "all namespaces" on page reload

Signed-off-by: Roman <ixrock@gmail.com>

* - fix: persist table-sort params and cluster-view's sidebar state to lens-local-storage
- new-feature: auto-open main-window's devtools in development-mode (yes/no/ugly?)

Signed-off-by: Roman <ixrock@gmail.com>

* fix: crd definition details -> crashing with <AceEditor mode="json"> (added missing mode-file in ace-editor.tsx)

Signed-off-by: Roman <ixrock@gmail.com>

* fix: crd definitions -> groups selector couldn't deselect last selected option

Signed-off-by: Roman <ixrock@gmail.com>

* refactoring: extensions-api exports clarification for "@k8slens/extensions"

Signed-off-by: Roman <ixrock@gmail.com>

* fix: various app-crashes related to kube-events (events page, some details page, overview, etc.)

Signed-off-by: Roman <ixrock@gmail.com>

* Reverted "use {useDefineForClassFields: true} in tsconfig.json" (various app-crash fixes)
This flag seems to be not possible to use with class-inheritance in some cases.

Example / demo:
`KubeObject` class has initial type definitions for the fields like: "metadata", "kind", etc.
and constructor() has Object.assign(this, data);
Meanwhile child class, e.g. KubeEvent inherited from KubeObject and has it's own extra type definitions for underlying resource, e.g. "involvedObject", "source", etc.

So calling super(data) doesn't work as expected for child class as it's own type definitions overwrites data from parent's constructor with `undefined` at later point.

Signed-off-by: Roman <ixrock@gmail.com>

* master-merge lint-fixes

Signed-off-by: Roman <ixrock@gmail.com>

* catalog.tsx / catalog-entities.store.ts refactoring & fixes

Signed-off-by: Roman <ixrock@gmail.com>

* fix: Catalog -> Browse all tab

Signed-off-by: Roman <ixrock@gmail.com>

* fix: CommandPalette doesn't appear from global menu by click/hotkey

Signed-off-by: Roman <ixrock@gmail.com>

* - Merging interfaces & classses to avoid overwriting fields from parent's super(data)-call with Object.assign(this, data). Otherwise use "declare" keyword at class field definition.

- Revamping {useDefineForClassFields: true} to avoid issues with non-observable class fields in some cases (from previous commit):

```
@observer
export class CommandContainer extends React.Component<CommandContainerProps> {
  // without some defined initial value "commandComponent" is non-observable for some reasons
  // when tsconfig.ts has {useDefineForClassFields:false}
  @observable.ref commandComponent: React.ReactNode = null;

  constructor(props: CommandContainerProps) {
    super(props);
    makeObservable(this);
  }
```

Signed-off-by: Roman <ixrock@gmail.com>

* update KubeObject class type definition

Signed-off-by: Roman <ixrock@gmail.com>

* clean up / responding to comments

Signed-off-by: Roman <ixrock@gmail.com>

* fix: app-crash when navigating to catalog from active cluster-view, refactoring `catalog-entity-store`

Signed-off-by: Roman <ixrock@gmail.com>

* catalog-pusher clean up, replaced .observe_() to external observe() helper from "mobx"

Signed-off-by: Roman <ixrock@gmail.com>

* fix: catalog's items stale/non-observable (after connection to the cluster status still "disconnected"), lint-fixes

Signed-off-by: Roman <ixrock@gmail.com>

* fix: Catalog is empty after closing main-window and re-opening app from Tray

Signed-off-by: Roman <ixrock@gmail.com>

* fix: HotBar's icon context menu items non-observable (no "disconnect cluster", etc.)

Signed-off-by: Roman <ixrock@gmail.com>

* lint-fix/license check

Signed-off-by: Roman <ixrock@gmail.com>

* fix: redirect to catalog when disconnecting active cluster

Signed-off-by: Roman <ixrock@gmail.com>

* fix: refresh visibility of active cluster-view on switching from hotbar/catalog

Signed-off-by: Roman <ixrock@gmail.com>

* updated package.json for built-in extensions to use "*" version for packages served from main app

Signed-off-by: Roman <ixrock@gmail.com>

* - added missing makeObservable(this) to metrics-settings.tsx
- updated package-lock.json for built-in extensions
- lint fixes

Signed-off-by: Roman <ixrock@gmail.com>

* master-merge clean up fix, updated package-lock.json for built-in extensions after `make clean-extensions && make build-extensions`

Signed-off-by: Roman <ixrock@gmail.com>

* fix unit-tests

Signed-off-by: Roman <ixrock@gmail.com>

* master-merge fixes

Signed-off-by: Roman <ixrock@gmail.com>

* make lint happy

Signed-off-by: Roman <ixrock@gmail.com>

* reverted some changes, removed auto-opening devtools in dev-mode

Signed-off-by: Roman <ixrock@gmail.com>

* merge fixes

Signed-off-by: Roman <ixrock@gmail.com>

* master-merge conflict fixes:
- proper handling and navigating into catalog's active category via URL-builder

Signed-off-by: Roman <ixrock@gmail.com>

* reverting splitted params for catalog's page route to "/catalog/:group?/:kind?"

Signed-off-by: Roman <ixrock@gmail.com>

* clean-up: remove app's injecting dependencies from `extensions/kube-object-event-status/package.json`

Signed-off-by: Roman <ixrock@gmail.com>

* master-merge fix: added missing makeObservable(this) for extensions.tsx

Signed-off-by: Roman <ixrock@gmail.com>

* fix: catalog entity context menu stale/unobservable

Signed-off-by: Roman <ixrock@gmail.com>

Co-authored-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
RomanandJari Kolehmainen authored and GitHub committed 2021-05-25 10:24:31 +03:00
1 parent 0c45dd807e
commit 2c3b510997
256 files changed
+2359 -1473

No files matched your search

@@ -22,17 +22,8 @@
import { reaction } from "mobx";
import { StorageAdapter, StorageHelper } from "../storageHelper";
import { delay } from "../../../common/utils/delay";
import { ClusterStore } from "../../../common/cluster-store";
describe("renderer/utils/StorageHelper", () => {
beforeEach(() => {
ClusterStore.createInstance();
});
afterEach(() => {
ClusterStore.resetInstance();
});
describe("window.localStorage might be used as StorageAdapter", () => {
type StorageModel = string;
@@ -196,7 +187,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);
});
+53 -33
View File
@@ -21,72 +21,92 @@
// 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 { comparer, observable, reaction, toJS, when } from "mobx";
import fse from "fs-extra";
import { StorageHelper } from "./storageHelper";
import { ClusterStore, getHostedClusterId } from "../../common/cluster-store";
import logger from "../../main/logger";
let initialized = false;
const loaded = observable.box(false);
const storage = observable.map<string/* key */, any /* serializable */>();
const storage = observable({
initialized: false,
loaded: false,
data: {} as Record<string/*key*/, any>, // json-serializable
});
export function createStorage<T>(key: string, defaultValue: T, observableOptions?: CreateObservableOptions) {
/**
* Creates a helper for saving data under the "key" intended for window.localStorage
* @param key
* @param defaultValue
*/
export function createStorage<T>(key: string, defaultValue: T) {
const { logPrefix } = StorageHelper;
const clusterId = getHostedClusterId();
const savingFolder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const jsonFilePath = path.resolve(savingFolder, `${clusterId ?? "app"}.json`);
const folder = path.resolve((app || remote.app).getPath("userData"), "lens-local-storage");
const fileName = `${clusterId ?? "app"}.json`;
const filePath = path.resolve(folder, fileName);
if (!initialized) {
initialized = true;
if (!storage.initialized) {
init(); // called once per cluster-view
}
// read once per cluster domain
fse.readJson(jsonFilePath)
.then((data = {}) => storage.merge(data))
function init() {
storage.initialized = true;
// read previously saved state (if any)
fse.readJson(filePath)
.then(data => storage.data = data)
.catch(() => null) // ignore empty / non-existing / invalid json files
.finally(() => loaded.set(true));
.finally(() => {
logger.info(`${logPrefix} loading finished for ${filePath}`);
storage.loaded = true;
});
// bind auto-saving
reaction(() => storage.toJSON(), saveFile, { delay: 250 });
// bind auto-saving data changes to %storage-file.json
reaction(() => toJS(storage.data), saveFile, {
delay: 250, // lazy, avoid excessive writes to fs
equals: comparer.structural, // save only when something really changed
});
// remove json-file when cluster deleted
if (clusterId !== undefined) {
when(() => ClusterStore.getInstance(false)?.removedClusters.has(clusterId)).then(removeFile);
}
}
async function saveFile(json = {}) {
try {
await fse.ensureDir(savingFolder, { mode: 0o755 });
await fse.writeJson(jsonFilePath, json, { spaces: 2 });
} catch (error) {
logger.error(`[save]: ${error}`, { json, jsonFilePath });
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${logPrefix} saving ${filePath}`);
try {
await fse.ensureDir(folder, { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${logPrefix} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
}
}
}
function removeFile() {
logger.debug("[remove]:", jsonFilePath);
fse.unlink(jsonFilePath).catch(Function);
function removeFile() {
logger.debug(`${logPrefix} removing ${filePath}`);
fse.unlink(filePath).catch(Function);
}
}
return new StorageHelper<T>(key, {
autoInit: true,
observable: observableOptions,
defaultValue,
storage: {
async getItem(key: string) {
await when(() => loaded.get());
await when(() => storage.loaded);
return storage.get(key);
return storage.data[key];
},
setItem(key: string, value: any) {
storage.set(key, value);
storage.data[key] = value;
},
removeItem(key: string) {
storage.delete(key);
delete storage.data[key];
}
},
});
+37 -39
View File
@@ -21,15 +21,11 @@
// 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, makeObservable, 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>;
@@ -40,42 +36,42 @@ export interface StorageAdapter<T> {
export interface StorageHelperOptions<T> {
autoInit?: boolean; // start preloading data immediately, default: true
observable?: CreateObservableOptions;
storage: StorageAdapter<T>;
defaultValue: T;
}
export class StorageHelper<T> {
static readonly defaultOptions: Partial<StorageHelperOptions<any>> = {
autoInit: true,
observable: {
deep: true,
equals: comparer.shallow,
}
};
static logPrefix = "[StorageHelper]:";
readonly storage: StorageAdapter<T>;
private data = observable.box<T>(undefined, {
deep: true,
equals: comparer.structural,
});
private data: IObservableValue<T>;
@observable initialized = false;
whenReady = when(() => this.initialized);
public readonly storage: StorageAdapter<T>;
public readonly defaultValue: T;
get whenReady() {
return when(() => this.initialized);
}
get defaultValue(): T {
// return as-is since options.defaultValue might be a getter too
return this.options.defaultValue;
}
constructor(readonly key: string, private options: StorageHelperOptions<T>) {
this.data = observable.box<T>(this.options.defaultValue, {
...StorageHelper.defaultOptions.observable,
...(options.observable ?? {})
});
this.data.observe(change => {
const { newValue, oldValue } = toJS(change, { recurseEverything: true });
makeObservable(this);
this.onChange(newValue, oldValue);
const { storage, autoInit = true } = options;
this.storage = storage;
this.data.observe_(({ newValue, oldValue }) => {
this.onChange(newValue as T, oldValue as T);
});
this.storage = options.storage;
this.defaultValue = options.defaultValue;
if (this.options.autoInit) {
if (autoInit) {
this.init();
}
}
@@ -92,7 +88,7 @@ export class StorageHelper<T> {
};
private onError = (error: any): void => {
logger.error(`[load]: ${error}`, this);
logger.error(`${StorageHelper.logPrefix} loading error: ${error}`, this);
};
@action
@@ -130,29 +126,31 @@ export class StorageHelper<T> {
this.storage.onChange?.({ value, oldValue, key: this.key });
} catch (error) {
logger.error(`[change]: ${error}`, this, { value, oldValue });
logger.error(`${StorageHelper.logPrefix} updating storage: ${error}`, this, { value, oldValue });
}
}
get(): T {
return this.data.get();
return this.data.get() ?? this.defaultValue;
}
@action
set(value: T) {
if (value == null) {
// This cannot use recursion because defaultValue might be null or undefined
this.data.set(this.defaultValue);
if (this.isDefaultValue(value)) {
this.reset();
} else {
this.data.set(value);
}
}
@action
reset() {
this.set(this.defaultValue);
this.data.set(undefined);
}
@action
merge(value: Partial<T> | ((draft: Draft<T>) => Partial<T> | void)) {
const nextValue = produce(this.get(), (state: Draft<T>) => {
const nextValue = produce(this.toJSON(), (state: Draft<T>) => {
const newValue = isFunction(value) ? value(state) : value;
return isPlainObject(newValue)
@@ -163,7 +161,7 @@ export class StorageHelper<T> {
this.set(nextValue as T);
}
toJS() {
return toJS(this.get(), { recurseEverything: true });
toJSON(): T {
return toJS(this.get());
}
}