Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / store / dialog / with-dialog.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import { connect } from 'react-redux';
7 import { DialogState } from './dialog-reducer';
8 import { Dispatch } from 'redux';
9 import { dialogActions } from './dialog-actions';
10
11 export type WithDialogStateProps<T> = {
12     open: boolean;
13     data: T;
14 };
15
16 export type WithDialogDispatchProps = {
17     closeDialog: () => void;
18 };
19
20 export type WithDialogProps<T> = WithDialogStateProps<T> & WithDialogDispatchProps;
21 export const withDialog =
22     (id: string) =>
23     // TODO: How to make compiler happy with & P instead of & any?
24     // eslint-disable-next-line
25     <T, P>(component: React.ComponentType<WithDialogProps<T> & any>) =>
26         connect(mapStateToProps(id), mapDispatchToProps(id))(component);
27
28 const emptyData = {};
29
30 export const mapStateToProps =
31     (id: string) =>
32     <T>(state: { dialog: DialogState }): WithDialogStateProps<T> => {
33         const dialog = state.dialog[id];
34         return dialog ? dialog : { open: false, data: emptyData };
35     };
36
37 export const mapDispatchToProps =
38     (id: string) =>
39     (dispatch: Dispatch): WithDialogDispatchProps => ({
40         closeDialog: () => {
41             dispatch(dialogActions.CLOSE_DIALOG({ id }));
42         },
43     });