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

switch to filtering only for catalog view

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton 2021-08-26 10:02:29 -04:00 committed by Panu Horsmalahti
parent b85e54f7dc
commit 8711fec4ad
9 changed files with 134 additions and 105 deletions

View File

@ -163,6 +163,8 @@ export function find<T>(src: Iterable<T>, match: (i: T) => any): T | undefined {
* @param reducer A function for producing the next item from an accumilation and the current item * @param reducer A function for producing the next item from an accumilation and the current item
* @param initial The initial value for the iteration * @param initial The initial value for the iteration
*/ */
export function reduce<T, R>(src: Iterable<T>, reducer: (acc: Iterable<R>, cur: T) => Iterable<R>, initial: Iterable<R>): Iterable<R>;
export function reduce<T, R = T>(src: Iterable<T>, reducer: (acc: R, cur: T) => R, initial: R): R { export function reduce<T, R = T>(src: Iterable<T>, reducer: (acc: R, cur: T) => R, initial: R): R {
let acc = initial; let acc = initial;

View File

@ -19,13 +19,12 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
import { Disposers, LensExtension } from "./lens-extension"; import { LensExtension } from "./lens-extension";
import { WindowManager } from "../main/window-manager"; import { WindowManager } from "../main/window-manager";
import { catalogEntityRegistry, EntityFilter } from "../main/catalog"; import { catalogEntityRegistry } from "../main/catalog";
import type { CatalogEntity } from "../common/catalog"; import type { CatalogEntity } from "../common/catalog";
import type { IObservableArray } from "mobx"; import type { IObservableArray } from "mobx";
import type { MenuRegistration } from "./registries"; import type { MenuRegistration } from "./registries";
import type { Disposer } from "../common/utils";
export class LensMainExtension extends LensExtension { export class LensMainExtension extends LensExtension {
appMenus: MenuRegistration[] = []; appMenus: MenuRegistration[] = [];
@ -34,19 +33,6 @@ export class LensMainExtension extends LensExtension {
return WindowManager.getInstance().navigateExtension(this.id, pageId, params, frameId); return WindowManager.getInstance().navigateExtension(this.id, pageId, params, frameId);
} }
/**
* Add a filtering function for the catalog. This will be removed if the extension is disabled.
* @param fn The function which should return a truthy value for those entities which should be kepted
* @returns A function to clean up the filter
*/
addCatalogFilter(fn: EntityFilter): Disposer {
const dispose = catalogEntityRegistry.addCatalogFilter(fn);
this[Disposers].push(dispose);
return dispose;
}
addCatalogSource(id: string, source: IObservableArray<CatalogEntity>) { addCatalogSource(id: string, source: IObservableArray<CatalogEntity>) {
catalogEntityRegistry.addObservableSource(`${this.name}:${id}`, source); catalogEntityRegistry.addObservableSource(`${this.name}:${id}`, source);
} }

View File

@ -21,9 +21,11 @@
import type * as registries from "./registries"; import type * as registries from "./registries";
import type { Cluster } from "../main/cluster"; import type { Cluster } from "../main/cluster";
import { LensExtension } from "./lens-extension"; import { Disposers, LensExtension } from "./lens-extension";
import { getExtensionPageUrl } from "./registries/page-registry"; import { getExtensionPageUrl } from "./registries/page-registry";
import type { CatalogEntity } from "../common/catalog"; import type { CatalogEntity } from "../common/catalog";
import type { Disposer } from "../common/utils";
import { catalogEntityRegistry, EntityFilter } from "../renderer/api/catalog-entity-registry";
export class LensRendererExtension extends LensExtension { export class LensRendererExtension extends LensExtension {
globalPages: registries.PageRegistration[] = []; globalPages: registries.PageRegistration[] = [];
@ -59,4 +61,17 @@ export class LensRendererExtension extends LensExtension {
async isEnabledForCluster(cluster: Cluster): Promise<Boolean> { async isEnabledForCluster(cluster: Cluster): Promise<Boolean> {
return (void cluster) || true; return (void cluster) || true;
} }
/**
* Add a filtering function for the catalog. This will be removed if the extension is disabled.
* @param fn The function which should return a truthy value for those entities which should be kepted
* @returns A function to clean up the filter
*/
addCatalogFilter(fn: EntityFilter): Disposer {
const dispose = catalogEntityRegistry.addCatalogFilter(fn);
this[Disposers].push(dispose);
return dispose;
}
} }

View File

@ -20,7 +20,7 @@
*/ */
import { observable, reaction } from "mobx"; import { observable, reaction } from "mobx";
import { KubernetesCluster, WebLink, WebLinkSpec, WebLinkStatus } from "../../../common/catalog-entities"; import { WebLink, WebLinkSpec, WebLinkStatus } from "../../../common/catalog-entities";
import { catalogCategoryRegistry, CatalogEntity, CatalogEntityMetadata } from "../../../common/catalog"; import { catalogCategoryRegistry, CatalogEntity, CatalogEntityMetadata } from "../../../common/catalog";
import { CatalogEntityRegistry } from "../catalog-entity-registry"; import { CatalogEntityRegistry } from "../catalog-entity-registry";
@ -61,35 +61,6 @@ describe("CatalogEntityRegistry", () => {
phase: "available" phase: "available"
} }
}); });
const entity2 = new WebLink({
metadata: {
uid: "test2",
name: "test-link",
source: "test",
labels: {}
},
spec: {
url: "https://k8slens.dev"
},
status: {
phase: "available"
}
});
const entitykc = new KubernetesCluster({
metadata: {
uid: "test2",
name: "test-link",
source: "test",
labels: {}
},
spec: {
kubeconfigPath: "",
kubeconfigContext: "",
},
status: {
phase: "connected"
}
});
const invalidEntity = new InvalidEntity({ const invalidEntity = new InvalidEntity({
metadata: { metadata: {
uid: "invalid", uid: "invalid",
@ -161,18 +132,5 @@ describe("CatalogEntityRegistry", () => {
registry.addObservableSource("test", source); registry.addObservableSource("test", source);
expect(registry.items.length).toBe(0); expect(registry.items.length).toBe(0);
}); });
it("does not return items that are filtered out", () => {
const source = observable.array([entity, entity2, entitykc]);
registry.addObservableSource("test", source);
expect(registry.items.length).toBe(3);
const d = registry.addCatalogFilter(entity => entity.kind === KubernetesCluster.kind);
expect(registry.items.length).toBe(1);
d();
expect(registry.items.length).toBe(3);
});
}); });
}); });

