Cascade different refactorings to eliminate global shared state from app paths

Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com>

Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
Janne SavolainenandMikko Aspiala committed 2022-01-05 13:26:49 +02:00
1 parent 908a40975e
commit 9d33fff906
336 files changed
+9105 -3307

No files matched your search

@@ -0,0 +1,33 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { CatalogEntityStore } from "./catalog-entity.store";
import catalogEntityRegistryInjectable from "../../../api/catalog-entity-registry/catalog-entity-registry.injectable";
const catalogEntityStoreInjectable = getInjectable({
instantiate: (di) => new CatalogEntityStore({
registry: di.inject(catalogEntityRegistryInjectable),
}),
lifecycle: lifecycleEnum.singleton,
});
export default catalogEntityStoreInjectable;
@@ -20,14 +20,18 @@
*/
import { computed, makeObservable, observable, reaction } from "mobx";
import { catalogEntityRegistry, CatalogEntityRegistry } from "../../api/catalog-entity-registry";
import type { CatalogEntity } from "../../api/catalog-entity";
import { ItemStore } from "../../../common/item.store";
import { CatalogCategory, catalogCategoryRegistry } from "../../../common/catalog";
import { autoBind, disposer } from "../../../common/utils";
import type { CatalogEntityRegistry } from "../../../api/catalog-entity-registry";
import type { CatalogEntity } from "../../../api/catalog-entity";
import { ItemStore } from "../../../../common/item.store";
import { CatalogCategory, catalogCategoryRegistry } from "../../../../common/catalog";
import { autoBind, disposer } from "../../../../common/utils";
interface Dependencies {
registry: CatalogEntityRegistry
}
export class CatalogEntityStore extends ItemStore<CatalogEntity> {
constructor(private registry: CatalogEntityRegistry = catalogEntityRegistry) {
constructor(private dependencies: Dependencies) {
super();
makeObservable(this);
autoBind(this);
@@ -38,10 +42,10 @@ export class CatalogEntityStore extends ItemStore<CatalogEntity> {
@computed get entities() {
if (!this.activeCategory) {
return this.registry.filteredItems;
return this.dependencies.registry.filteredItems;
}
return this.registry.getItemsForCategory(this.activeCategory, { filtered: true });
return this.dependencies.registry.getItemsForCategory(this.activeCategory, { filtered: true });
}
@computed get selectedItem() {
@@ -69,6 +73,6 @@ export class CatalogEntityStore extends ItemStore<CatalogEntity> {
}
onRun(entity: CatalogEntity): void {
this.registry.onRun(entity);
this.dependencies.registry.onRun(entity);
}
}
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
import { browseCatalogTab } from "../../../../common/routes";
import createStorageInjectable from "../../../utils/create-storage/create-storage.injectable";
const catalogPreviousActiveTabStorageInjectable = getInjectable({
instantiate: (di) => {
const createStorage = di.inject(createStorageInjectable);
return createStorage(
"catalog-previous-active-tab",
browseCatalogTab,
);
},
lifecycle: lifecycleEnum.singleton,
});
export default catalogPreviousActiveTabStorageInjectable;
@@ -20,17 +20,27 @@
*/
import React from "react";
import { render, screen } from "@testing-library/react";
import { screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Catalog } from "./catalog";
import { createMemoryHistory } from "history";
import { mockWindow } from "../../../../__mocks__/windowMock";
import { kubernetesClusterCategory } from "../../../common/catalog-entities/kubernetes-cluster";
import { catalogCategoryRegistry, CatalogCategoryRegistry, CatalogEntity, CatalogEntityActionContext, CatalogEntityData } from "../../../common/catalog";
import { CatalogEntityRegistry } from "../../../renderer/api/catalog-entity-registry";
import { CatalogCategoryRegistry, CatalogEntity, CatalogEntityActionContext, CatalogEntityData } from "../../../common/catalog";
import { CatalogEntityRegistry } from "../../api/catalog-entity-registry";
import { CatalogEntityDetailRegistry } from "../../../extensions/registries";
import { CatalogEntityStore } from "./catalog-entity.store";
import { AppPaths } from "../../../common/app-paths";
import type { CatalogEntityStore } from "./catalog-entity-store/catalog-entity.store";
import { getDiForUnitTesting } from "../getDiForUnitTesting";
import type { DependencyInjectionContainer } from "@ogre-tools/injectable";
import catalogEntityStoreInjectable from "./catalog-entity-store/catalog-entity-store.injectable";
import catalogEntityRegistryInjectable
from "../../api/catalog-entity-registry/catalog-entity-registry.injectable";
import type { DiRender } from "../test-utils/renderFor";
import { renderFor } from "../test-utils/renderFor";
import { ThemeStore } from "../../theme.store";
import { UserStore } from "../../../common/user-store";
import mockFs from "mock-fs";
import directoryForUserDataInjectable
from "../../../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
mockWindow();
jest.mock("electron", () => ({
@@ -49,8 +59,6 @@ jest.mock("electron", () => ({
},
}));
AppPaths.init();
jest.mock("./hotbar-toggle-menu-item", () => ({
HotbarToggleMenuItem: () => <div>menu item</div>,
}));
@@ -103,31 +111,46 @@ describe("<Catalog />", () => {
}, onRun);
}
beforeEach(() => {
CatalogEntityDetailRegistry.createInstance();
// mock the return of getting CatalogCategoryRegistry.filteredItems
jest
.spyOn(catalogCategoryRegistry, "filteredItems", "get")
.mockImplementation(() => {
return [kubernetesClusterCategory];
});
let di: DependencyInjectionContainer;
let catalogEntityStore: CatalogEntityStore;
let catalogEntityRegistry: CatalogEntityRegistry;
let render: DiRender;
// we don't care what this.renderList renders in this test case.
jest.spyOn(Catalog.prototype, "renderList").mockImplementation(() => {
return <span>empty renderList</span>;
});
beforeEach(async () => {
di = getDiForUnitTesting({ doGeneralOverrides: true });
di.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
await di.runSetups();
mockFs();
UserStore.createInstance();
ThemeStore.createInstance();
CatalogEntityDetailRegistry.createInstance();
render = renderFor(di);
const catalogCategoryRegistry = new CatalogCategoryRegistry();
catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
di.override(catalogEntityRegistryInjectable, () => catalogEntityRegistry);
catalogEntityStore = di.inject(catalogEntityStoreInjectable);
});
afterEach(() => {
UserStore.resetInstance();
ThemeStore.resetInstance();
CatalogEntityDetailRegistry.resetInstance();
jest.clearAllMocks();
jest.restoreAllMocks();
mockFs.restore();
});
it("can use catalogEntityRegistry.addOnBeforeRun to add hooks for catalog entities", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn();
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -153,7 +176,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
@@ -161,9 +183,6 @@ describe("<Catalog />", () => {
});
it("onBeforeRun prevents event => onRun wont be triggered", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn();
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -187,7 +206,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
@@ -195,9 +213,6 @@ describe("<Catalog />", () => {
});
it("addOnBeforeRun throw an exception => onRun will be triggered", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn();
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -222,7 +237,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
@@ -230,9 +244,6 @@ describe("<Catalog />", () => {
});
it("addOnRunHook return a promise and does not prevent run event => onRun()", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn(() => done());
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -252,7 +263,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
@@ -260,9 +270,6 @@ describe("<Catalog />", () => {
});
it("addOnRunHook return a promise and prevents event wont be triggered", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn();
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -289,7 +296,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
@@ -297,9 +303,6 @@ describe("<Catalog />", () => {
});
it("addOnRunHook return a promise and reject => onRun will be triggered", (done) => {
const catalogCategoryRegistry = new CatalogCategoryRegistry();
const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);
const catalogEntityStore = new CatalogEntityStore(catalogEntityRegistry);
const onRun = jest.fn();
const catalogEntityItem = createMockCatalogEntity(onRun);
@@ -324,7 +327,6 @@ describe("<Catalog />", () => {
history={history}
location={mockLocation}
match={mockMatch}
catalogEntityStore={catalogEntityStore}
/>,
);
+45 -31
View File
@@ -25,7 +25,7 @@ import React from "react";
import { disposeOnUnmount, observer } from "mobx-react";
import { ItemListLayout } from "../item-object-list";
import { action, makeObservable, observable, reaction, runInAction, when } from "mobx";
import { CatalogEntityStore } from "./catalog-entity.store";
import type { CatalogEntityStore } from "./catalog-entity-store/catalog-entity.store";
import { navigate } from "../../navigation";
import { MenuItem, MenuActions } from "../menu";
import type { CatalogEntityContextMenu, CatalogEntityContextMenuContext } from "../../api/catalog-entity";
@@ -36,7 +36,7 @@ import { CatalogAddButton } from "./catalog-add-button";
import type { RouteComponentProps } from "react-router";
import { Notifications } from "../notifications";
import { MainLayout } from "../layout/main-layout";
import { createStorage, prevDefault } from "../../utils";
import { prevDefault } from "../../utils";
import { CatalogEntityDetails } from "./catalog-entity-details";
import { browseCatalogTab, catalogURL, CatalogViewRouteParam } from "../../../common/routes";
import { CatalogMenu } from "./catalog-menu";
@@ -46,8 +46,10 @@ import { HotbarToggleMenuItem } from "./hotbar-toggle-menu-item";
import { Avatar } from "../avatar";
import { KubeObject } from "../../../common/k8s-api/kube-object";
import { getLabelBadges } from "./helpers";
export const previousActiveTab = createStorage("catalog-previous-active-tab", browseCatalogTab);
import { withInjectables } from "@ogre-tools/injectable-react";
import catalogPreviousActiveTabStorageInjectable
from "./catalog-previous-active-tab-storage/catalog-previous-active-tab-storage.injectable";
import catalogEntityStoreInjectable from "./catalog-entity-store/catalog-entity-store.injectable";
enum sortBy {
name = "name",
@@ -56,26 +58,23 @@ enum sortBy {
status = "status",
}
interface Props extends RouteComponentProps<CatalogViewRouteParam> {
catalogEntityStore?: CatalogEntityStore;
interface Props extends RouteComponentProps<CatalogViewRouteParam> {}
interface Dependencies {
catalogPreviousActiveTabStorage: { set: (value: string ) => void }
catalogEntityStore: CatalogEntityStore
}
@observer
export class Catalog extends React.Component<Props> {
@observable private catalogEntityStore?: CatalogEntityStore;
class NonInjectedCatalog extends React.Component<Props & Dependencies> {
@observable private contextMenu: CatalogEntityContextMenuContext;
@observable activeTab?: string;
constructor(props: Props) {
constructor(props: Props & Dependencies) {
super(props);
makeObservable(this);
this.catalogEntityStore = props.catalogEntityStore;
}
static defaultProps = {
catalogEntityStore: new CatalogEntityStore(),
};
get routeActiveTab(): string {
const { group, kind } = this.props.match.params ?? {};
@@ -92,9 +91,9 @@ export class Catalog extends React.Component<Props> {
navigate: (url: string) => navigate(url),
};
disposeOnUnmount(this, [
this.catalogEntityStore.watch(),
this.props.catalogEntityStore.watch(),
reaction(() => this.routeActiveTab, async (routeTab) => {
previousActiveTab.set(this.routeActiveTab);
this.props.catalogPreviousActiveTabStorage.set(this.routeActiveTab);
try {
await when(() => (routeTab === browseCatalogTab || !!catalogCategoryRegistry.filteredItems.find(i => i.getId() === routeTab)), { timeout: 5_000 }); // we need to wait because extensions might take a while to load
@@ -102,7 +101,7 @@ export class Catalog extends React.Component<Props> {
runInAction(() => {
this.activeTab = routeTab;
this.catalogEntityStore.activeCategory = item;
this.props.catalogEntityStore.activeCategory = item;
});
} catch (error) {
console.error(error);
@@ -113,13 +112,13 @@ export class Catalog extends React.Component<Props> {
// If active category is filtered out, automatically switch to the first category
disposeOnUnmount(this, reaction(() => catalogCategoryRegistry.filteredItems, () => {
if (!catalogCategoryRegistry.filteredItems.find(item => item.getId() === this.catalogEntityStore.activeCategory.getId())) {
if (!catalogCategoryRegistry.filteredItems.find(item => item.getId() === this.props.catalogEntityStore.activeCategory.getId())) {
const item = catalogCategoryRegistry.filteredItems[0];
runInAction(() => {
if (item) {
this.activeTab = item.getId();
this.catalogEntityStore.activeCategory = item;
this.props.catalogEntityStore.activeCategory = item;
}
});
}
@@ -135,10 +134,10 @@ export class Catalog extends React.Component<Props> {
}
onDetails = (entity: CatalogEntity) => {
if (this.catalogEntityStore.selectedItemId) {
this.catalogEntityStore.selectedItemId = null;
if (this.props.catalogEntityStore.selectedItemId) {
this.props.catalogEntityStore.selectedItemId = null;
} else {
this.catalogEntityStore.onRun(entity);
this.props.catalogEntityStore.onRun(entity);
}
};
@@ -189,7 +188,7 @@ export class Catalog extends React.Component<Props> {
return (
<MenuActions onOpen={onOpen}>
<MenuItem key="open-details" onClick={() => this.catalogEntityStore.selectedItemId = entity.getId()}>
<MenuItem key="open-details" onClick={() => this.props.catalogEntityStore.selectedItemId = entity.getId()}>
View Details
</MenuItem>
{
@@ -238,7 +237,7 @@ export class Catalog extends React.Component<Props> {
}
renderList() {
const { activeCategory } = this.catalogEntityStore;
const { activeCategory } = this.props.catalogEntityStore;
const tableId = activeCategory ? `catalog-items-${activeCategory.metadata.name.replace(" ", "")}` : "catalog-items";
if (this.activeTab === undefined) {
@@ -252,7 +251,7 @@ export class Catalog extends React.Component<Props> {
renderHeaderTitle={activeCategory?.metadata.name || "Browse All"}
isSelectable={false}
isConfigurable={true}
store={this.catalogEntityStore}
store={this.props.catalogEntityStore}
sortingCallbacks={{
[sortBy.name]: entity => entity.getName(),
[sortBy.source]: entity => entity.getSource(),
@@ -292,11 +291,11 @@ export class Catalog extends React.Component<Props> {
}
render() {
if (!this.catalogEntityStore) {
if (!this.props.catalogEntityStore) {
return null;
}
const selectedEntity = this.catalogEntityStore.selectedItem;
const selectedEntity = this.props.catalogEntityStore.selectedItem;
return (
<MainLayout sidebar={this.renderNavigation()}>
@@ -307,13 +306,13 @@ export class Catalog extends React.Component<Props> {
selectedEntity
? <CatalogEntityDetails
entity={selectedEntity}
hideDetails={() => this.catalogEntityStore.selectedItemId = null}
onRun={() => this.catalogEntityStore.onRun(selectedEntity)}
hideDetails={() => this.props.catalogEntityStore.selectedItemId = null}
onRun={() => this.props.catalogEntityStore.onRun(selectedEntity)}
/>
: (
<RenderDelay>
<CatalogAddButton
category={this.catalogEntityStore.activeCategory}
category={this.props.catalogEntityStore.activeCategory}
/>
</RenderDelay>
)
@@ -322,3 +321,18 @@ export class Catalog extends React.Component<Props> {
);
}
}
export const Catalog = withInjectables<Dependencies, Props>(
NonInjectedCatalog,
{
getProps: (di, props) => ({
catalogEntityStore: di.inject(catalogEntityStoreInjectable),
catalogPreviousActiveTabStorage: di.inject(
catalogPreviousActiveTabStorageInjectable,
),
...props,
}),
},
);