1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { DataColumn, toggleSortDirection, resetSortDirection } from "../../components/data-table/data-column";
6 import actions, { DataExplorerAction } from "./data-explorer-action";
7 import { DataTableFilterItem } from "../../components/data-table-filters/data-table-filters";
8 import { DataColumns } from "../../components/data-table/data-table";
10 interface DataExplorer {
11 columns: DataColumns<any>;
15 rowsPerPageOptions?: number[];
19 export const initialDataExplorer: DataExplorer = {
24 rowsPerPageOptions: [5, 10, 25, 50],
28 export type DataExplorerState = Record<string, DataExplorer | undefined>;
30 const dataExplorerReducer = (state: DataExplorerState = {}, action: DataExplorerAction) =>
31 actions.match(action, {
32 SET_COLUMNS: ({ id, columns }) =>
33 update(state, id, setColumns(columns)),
35 SET_FILTERS: ({ id, columnName, filters }) =>
36 update(state, id, mapColumns(setFilters(columnName, filters))),
38 SET_ITEMS: ({ id, items }) =>
39 update(state, id, explorer => ({ ...explorer, items })),
41 SET_PAGE: ({ id, page }) =>
42 update(state, id, explorer => ({ ...explorer, page })),
44 SET_ROWS_PER_PAGE: ({ id, rowsPerPage }) =>
45 update(state, id, explorer => ({ ...explorer, rowsPerPage })),
47 TOGGLE_SORT: ({ id, columnName }) =>
48 update(state, id, mapColumns(toggleSort(columnName))),
50 TOGGLE_COLUMN: ({ id, columnName }) =>
51 update(state, id, mapColumns(toggleColumn(columnName))),
56 export default dataExplorerReducer;
58 export const getDataExplorer = (state: DataExplorerState, id: string) =>
59 state[id] || initialDataExplorer;
61 const update = (state: DataExplorerState, id: string, updateFn: (dataExplorer: DataExplorer) => DataExplorer) =>
62 ({ ...state, [id]: updateFn(getDataExplorer(state, id)) });
64 const setColumns = (columns: DataColumns<any>) =>
65 (dataExplorer: DataExplorer) =>
66 ({ ...dataExplorer, columns });
68 const mapColumns = (mapFn: (column: DataColumn<any>) => DataColumn<any>) =>
69 (dataExplorer: DataExplorer) =>
70 ({ ...dataExplorer, columns: dataExplorer.columns.map(mapFn) });
72 const toggleSort = (columnName: string) =>
73 (column: DataColumn<any>) => column.name === columnName
74 ? toggleSortDirection(column)
75 : resetSortDirection(column);
77 const toggleColumn = (columnName: string) =>
78 (column: DataColumn<any>) => column.name === columnName
79 ? { ...column, selected: !column.selected }
82 const setFilters = (columnName: string, filters: DataTableFilterItem[]) =>
83 (column: DataColumn<any>) => column.name === columnName
84 ? { ...column, filters }