mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Load k8s resources only for selected namespaces (#1918)
* loading k8s resources into stores per selected namespaces -- part 1 Signed-off-by: Roman <ixrock@gmail.com> * loading k8s resources into stores per selected namespaces -- part 2 - fix: generating helm chart id Signed-off-by: Roman <ixrock@gmail.com> * loading k8s resources into stores per selected namespaces -- part 3 Signed-off-by: Roman <ixrock@gmail.com> * fixes Signed-off-by: Roman <ixrock@gmail.com> * fixes / responding to comments Signed-off-by: Roman <ixrock@gmail.com> * chore / small fixes Signed-off-by: Roman <ixrock@gmail.com> * fixes & refactoring Signed-off-by: Roman <ixrock@gmail.com> * make lint happy Signed-off-by: Roman <ixrock@gmail.com> * reset store on loading error Signed-off-by: Roman <ixrock@gmail.com> * added new cluster method: cluster.isAllowedResource Signed-off-by: Roman <ixrock@gmail.com> * fix: loading namespaces optimizations Signed-off-by: Roman <ixrock@gmail.com> * fixes & refactoring Signed-off-by: Roman <ixrock@gmail.com>
This commit is contained in:
1 parent
a92ed46f0d
commit
f8c111ddd8
18 files changed
+465
-360
No files matched your search
@@ -5,7 +5,7 @@ import { HelmRelease, helmReleasesApi, IReleaseCreatePayload, IReleaseUpdatePayl
|
||||
import { ItemStore } from "../../item.store";
|
||||
import { Secret } from "../../api/endpoints";
|
||||
import { secretsStore } from "../+config-secrets/secrets.store";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
import { namespaceStore } from "../+namespaces/namespace.store";
|
||||
|
||||
@autobind()
|
||||
export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
@@ -60,30 +60,23 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
@action
|
||||
async loadAll() {
|
||||
this.isLoading = true;
|
||||
let items;
|
||||
|
||||
try {
|
||||
const { isAdmin, allowedNamespaces } = getHostedCluster();
|
||||
const items = await this.loadItems(namespaceStore.getContextNamespaces());
|
||||
|
||||
items = await this.loadItems(!isAdmin ? allowedNamespaces : null);
|
||||
} finally {
|
||||
if (items) {
|
||||
items = this.sortItems(items);
|
||||
this.items.replace(items);
|
||||
}
|
||||
this.items.replace(this.sortItems(items));
|
||||
this.isLoaded = true;
|
||||
} catch (error) {
|
||||
console.error(`Loading Helm Chart releases has failed: ${error}`);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadItems(namespaces?: string[]) {
|
||||
if (!namespaces) {
|
||||
return helmReleasesApi.list();
|
||||
} else {
|
||||
return Promise
|
||||
.all(namespaces.map(namespace => helmReleasesApi.list(namespace)))
|
||||
.then(items => items.flat());
|
||||
}
|
||||
async loadItems(namespaces: string[]) {
|
||||
return Promise
|
||||
.all(namespaces.map(namespace => helmReleasesApi.list(namespace)))
|
||||
.then(items => items.flat());
|
||||
}
|
||||
|
||||
async create(payload: IReleaseCreatePayload) {
|
||||
|
||||
@@ -1,53 +1,120 @@
|
||||
import { action, comparer, observable, reaction } from "mobx";
|
||||
import { action, comparer, IReactionDisposer, IReactionOptions, observable, reaction, toJS, when } from "mobx";
|
||||
import { autobind, createStorage } from "../../utils";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { Namespace, namespacesApi } from "../../api/endpoints";
|
||||
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
|
||||
import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api";
|
||||
import { createPageParam } from "../../navigation";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { isAllowedResource } from "../../../common/rbac";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
import { clusterStore, getHostedCluster } from "../../../common/cluster-store";
|
||||
|
||||
const storage = createStorage<string[]>("context_namespaces", []);
|
||||
const storage = createStorage<string[]>("context_namespaces");
|
||||
|
||||
export const namespaceUrlParam = createPageParam<string[]>({
|
||||
name: "namespaces",
|
||||
isSystem: true,
|
||||
multiValues: true,
|
||||
get defaultValue() {
|
||||
return storage.get(); // initial namespaces coming from URL or local-storage (default)
|
||||
return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default)
|
||||
}
|
||||
});
|
||||
|
||||
export function getDummyNamespace(name: string) {
|
||||
return new Namespace({
|
||||
kind: Namespace.kind,
|
||||
apiVersion: "v1",
|
||||
metadata: {
|
||||
name,
|
||||
uid: "",
|
||||
resourceVersion: "",
|
||||
selfLink: `/api/v1/namespaces/${name}`
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class NamespaceStore extends KubeObjectStore<Namespace> {
|
||||
api = namespacesApi;
|
||||
contextNs = observable.array<string>();
|
||||
|
||||
@observable contextNs = observable.array<string>();
|
||||
@observable isReady = false;
|
||||
|
||||
whenReady = when(() => this.isReady);
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.init();
|
||||
}
|
||||
|
||||
private init() {
|
||||
this.setContext(this.initNamespaces);
|
||||
private async init() {
|
||||
await clusterStore.whenLoaded;
|
||||
if (!getHostedCluster()) return;
|
||||
await getHostedCluster().whenReady; // wait for cluster-state from main
|
||||
|
||||
return reaction(() => this.contextNs.toJS(), namespaces => {
|
||||
this.setContext(this.initialNamespaces);
|
||||
this.autoLoadAllowedNamespaces();
|
||||
this.autoUpdateUrlAndLocalStorage();
|
||||
|
||||
this.isReady = true;
|
||||
}
|
||||
|
||||
public onContextChange(callback: (contextNamespaces: string[]) => void, opts: IReactionOptions = {}): IReactionDisposer {
|
||||
return reaction(() => this.contextNs.toJS(), callback, {
|
||||
equals: comparer.shallow,
|
||||
...opts,
|
||||
});
|
||||
}
|
||||
|
||||
private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
|
||||
return this.onContextChange(namespaces => {
|
||||
storage.set(namespaces); // save to local-storage
|
||||
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url
|
||||
}, {
|
||||
fireImmediately: true,
|
||||
equals: comparer.identity,
|
||||
});
|
||||
}
|
||||
|
||||
get initNamespaces() {
|
||||
return namespaceUrlParam.get();
|
||||
private autoLoadAllowedNamespaces(): IReactionDisposer {
|
||||
return reaction(() => this.allowedNamespaces, () => this.loadAll(), {
|
||||
fireImmediately: true,
|
||||
equals: comparer.shallow,
|
||||
});
|
||||
}
|
||||
|
||||
getContextParams() {
|
||||
return {
|
||||
namespaces: this.contextNs.toJS(),
|
||||
};
|
||||
get allowedNamespaces(): string[] {
|
||||
return toJS(getHostedCluster().allowedNamespaces);
|
||||
}
|
||||
|
||||
private get initialNamespaces(): string[] {
|
||||
const allowed = new Set(this.allowedNamespaces);
|
||||
const prevSelected = storage.get();
|
||||
|
||||
if (Array.isArray(prevSelected)) {
|
||||
return prevSelected.filter(namespace => allowed.has(namespace));
|
||||
}
|
||||
|
||||
// otherwise select "default" or first allowed namespace
|
||||
if (allowed.has("default")) {
|
||||
return ["default"];
|
||||
} else if (allowed.size) {
|
||||
return [Array.from(allowed)[0]];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
getContextNamespaces(): string[] {
|
||||
const namespaces = this.contextNs.toJS();
|
||||
|
||||
// show all namespaces when nothing selected
|
||||
if (!namespaces.length) {
|
||||
if (this.isLoaded) {
|
||||
// return actual namespaces list since "allowedNamespaces" updating every 30s in cluster and thus might be stale
|
||||
return this.items.map(namespace => namespace.getName());
|
||||
}
|
||||
|
||||
return this.allowedNamespaces;
|
||||
}
|
||||
|
||||
return namespaces;
|
||||
}
|
||||
|
||||
subscribe(apis = [this.api]) {
|
||||
@@ -61,31 +128,18 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
|
||||
return super.subscribe(apis);
|
||||
}
|
||||
|
||||
protected async loadItems(namespaces?: string[]) {
|
||||
if (!isAllowedResource("namespaces")) {
|
||||
if (namespaces) return namespaces.map(this.getDummyNamespace);
|
||||
protected async loadItems(params: KubeObjectStoreLoadingParams) {
|
||||
const { allowedNamespaces } = this;
|
||||
|
||||
return [];
|
||||
let namespaces = await super.loadItems(params);
|
||||
|
||||
namespaces = namespaces.filter(namespace => allowedNamespaces.includes(namespace.getName()));
|
||||
|
||||
if (!namespaces.length && allowedNamespaces.length > 0) {
|
||||
return allowedNamespaces.map(getDummyNamespace);
|
||||
}
|
||||
|
||||
if (namespaces) {
|
||||
return Promise.all(namespaces.map(name => this.api.get({ name })));
|
||||
} else {
|
||||
return super.loadItems();
|
||||
}
|
||||
}
|
||||
|
||||
protected getDummyNamespace(name: string) {
|
||||
return new Namespace({
|
||||
kind: "Namespace",
|
||||
apiVersion: "v1",
|
||||
metadata: {
|
||||
name,
|
||||
uid: "",
|
||||
resourceVersion: "",
|
||||
selfLink: `/api/v1/namespaces/${name}`
|
||||
}
|
||||
});
|
||||
return namespaces;
|
||||
}
|
||||
|
||||
@action
|
||||
@@ -105,12 +159,6 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
|
||||
else this.contextNs.push(namespace);
|
||||
}
|
||||
|
||||
@action
|
||||
reset() {
|
||||
super.reset();
|
||||
this.contextNs.clear();
|
||||
}
|
||||
|
||||
@action
|
||||
async remove(item: Namespace) {
|
||||
await super.remove(item);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import difference from "lodash/difference";
|
||||
import uniqBy from "lodash/uniqBy";
|
||||
import { clusterRoleBindingApi, IRoleBindingSubject, RoleBinding, roleBindingApi } from "../../api/endpoints";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
|
||||
import { autobind } from "../../utils";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
|
||||
@@ -26,15 +26,13 @@ export class RoleBindingsStore extends KubeObjectStore<RoleBinding> {
|
||||
return clusterRoleBindingApi.get(params);
|
||||
}
|
||||
|
||||
protected loadItems(namespaces?: string[]) {
|
||||
if (namespaces) {
|
||||
return Promise.all(
|
||||
namespaces.map(namespace => roleBindingApi.list({ namespace }))
|
||||
).then(items => items.flat());
|
||||
} else {
|
||||
return Promise.all([clusterRoleBindingApi.list(), roleBindingApi.list()])
|
||||
.then(items => items.flat());
|
||||
}
|
||||
protected async loadItems(params: KubeObjectStoreLoadingParams): Promise<RoleBinding[]> {
|
||||
const items = await Promise.all([
|
||||
super.loadItems({ ...params, api: clusterRoleBindingApi }),
|
||||
super.loadItems({ ...params, api: roleBindingApi }),
|
||||
]);
|
||||
|
||||
return items.flat();
|
||||
}
|
||||
|
||||
protected async createItem(params: { name: string; namespace?: string }, data?: Partial<RoleBinding>) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { clusterRoleApi, Role, roleApi } from "../../api/endpoints";
|
||||
import { autobind } from "../../utils";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
|
||||
@autobind()
|
||||
@@ -24,15 +24,13 @@ export class RolesStore extends KubeObjectStore<Role> {
|
||||
return clusterRoleApi.get(params);
|
||||
}
|
||||
|
||||
protected loadItems(namespaces?: string[]): Promise<Role[]> {
|
||||
if (namespaces) {
|
||||
return Promise.all(
|
||||
namespaces.map(namespace => roleApi.list({ namespace }))
|
||||
).then(items => items.flat());
|
||||
} else {
|
||||
return Promise.all([clusterRoleApi.list(), roleApi.list()])
|
||||
.then(items => items.flat());
|
||||
}
|
||||
protected async loadItems(params: KubeObjectStoreLoadingParams): Promise<Role[]> {
|
||||
const items = await Promise.all([
|
||||
super.loadItems({ ...params, api: clusterRoleApi }),
|
||||
super.loadItems({ ...params, api: roleApi }),
|
||||
]);
|
||||
|
||||
return items.flat();
|
||||
}
|
||||
|
||||
protected async createItem(params: { name: string; namespace?: string }, data?: Partial<Role>) {
|
||||
|
||||
@@ -27,7 +27,7 @@ export class OverviewStatuses extends React.Component {
|
||||
@autobind()
|
||||
renderWorkload(resource: KubeResource): React.ReactElement {
|
||||
const store = workloadStores[resource];
|
||||
const items = store.getAllByNs(namespaceStore.contextNs);
|
||||
const items = store.getAllByNs(namespaceStore.getContextNamespaces());
|
||||
|
||||
return (
|
||||
<div className="workload" key={resource}>
|
||||
|
||||
@@ -17,81 +17,65 @@ import { cronJobStore } from "../+workloads-cronjobs/cronjob.store";
|
||||
import { Events } from "../+events";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { isAllowedResource } from "../../../common/rbac";
|
||||
import { namespaceStore } from "../+namespaces/namespace.store";
|
||||
|
||||
interface Props extends RouteComponentProps<IWorkloadsOverviewRouteParams> {
|
||||
}
|
||||
|
||||
@observer
|
||||
export class WorkloadsOverview extends React.Component<Props> {
|
||||
@observable isLoading = false;
|
||||
@observable isUnmounting = false;
|
||||
|
||||
async componentDidMount() {
|
||||
const stores: KubeObjectStore[] = [];
|
||||
const stores: KubeObjectStore[] = [
|
||||
isAllowedResource("pods") && podsStore,
|
||||
isAllowedResource("deployments") && deploymentStore,
|
||||
isAllowedResource("daemonsets") && daemonSetStore,
|
||||
isAllowedResource("statefulsets") && statefulSetStore,
|
||||
isAllowedResource("replicasets") && replicaSetStore,
|
||||
isAllowedResource("jobs") && jobStore,
|
||||
isAllowedResource("cronjobs") && cronJobStore,
|
||||
isAllowedResource("events") && eventStore,
|
||||
].filter(Boolean);
|
||||
|
||||
if (isAllowedResource("pods")) {
|
||||
stores.push(podsStore);
|
||||
}
|
||||
const unsubscribeMap = new Map<KubeObjectStore, () => void>();
|
||||
|
||||
if (isAllowedResource("deployments")) {
|
||||
stores.push(deploymentStore);
|
||||
}
|
||||
const loadStores = async () => {
|
||||
this.isLoading = true;
|
||||
|
||||
if (isAllowedResource("daemonsets")) {
|
||||
stores.push(daemonSetStore);
|
||||
}
|
||||
for (const store of stores) {
|
||||
if (this.isUnmounting) break;
|
||||
|
||||
if (isAllowedResource("statefulsets")) {
|
||||
stores.push(statefulSetStore);
|
||||
}
|
||||
try {
|
||||
await store.loadAll();
|
||||
unsubscribeMap.get(store)?.(); // unsubscribe previous watcher
|
||||
unsubscribeMap.set(store, store.subscribe());
|
||||
} catch (error) {
|
||||
console.error("loading store error", error);
|
||||
}
|
||||
}
|
||||
this.isLoading = false;
|
||||
};
|
||||
|
||||
if (isAllowedResource("replicasets")) {
|
||||
stores.push(replicaSetStore);
|
||||
}
|
||||
namespaceStore.onContextChange(loadStores, {
|
||||
fireImmediately: true,
|
||||
});
|
||||
|
||||
if (isAllowedResource("jobs")) {
|
||||
stores.push(jobStore);
|
||||
}
|
||||
|
||||
if (isAllowedResource("cronjobs")) {
|
||||
stores.push(cronJobStore);
|
||||
}
|
||||
|
||||
if (isAllowedResource("events")) {
|
||||
stores.push(eventStore);
|
||||
}
|
||||
|
||||
const unsubscribeList: Array<() => void> = [];
|
||||
|
||||
for (const store of stores) {
|
||||
await store.loadAll();
|
||||
unsubscribeList.push(store.subscribe());
|
||||
}
|
||||
|
||||
await when(() => this.isUnmounting);
|
||||
unsubscribeList.forEach(dispose => dispose());
|
||||
await when(() => this.isUnmounting && !this.isLoading);
|
||||
unsubscribeMap.forEach(dispose => dispose());
|
||||
unsubscribeMap.clear();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.isUnmounting = true;
|
||||
}
|
||||
|
||||
get contents() {
|
||||
return (
|
||||
<>
|
||||
<OverviewStatuses/>
|
||||
{ isAllowedResource("events") && <Events
|
||||
compact
|
||||
hideFilters
|
||||
className="box grow"
|
||||
/> }
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className="WorkloadsOverview flex column gaps">
|
||||
{this.contents}
|
||||
<OverviewStatuses/>
|
||||
{isAllowedResource("events") && <Events compact hideFilters className="box grow"/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,8 +19,7 @@ import { lookupApiLink } from "../../api/kube-api";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
import { Badge } from "../badge";
|
||||
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
containers = "containers",
|
||||
@@ -77,15 +76,15 @@ export class Pods extends React.Component<Props> {
|
||||
tableId = "workloads_pods"
|
||||
isConfigurable
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (pod: Pod) => pod.getName(),
|
||||
[sortBy.namespace]: (pod: Pod) => pod.getNs(),
|
||||
[sortBy.containers]: (pod: Pod) => pod.getContainers().length,
|
||||
[sortBy.restarts]: (pod: Pod) => pod.getRestartsCount(),
|
||||
[sortBy.owners]: (pod: Pod) => pod.getOwnerRefs().map(ref => ref.kind),
|
||||
[sortBy.qos]: (pod: Pod) => pod.getQosClass(),
|
||||
[sortBy.node]: (pod: Pod) => pod.getNodeName(),
|
||||
[sortBy.age]: (pod: Pod) => pod.metadata.creationTimestamp,
|
||||
[sortBy.status]: (pod: Pod) => pod.getStatusMessage(),
|
||||
[columnId.name]: (pod: Pod) => pod.getName(),
|
||||
[columnId.namespace]: (pod: Pod) => pod.getNs(),
|
||||
[columnId.containers]: (pod: Pod) => pod.getContainers().length,
|
||||
[columnId.restarts]: (pod: Pod) => pod.getRestartsCount(),
|
||||
[columnId.owners]: (pod: Pod) => pod.getOwnerRefs().map(ref => ref.kind),
|
||||
[columnId.qos]: (pod: Pod) => pod.getQosClass(),
|
||||
[columnId.node]: (pod: Pod) => pod.getNodeName(),
|
||||
[columnId.age]: (pod: Pod) => pod.metadata.creationTimestamp,
|
||||
[columnId.status]: (pod: Pod) => pod.getStatusMessage(),
|
||||
}}
|
||||
searchFilters={[
|
||||
(pod: Pod) => pod.getSearchFields(),
|
||||
@@ -95,16 +94,16 @@ export class Pods extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Pods"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning", showWithColumn: "name" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Containers", className: "containers", sortBy: sortBy.containers },
|
||||
{ title: "Restarts", className: "restarts", sortBy: sortBy.restarts },
|
||||
{ title: "Controlled By", className: "owners", sortBy: sortBy.owners },
|
||||
{ title: "Node", className: "node", sortBy: sortBy.node },
|
||||
{ title: "QoS", className: "qos", sortBy: sortBy.qos },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Status", className: "status", sortBy: sortBy.status },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Containers", className: "containers", sortBy: columnId.containers, id: columnId.containers },
|
||||
{ title: "Restarts", className: "restarts", sortBy: columnId.restarts, id: columnId.restarts },
|
||||
{ title: "Controlled By", className: "owners", sortBy: columnId.owners, id: columnId.owners },
|
||||
{ title: "Node", className: "node", sortBy: columnId.node, id: columnId.node },
|
||||
{ title: "QoS", className: "qos", sortBy: columnId.qos, id: columnId.qos },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
|
||||
]}
|
||||
renderTableContents={(pod: Pod) => [
|
||||
<Badge flat key="name" label={pod.getName()} tooltip={pod.getName()} />,
|
||||
|
||||
@@ -36,3 +36,14 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ItemListLayoutVisibilityMenu {
|
||||
.MenuItem {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.Checkbox {
|
||||
width: 100%;
|
||||
padding: var(--spacing);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
import "./item-list-layout.scss";
|
||||
import "./table-menu.scss";
|
||||
import groupBy from "lodash/groupBy";
|
||||
|
||||
import React, { ReactNode } from "react";
|
||||
import { computed, observable, reaction, toJS, when } from "mobx";
|
||||
import { computed, IReactionDisposer, observable, reaction, toJS } from "mobx";
|
||||
import { disposeOnUnmount, observer } from "mobx-react";
|
||||
import { ConfirmDialog, ConfirmDialogParams } from "../confirm-dialog";
|
||||
import { TableSortCallback, Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps } from "../table";
|
||||
import { Table, TableCell, TableCellProps, TableHead, TableProps, TableRow, TableRowProps, TableSortCallback } from "../table";
|
||||
import { autobind, createStorage, cssNames, IClassName, isReactNode, noop, prevDefault, stopPropagation } from "../../utils";
|
||||
import { AddRemoveButtons, AddRemoveButtonsProps } from "../add-remove-buttons";
|
||||
import { NoItems } from "../no-items";
|
||||
@@ -19,11 +18,10 @@ import { PageFiltersList } from "./page-filters-list";
|
||||
import { PageFiltersSelect } from "./page-filters-select";
|
||||
import { NamespaceSelectFilter } from "../+namespaces/namespace-select";
|
||||
import { themeStore } from "../../theme.store";
|
||||
import { MenuActions} from "../menu/menu-actions";
|
||||
import { MenuActions } from "../menu/menu-actions";
|
||||
import { MenuItem } from "../menu";
|
||||
import { Checkbox } from "../checkbox";
|
||||
import { userStore } from "../../../common/user-store";
|
||||
import logger from "../../../main/logger";
|
||||
|
||||
// todo: refactor, split to small re-usable components
|
||||
|
||||
@@ -98,10 +96,11 @@ interface ItemListLayoutUserSettings {
|
||||
@observer
|
||||
export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
static defaultProps = defaultProps as object;
|
||||
@observable hiddenColumnNames = new Set<string>();
|
||||
|
||||
private watchDisposers: IReactionDisposer[] = [];
|
||||
|
||||
@observable isUnmounting = false;
|
||||
|
||||
// default user settings (ui show-hide tweaks mostly)
|
||||
@observable userSettings: ItemListLayoutUserSettings = {
|
||||
showAppliedFilters: false,
|
||||
};
|
||||
@@ -120,31 +119,54 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
const { store, dependentStores, isClusterScoped, tableId } = this.props;
|
||||
const { isClusterScoped, isConfigurable, tableId } = this.props;
|
||||
|
||||
if (this.canBeConfigured) this.hiddenColumnNames = new Set(userStore.preferences?.hiddenTableColumns?.[tableId]);
|
||||
if (isConfigurable && !tableId) {
|
||||
throw new Error("[ItemListLayout]: configurable list require props.tableId to be specified");
|
||||
}
|
||||
|
||||
const stores = [store, ...dependentStores];
|
||||
this.loadStores();
|
||||
|
||||
if (!isClusterScoped) stores.push(namespaceStore);
|
||||
|
||||
try {
|
||||
stores.map(store => store.reset());
|
||||
await Promise.all(stores.map(store => store.loadAll()));
|
||||
const subscriptions = stores.map(store => store.subscribe());
|
||||
|
||||
await when(() => this.isUnmounting);
|
||||
subscriptions.forEach(dispose => dispose()); // unsubscribe all
|
||||
} catch (error) {
|
||||
console.log("catched", error);
|
||||
if (!isClusterScoped) {
|
||||
disposeOnUnmount(this, [
|
||||
namespaceStore.onContextChange(() => this.loadStores())
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
async componentWillUnmount() {
|
||||
this.isUnmounting = true;
|
||||
const { store, isSelectable } = this.props;
|
||||
this.unsubscribeStores();
|
||||
}
|
||||
|
||||
if (isSelectable) store.resetSelection();
|
||||
@computed get stores() {
|
||||
const { store, dependentStores } = this.props;
|
||||
|
||||
return new Set([store, ...dependentStores]);
|
||||
}
|
||||
|
||||
async loadStores() {
|
||||
this.unsubscribeStores(); // reset first
|
||||
|
||||
// load
|
||||
for (const store of this.stores) {
|
||||
if (this.isUnmounting) {
|
||||
this.unsubscribeStores();
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
await store.loadAll();
|
||||
this.watchDisposers.push(store.subscribe());
|
||||
} catch (error) {
|
||||
console.error("loading store error", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsubscribeStores() {
|
||||
this.watchDisposers.forEach(dispose => dispose());
|
||||
this.watchDisposers.length = 0;
|
||||
}
|
||||
|
||||
private filterCallbacks: { [type: string]: ItemsFilter } = {
|
||||
@@ -180,9 +202,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
};
|
||||
|
||||
@computed get isReady() {
|
||||
const { isReady, store } = this.props;
|
||||
|
||||
return typeof isReady == "boolean" ? isReady : store.isLoaded;
|
||||
return this.props.isReady ?? this.props.store.isLoaded;
|
||||
}
|
||||
|
||||
@computed get filters() {
|
||||
@@ -228,42 +248,6 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
return this.applyFilters(filterItems, allItems);
|
||||
}
|
||||
|
||||
updateColumnFilter(checkboxValue: boolean, columnName: string) {
|
||||
if (checkboxValue){
|
||||
this.hiddenColumnNames.delete(columnName);
|
||||
} else {
|
||||
this.hiddenColumnNames.add(columnName);
|
||||
}
|
||||
|
||||
if (this.canBeConfigured) {
|
||||
userStore.preferences.hiddenTableColumns[this.props.tableId] = Array.from(this.hiddenColumnNames);
|
||||
}
|
||||
}
|
||||
|
||||
columnIsVisible(index: number): boolean {
|
||||
const {renderTableHeader} = this.props;
|
||||
|
||||
if (!this.canBeConfigured) return true;
|
||||
|
||||
return !this.hiddenColumnNames.has(renderTableHeader[index].showWithColumn ?? renderTableHeader[index].className);
|
||||
}
|
||||
|
||||
get canBeConfigured(): boolean {
|
||||
const { isConfigurable, tableId, renderTableHeader } = this.props;
|
||||
|
||||
if (!isConfigurable || !tableId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!renderTableHeader?.every(({ className }) => className)) {
|
||||
logger.warning("[ItemObjectList]: cannot configure an object list without all headers being identifiable");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@autobind()
|
||||
getRow(uid: string) {
|
||||
const {
|
||||
@@ -295,20 +279,18 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
/>
|
||||
)}
|
||||
{
|
||||
renderTableContents(item)
|
||||
.map((content, index) => {
|
||||
const cellProps: TableCellProps = isReactNode(content) ? { children: content } : content;
|
||||
renderTableContents(item).map((content, index) => {
|
||||
const cellProps: TableCellProps = isReactNode(content) ? { children: content } : content;
|
||||
const headCell = renderTableHeader?.[index];
|
||||
|
||||
if (copyClassNameFromHeadCells && renderTableHeader) {
|
||||
const headCell = renderTableHeader[index];
|
||||
if (copyClassNameFromHeadCells && headCell) {
|
||||
cellProps.className = cssNames(cellProps.className, headCell.className);
|
||||
}
|
||||
|
||||
if (headCell) {
|
||||
cellProps.className = cssNames(cellProps.className, headCell.className);
|
||||
}
|
||||
}
|
||||
|
||||
return this.columnIsVisible(index) ? <TableCell key={index} {...cellProps} /> : null;
|
||||
})
|
||||
if (!headCell || !this.isHiddenColumn(headCell)) {
|
||||
return <TableCell key={index} {...cellProps} />;
|
||||
}
|
||||
})
|
||||
}
|
||||
{renderItemMenu && (
|
||||
<TableCell className="menu" onClick={stopPropagation}>
|
||||
@@ -347,16 +329,11 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
return;
|
||||
}
|
||||
|
||||
return <PageFiltersList filters={filters} />;
|
||||
return <PageFiltersList filters={filters}/>;
|
||||
}
|
||||
|
||||
renderNoItems() {
|
||||
const { allItems, items, filters } = this;
|
||||
const allItemsCount = allItems.length;
|
||||
const itemsCount = items.length;
|
||||
const isFiltered = filters.length > 0 && allItemsCount > itemsCount;
|
||||
|
||||
if (isFiltered) {
|
||||
if (this.filters.length > 0) {
|
||||
return (
|
||||
<NoItems>
|
||||
No items found.
|
||||
@@ -369,7 +346,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
);
|
||||
}
|
||||
|
||||
return <NoItems />;
|
||||
return <NoItems/>;
|
||||
}
|
||||
|
||||
renderHeaderContent(placeholders: IHeaderPlaceholders): ReactNode {
|
||||
@@ -413,12 +390,12 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
title: <h5 className="title">{title}</h5>,
|
||||
info: this.renderInfo(),
|
||||
filters: <>
|
||||
{!isClusterScoped && <NamespaceSelectFilter />}
|
||||
{!isClusterScoped && <NamespaceSelectFilter/>}
|
||||
<PageFiltersSelect allowEmpty disableFilters={{
|
||||
[FilterType.NAMESPACE]: true, // namespace-select used instead
|
||||
}} />
|
||||
}}/>
|
||||
</>,
|
||||
search: <SearchInputUrl />,
|
||||
search: <SearchInputUrl/>,
|
||||
};
|
||||
let header = this.renderHeaderContent(placeholders);
|
||||
|
||||
@@ -442,10 +419,40 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
);
|
||||
}
|
||||
|
||||
renderTableHeader() {
|
||||
const { renderTableHeader, isSelectable, isConfigurable, store } = this.props;
|
||||
|
||||
if (!renderTableHeader) {
|
||||
return;
|
||||
}
|
||||
|
||||
return (
|
||||
<TableHead showTopLine nowrap>
|
||||
{isSelectable && (
|
||||
<TableCell
|
||||
checkbox
|
||||
isChecked={store.isSelectedAll(this.items)}
|
||||
onClick={prevDefault(() => store.toggleSelectionAll(this.items))}
|
||||
/>
|
||||
)}
|
||||
{renderTableHeader.map((cellProps, index) => {
|
||||
if (!this.isHiddenColumn(cellProps)) {
|
||||
return <TableCell key={cellProps.id ?? index} {...cellProps} />;
|
||||
}
|
||||
})}
|
||||
{isConfigurable && (
|
||||
<TableCell className="menu">
|
||||
{this.renderColumnVisibilityMenu()}
|
||||
</TableCell>
|
||||
)}
|
||||
</TableHead>
|
||||
);
|
||||
}
|
||||
|
||||
renderList() {
|
||||
const {
|
||||
isSelectable, tableProps = {}, renderTableHeader, renderItemMenu,
|
||||
store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks, detailsItem
|
||||
store, hasDetailsView, addRemoveButtons = {}, virtual, sortingCallbacks, detailsItem,
|
||||
tableProps = {},
|
||||
} = this.props;
|
||||
const { isReady, removeItemsDialog, items } = this;
|
||||
const { selectedItems } = store;
|
||||
@@ -454,7 +461,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
return (
|
||||
<div className="items box grow flex column">
|
||||
{!isReady && (
|
||||
<Spinner center />
|
||||
<Spinner center/>
|
||||
)}
|
||||
{isReady && (
|
||||
<Table
|
||||
@@ -470,23 +477,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
className: cssNames("box grow", tableProps.className, themeStore.activeTheme.type),
|
||||
})}
|
||||
>
|
||||
{renderTableHeader && (
|
||||
<TableHead showTopLine nowrap>
|
||||
{isSelectable && (
|
||||
<TableCell
|
||||
checkbox
|
||||
isChecked={store.isSelectedAll(items)}
|
||||
onClick={prevDefault(() => store.toggleSelectionAll(items))}
|
||||
/>
|
||||
)}
|
||||
{renderTableHeader.map((cellProps, index) => this.columnIsVisible(index) ? <TableCell key={index} {...cellProps} /> : null)}
|
||||
{ renderItemMenu &&
|
||||
<TableCell className="menu" >
|
||||
{this.canBeConfigured && this.renderColumnMenu()}
|
||||
</TableCell>
|
||||
}
|
||||
</TableHead>
|
||||
)}
|
||||
{this.renderTableHeader()}
|
||||
{
|
||||
!virtual && items.map(item => this.getRow(item.getId()))
|
||||
}
|
||||
@@ -502,24 +493,47 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
|
||||
);
|
||||
}
|
||||
|
||||
renderColumnMenu() {
|
||||
const { renderTableHeader} = this.props;
|
||||
@computed get hiddenColumns() {
|
||||
return userStore.getHiddenTableColumns(this.props.tableId);
|
||||
}
|
||||
|
||||
isHiddenColumn({ id: columnId, showWithColumn }: TableCellProps): boolean {
|
||||
if (!this.props.isConfigurable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.hiddenColumns.has(columnId) || (
|
||||
showWithColumn && this.hiddenColumns.has(showWithColumn)
|
||||
);
|
||||
}
|
||||
|
||||
updateColumnVisibility({ id: columnId }: TableCellProps, isVisible: boolean) {
|
||||
const hiddenColumns = new Set(this.hiddenColumns);
|
||||
|
||||
if (!isVisible) {
|
||||
hiddenColumns.add(columnId);
|
||||
} else {
|
||||
hiddenColumns.delete(columnId);
|
||||
}
|
||||
|
||||
userStore.setHiddenTableColumns(this.props.tableId, hiddenColumns);
|
||||
}
|
||||
|
||||
renderColumnVisibilityMenu() {
|
||||
const { renderTableHeader } = this.props;
|
||||
|
||||
return (
|
||||
<MenuActions
|
||||
toolbar = {false}
|
||||
autoCloseOnSelect = {false}
|
||||
className={cssNames("KubeObjectMenu")}
|
||||
>
|
||||
<MenuActions className="ItemListLayoutVisibilityMenu" toolbar={false} autoCloseOnSelect={false}>
|
||||
{renderTableHeader.map((cellProps, index) => (
|
||||
!cellProps.showWithColumn &&
|
||||
!cellProps.showWithColumn && (
|
||||
<MenuItem key={index} className="input">
|
||||
<Checkbox label = {cellProps.title ?? `<${cellProps.className}>`}
|
||||
className = "MenuCheckbox"
|
||||
value ={!this.hiddenColumnNames.has(cellProps.className)}
|
||||
onChange = {(v) => this.updateColumnFilter(v, cellProps.className)}
|
||||
<Checkbox
|
||||
label={cellProps.title ?? `<${cellProps.className}>`}
|
||||
value={!this.isHiddenColumn(cellProps)}
|
||||
onChange={isVisible => this.updateColumnVisibility(cellProps, isVisible)}
|
||||
/>
|
||||
</MenuItem>
|
||||
)
|
||||
))}
|
||||
</MenuActions>
|
||||
);
|
||||
|
||||
@@ -34,14 +34,14 @@ export class PageFiltersStore {
|
||||
namespaceStore.setContext(filteredNs);
|
||||
}
|
||||
}),
|
||||
reaction(() => namespaceStore.contextNs.toJS(), contextNs => {
|
||||
namespaceStore.onContextChange(namespaces => {
|
||||
const filteredNs = this.getValues(FilterType.NAMESPACE);
|
||||
const isChanged = contextNs.length !== filteredNs.length;
|
||||
const isChanged = namespaces.length !== filteredNs.length;
|
||||
|
||||
if (isChanged) {
|
||||
this.filters.replace([
|
||||
...this.filters.filter(({ type }) => type !== FilterType.NAMESPACE),
|
||||
...contextNs.map(ns => ({ type: FilterType.NAMESPACE, value: ns })),
|
||||
...namespaces.map(ns => ({ type: FilterType.NAMESPACE, value: ns })),
|
||||
]);
|
||||
}
|
||||
}, {
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
.MenuCheckbox {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
@@ -9,13 +9,14 @@ import { Checkbox } from "../checkbox";
|
||||
export type TableCellElem = React.ReactElement<TableCellProps>;
|
||||
|
||||
export interface TableCellProps extends React.DOMAttributes<HTMLDivElement> {
|
||||
id?: string; // used for configuration visibility of columns
|
||||
className?: string;
|
||||
title?: ReactNode;
|
||||
checkbox?: boolean; // render cell with a checkbox
|
||||
isChecked?: boolean; // mark checkbox as checked or not
|
||||
renderBoolean?: boolean; // show "true" or "false" for all of the children elements are "typeof boolean"
|
||||
sortBy?: TableSortBy; // column name, must be same as key in sortable object <Table sortable={}/>
|
||||
showWithColumn?: string // className of another column, if it is not empty the current column is not shown in the filter menu, visibility of this one is the same as a specified column, applicable to headers only
|
||||
showWithColumn?: string // id of the column which follow same visibility rules
|
||||
_sorting?: Partial<TableSortParams>; // <Table> sorting state, don't use this prop outside (!)
|
||||
_sort?(sortBy: TableSortBy): void; // <Table> sort function, don't use this prop outside (!)
|
||||
_nowrap?: boolean; // indicator, might come from parent <TableHead>, don't use this prop outside (!)
|
||||
@@ -73,7 +74,7 @@ export class TableCell extends React.Component<TableCellProps> {
|
||||
const content = displayBooleans(displayBoolean, title || children);
|
||||
|
||||
return (
|
||||
<div {...cellProps} id={className} className={classNames} onClick={this.onClick}>
|
||||
<div {...cellProps} className={classNames} onClick={this.onClick}>
|
||||
{this.renderCheckbox()}
|
||||
{_nowrap ? <div className="content">{content}</div> : content}
|
||||
{this.renderSortIcon()}
|
||||
|
||||
Reference in new issue
Block a user