1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from "react";
6 import { Tree, toggleNodeSelection, getNode, initTreeNode, getNodeChildrenIds, selectNode, deselectNodes } from '~/models/tree';
7 import { Tree as TreeComponent, TreeItem, TreeItemStatus } from '~/components/tree/tree';
8 import { noop, map } from "lodash/fp";
9 import { toggleNodeCollapse } from '~/models/tree';
10 import { countNodes, countChildren } from '~/models/tree';
12 export interface DataTableFilterItem {
16 export type DataTableFilters = Tree<DataTableFilterItem>;
18 export interface DataTableFilterProps {
19 filters: DataTableFilters;
20 onChange?: (filters: DataTableFilters) => void;
23 * When set to true, only one filter can be selected at a time.
25 mutuallyExclusive?: boolean;
28 export class DataTableFiltersTree extends React.Component<DataTableFilterProps> {
31 const { filters } = this.props;
32 const hasSubfilters = countNodes(filters) !== countChildren('')(filters);
34 levelIndentation={hasSubfilters ? 20 : 0}
36 items={filtersToTree(filters)}
39 useRadioButtons={this.props.mutuallyExclusive}
43 this.props.mutuallyExclusive
44 ? this.toggleRadioButtonFilter
47 toggleItemOpen={this.toggleOpen}
52 * Handler for when a tree item is toggled via a radio button.
53 * Ensures mutual exclusivity among filter tree items.
55 toggleRadioButtonFilter = (_: any, item: TreeItem<DataTableFilterItem>) => {
56 const { onChange = noop } = this.props;
58 // If the filter is already selected, do nothing.
59 if (item.selected) { return; }
61 // Otherwise select this node and deselect the others
62 const filters = selectNode(item.id)(this.props.filters);
63 const toDeselect = Object.keys(this.props.filters).filter((id) => (id !== item.id));
64 onChange(deselectNodes(toDeselect)(filters));
67 toggleFilter = (_: React.MouseEvent, item: TreeItem<DataTableFilterItem>) => {
68 const { onChange = noop } = this.props;
69 onChange(toggleNodeSelection(item.id)(this.props.filters));
72 toggleOpen = (_: React.MouseEvent, item: TreeItem<DataTableFilterItem>) => {
73 const { onChange = noop } = this.props;
74 onChange(toggleNodeCollapse(item.id)(this.props.filters));
78 const renderItem = (item: TreeItem<DataTableFilterItem>) =>
79 <span>{item.data.name}</span>;
81 const filterToTreeItem = (filters: DataTableFilters) =>
82 (id: string): TreeItem<any> => {
83 const node = getNode(id)(filters) || initTreeNode({ id: '', value: 'InvalidNode' });
84 const items = getNodeChildrenIds(node.id)(filters)
85 .map(filterToTreeItem(filters));
91 items: items.length > 0 ? items : undefined,
93 selected: node.selected,
94 status: TreeItemStatus.LOADED,
98 const filtersToTree = (filters: DataTableFilters): TreeItem<DataTableFilterItem>[] =>
99 map(filterToTreeItem(filters), getNodeChildrenIds('')(filters));