View File

@ -19,20 +19,12 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
import { once } from "lodash";
import { action, computed, IComputedValue, IObservableArray, makeObservable, observable } from "mobx"; import { action, computed, IComputedValue, IObservableArray, makeObservable, observable } from "mobx";
import { CatalogCategoryRegistry, catalogCategoryRegistry, CatalogEntity, CatalogEntityKindData } from "../../common/catalog"; import { CatalogCategoryRegistry, catalogCategoryRegistry, CatalogEntity, CatalogEntityKindData } from "../../common/catalog";
import { Disposer, iter } from "../../common/utils"; import { iter } from "../../common/utils";
export type EntityFilter = (entity: CatalogEntity) => any;
export class CatalogEntityRegistry { export class CatalogEntityRegistry {
protected sources = observable.map<string, IComputedValue<CatalogEntity[]>>(); protected sources = observable.map<string, IComputedValue<CatalogEntity[]>>();
protected filters = observable.set<EntityFilter>([
entity => this.categoryRegistry.getCategoryForEntity(entity)
], {
deep: false,
});
constructor(private categoryRegistry: CatalogCategoryRegistry) { constructor(private categoryRegistry: CatalogCategoryRegistry) {
makeObservable(this); makeObservable(this);
@ -52,42 +44,24 @@ export class CatalogEntityRegistry {
@computed get items(): CatalogEntity[] { @computed get items(): CatalogEntity[] {
return Array.from( return Array.from(
iter.reduce( iter.filter(
this.filters,
iter.filter,
iter.flatMap(this.sources.values(), source => source.get()), iter.flatMap(this.sources.values(), source => source.get()),
entity => this.categoryRegistry.getCategoryForEntity(entity)
) )
); );
} }
getById<T extends CatalogEntity>(id: string): T | undefined { getById<T extends CatalogEntity>(id: string): T | undefined {
const item = this.items.find((entity) => entity.metadata.uid === id); return this.items.find((entity) => entity.metadata.uid === id) as T | undefined;
if (item) return item as T;
return undefined;
} }
getItemsForApiKind<T extends CatalogEntity>(apiVersion: string, kind: string): T[] { getItemsForApiKind<T extends CatalogEntity>(apiVersion: string, kind: string): T[] {
const items = this.items.filter((item) => item.apiVersion === apiVersion && item.kind === kind); return this.items.filter((item) => item.apiVersion === apiVersion && item.kind === kind) as T[];
return items as T[];
} }
getItemsByEntityClass<T extends CatalogEntity>({ apiVersion, kind }: CatalogEntityKindData): T[] { getItemsByEntityClass<T extends CatalogEntity>({ apiVersion, kind }: CatalogEntityKindData): T[] {
return this.getItemsForApiKind(apiVersion, kind); return this.getItemsForApiKind(apiVersion, kind);
} }
/**
* Add a new filter to the set of item filters
* @param fn The function that should return a truthy value if that entity should be sent currently "active"
* @returns A function to remove that filter
*/
addCatalogFilter(fn: EntityFilter): Disposer {
this.filters.add(fn);
return once(() => void this.filters.delete(fn));
}
} }
export const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry); export const catalogEntityRegistry = new CatalogEntityRegistry(catalogCategoryRegistry);

View File

@ -23,7 +23,8 @@ import { CatalogEntityRegistry } from "../catalog-entity-registry";
import "../../../common/catalog-entities"; import "../../../common/catalog-entities";
import { catalogCategoryRegistry } from "../../../common/catalog/catalog-category-registry"; import { catalogCategoryRegistry } from "../../../common/catalog/catalog-category-registry";
import { CatalogCategory, CatalogEntityData, CatalogEntityKindData } from "../catalog-entity"; import { CatalogCategory, CatalogEntityData, CatalogEntityKindData } from "../catalog-entity";
import { WebLink } from "../../../common/catalog-entities"; import { KubernetesCluster, WebLink } from "../../../common/catalog-entities";
import { observable } from "mobx";
class TestCatalogEntityRegistry extends CatalogEntityRegistry { class TestCatalogEntityRegistry extends CatalogEntityRegistry {
replaceItems(items: Array<CatalogEntityData & CatalogEntityKindData>) { replaceItems(items: Array<CatalogEntityData & CatalogEntityKindData>) {
@ -51,6 +52,49 @@ class FooBarCategory extends CatalogCategory {
} }
}; };
} }
const entity = new WebLink({
metadata: {
uid: "test",
name: "test-link",
source: "test",
labels: {}
},
spec: {
url: "https://k8slens.dev"
},
status: {
phase: "available"
}
});
const entity2 = new WebLink({
metadata: {
uid: "test2",
name: "test-link",
source: "test",
labels: {}
},
spec: {
url: "https://k8slens.dev"
},
status: {
phase: "available"
}
});
const entitykc = new KubernetesCluster({
metadata: {
uid: "test2",
name: "test-link",
source: "test",
labels: {}
},
spec: {
kubeconfigPath: "",
kubeconfigContext: "",
},
status: {
phase: "connected"
}
});
describe("CatalogEntityRegistry", () => { describe("CatalogEntityRegistry", () => {
describe("updateItems", () => { describe("updateItems", () => {
@ -250,4 +294,18 @@ describe("CatalogEntityRegistry", () => {
catalogCategoryRegistry.add(new FooBarCategory()); catalogCategoryRegistry.add(new FooBarCategory());
expect(catalog.items.length).toBe(1); expect(catalog.items.length).toBe(1);
}); });
it("does not return items that are filtered out", () => {
const source = observable.array([entity, entity2, entitykc]);
const catalog = new TestCatalogEntityRegistry(catalogCategoryRegistry);
catalog.replaceItems(source);
expect(catalog.items.length).toBe(3);
const d = catalog.addCatalogFilter(entity => entity.kind === KubernetesCluster.kind);
expect(catalog.items.length).toBe(1);
d();
expect(catalog.items.length).toBe(3);
});
}); });

View File

@ -25,10 +25,17 @@ import { CatalogCategory, CatalogEntity, CatalogEntityData, catalogCategoryRegis
import "../../common/catalog-entities"; import "../../common/catalog-entities";
import type { Cluster } from "../../main/cluster"; import type { Cluster } from "../../main/cluster";
import { ClusterStore } from "../../common/cluster-store"; import { ClusterStore } from "../../common/cluster-store";
import { Disposer, iter } from "../utils";
import { once } from "lodash";
export type EntityFilter = (entity: CatalogEntity) => any;
export class CatalogEntityRegistry { export class CatalogEntityRegistry {
@observable.ref activeEntity: CatalogEntity; @observable.ref activeEntity: CatalogEntity;
protected _entities = observable.map<string, CatalogEntity>([], { deep: true }); protected _entities = observable.map<string, CatalogEntity>([], { deep: true });
protected filters = observable.set<EntityFilter>([], {
deep: false,
});
/** /**
* Buffer for keeping entities that don't yet have CatalogCategory synced * Buffer for keeping entities that don't yet have CatalogCategory synced
@ -95,27 +102,56 @@ export class CatalogEntityRegistry {
return Array.from(this._entities.values()); return Array.from(this._entities.values());
} }
@computed get entities(): Map<string, CatalogEntity> { @computed get filteredItems() {
this.processRawEntities(); return Array.from(
iter.reduce(
this.filters,
iter.filter,
this.items,
)
);
}
return this._entities; @computed get entities(): Map<string, CatalogEntity> {
return new Map(
this.items.map(entity => [entity.getId(), entity])
);
}
@computed get filteredEntities(): Map<string, CatalogEntity> {
return new Map(
this.filteredItems.map(entity => [entity.getId(), entity])
);
} }
getById<T extends CatalogEntity>(id: string) { getById<T extends CatalogEntity>(id: string) {
return this.entities.get(id) as T; return this.entities.get(id) as T;
} }
getItemsForApiKind<T extends CatalogEntity>(apiVersion: string, kind: string): T[] { getItemsForApiKind<T extends CatalogEntity>(apiVersion: string, kind: string, { filtered = false } = {}): T[] {
const items = this.items.filter((item) => item.apiVersion === apiVersion && item.kind === kind); const byApiKind = (item: CatalogEntity) => item.apiVersion === apiVersion && item.kind === kind;
const entities = filtered ? this.filteredItems : this.items;
return items as T[]; return entities.filter(byApiKind) as T[];
} }
getItemsForCategory<T extends CatalogEntity>(category: CatalogCategory): T[] { getItemsForCategory<T extends CatalogEntity>(category: CatalogCategory, { filtered = false } = {}): T[] {
const supportedVersions = category.spec.versions.map((v) => `${category.spec.group}/${v.name}`); const supportedVersions = new Set(category.spec.versions.map((v) => `${category.spec.group}/${v.name}`));
const items = this.items.filter((item) => supportedVersions.includes(item.apiVersion) && item.kind === category.spec.names.kind); const byApiVersionKind = (item: CatalogEntity) => supportedVersions.has(item.apiVersion) && item.kind === category.spec.names.kind;
const entities = filtered ? this.filteredItems : this.items;
return items as T[]; return entities.filter(byApiVersionKind) as T[];
}
/**
* Add a new filter to the set of item filters
* @param fn The function that should return a truthy value if that entity should be sent currently "active"
* @returns A function to remove that filter
*/
addCatalogFilter(fn: EntityFilter): Disposer {
this.filters.add(fn);
return once(() => void this.filters.delete(fn));
} }
} }

View File

@ -129,10 +129,10 @@ export class CatalogEntityStore extends ItemStore<CatalogEntityItem<CatalogEntit
@computed get entities() { @computed get entities() {
if (!this.activeCategory) { if (!this.activeCategory) {
return catalogEntityRegistry.items.map(entity => new CatalogEntityItem(entity)); return catalogEntityRegistry.filteredItems.map(entity => new CatalogEntityItem(entity));
} }
return catalogEntityRegistry.getItemsForCategory(this.activeCategory).map(entity => new CatalogEntityItem(entity)); return catalogEntityRegistry.getItemsForCategory(this.activeCategory, { filtered: true }).map(entity => new CatalogEntityItem(entity));
} }
@computed get selectedItem() { @computed get selectedItem() {

View File

@ -52,7 +52,7 @@ export class HotbarMenu extends React.Component<Props> {
return null; return null;
} }
return item ? catalogEntityRegistry.items.find((entity) => entity.metadata.uid === item.entity.uid) : null; return catalogEntityRegistry.getById(item?.entity.uid) ?? null;
} }
onDragEnd(result: DropResult) { onDragEnd(result: DropResult) {