Merge branch '21666-provision-test-improvement'
[arvados.git] / services / workbench2 / src / store / multiselect / multiselect-reducer.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { multiselectActionConstants } from "./multiselect-actions";
6 import { TCheckedList } from "components/data-table/data-table";
7
8 type MultiselectToolbarState = {
9     isVisible: boolean;
10     checkedList: TCheckedList;
11     selectedUuid: string;
12     disabledButtons: string[];
13 };
14
15 const multiselectToolbarInitialState = {
16     isVisible: false,
17     checkedList: {},
18     selectedUuid: '',
19     disabledButtons: []
20 };
21
22 const uncheckAllOthers = (inputList: TCheckedList, uuid: string) => {
23     const checkedlist = {...inputList}
24     for (const key in checkedlist) {
25         if (key !== uuid) checkedlist[key] = false;
26     }
27     return checkedlist;
28 };
29
30 const toggleOneCheck = (inputList: TCheckedList, uuid: string)=>{
31     const checkedlist = { ...inputList };
32     const isOnlyOneSelected = Object.values(checkedlist).filter(x => x === true).length === 1;
33     return { ...inputList, [uuid]: (checkedlist[uuid] && checkedlist[uuid] === true) && isOnlyOneSelected ? false : true };
34 }
35
36 const { TOGGLE_VISIBLITY, SET_CHECKEDLIST, SELECT_ONE, DESELECT_ONE, DESELECT_ALL_OTHERS, TOGGLE_ONE, SET_SELECTED_UUID, ADD_DISABLED, REMOVE_DISABLED } = multiselectActionConstants;
37
38 export const multiselectReducer = (state: MultiselectToolbarState = multiselectToolbarInitialState, action) => {
39     switch (action.type) {
40         case TOGGLE_VISIBLITY:
41             return { ...state, isVisible: action.payload };
42         case SET_CHECKEDLIST:
43             return { ...state, checkedList: action.payload };
44         case SELECT_ONE:
45             return { ...state, checkedList: { ...state.checkedList, [action.payload]: true } };
46         case DESELECT_ONE:
47             return { ...state, checkedList: { ...state.checkedList, [action.payload]: false } };
48         case DESELECT_ALL_OTHERS:
49             return { ...state, checkedList: uncheckAllOthers(state.checkedList, action.payload) };
50         case TOGGLE_ONE:
51             return { ...state, checkedList: toggleOneCheck(state.checkedList, action.payload) };
52         case SET_SELECTED_UUID:
53             return {...state, selectedUuid: action.payload || ''}
54         case ADD_DISABLED:
55             return { ...state, disabledButtons: [...state.disabledButtons, action.payload]}
56         case REMOVE_DISABLED:
57             return { ...state, disabledButtons: state.disabledButtons.filter((button) => button !== action.payload) };
58         default:
59             return state;
60     }
61 };