Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / store / progress-indicator / progress-indicator-reducer.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { ProgressIndicatorAction, progressIndicatorActions } from "store/progress-indicator/progress-indicator-actions";
6
7 export type ProgressIndicatorState = { id: string, working: boolean }[];
8
9 const initialState: ProgressIndicatorState = [];
10
11 export const progressIndicatorReducer = (state: ProgressIndicatorState = initialState, action: ProgressIndicatorAction) => {
12     const stopWorking = (id: string) => state.filter(p => p.id !== id);
13
14     return progressIndicatorActions.match(action, {
15         START_WORKING: id => startWorking(id, state),
16         STOP_WORKING: id => stopWorking(id),
17         PERSIST_STOP_WORKING: id => state.map(p => ({
18             ...p,
19             working: p.id === id ? false : p.working
20         })),
21         TOGGLE_WORKING: ({ id, working }) => working ? startWorking(id, state) : stopWorking(id),
22         default: () => state,
23     });
24 };
25
26 const startWorking = (id: string, state: ProgressIndicatorState) => {
27     return getProgressIndicator(id)(state)
28         ? state.map(indicator => indicator.id === id
29             ? { ...indicator, working: true }
30             : indicator)
31         : state.concat({ id, working: true });
32 };
33
34 export function isSystemWorking(state: ProgressIndicatorState): boolean {
35     return state.length > 0 && state.reduce((working, p) => working ? true : p.working, false);
36 }
37
38 export const getProgressIndicator = (id: string) =>
39     (state: ProgressIndicatorState) =>
40         state.find(state => state.id === id);