Merge branch '18368-notification-banner' into 19836-new-tooltip-impl
[arvados.git] / src / views / run-process-panel / inputs / file-array-input.tsx
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 {
7     isRequiredInput,
8     FileArrayCommandInputParameter,
9     File,
10     CWLType
11 } from 'models/workflow';
12 import { Field } from 'redux-form';
13 import { ERROR_MESSAGE } from 'validators/require';
14 import { Input, Dialog, DialogTitle, DialogContent, DialogActions, Button, Divider, WithStyles, Typography } from '@material-ui/core';
15 import { GenericInputProps, GenericInput } from './generic-input';
16 import { ProjectsTreePicker } from 'views-components/projects-tree-picker/projects-tree-picker';
17 import { connect, DispatchProp } from 'react-redux';
18 import { initProjectsTreePicker, getSelectedNodes, treePickerActions, getProjectsTreePickerIds } from 'store/tree-picker/tree-picker-actions';
19 import { ProjectsTreePickerItem } from 'store/tree-picker/tree-picker-middleware';
20 import { CollectionFile, CollectionFileType } from 'models/collection-file';
21 import { createSelector, createStructuredSelector } from 'reselect';
22 import { ChipsInput } from 'components/chips-input/chips-input';
23 import { identity, values, noop } from 'lodash';
24 import { InputProps } from '@material-ui/core/Input';
25 import { TreePicker } from 'store/tree-picker/tree-picker';
26 import { RootState } from 'store/store';
27 import { Chips } from 'components/chips/chips';
28 import withStyles, { StyleRulesCallback } from '@material-ui/core/styles/withStyles';
29
30 export interface FileArrayInputProps {
31     input: FileArrayCommandInputParameter;
32     options?: { showOnlyOwned: boolean, showOnlyWritable: boolean };
33 }
34 export const FileArrayInput = ({ input }: FileArrayInputProps) =>
35     <Field
36         name={input.id}
37         commandInput={input}
38         component={FileArrayInputComponent as any}
39         parse={parseFiles}
40         format={formatFiles}
41         validate={validationSelector(input)} />;
42
43 const parseFiles = (files: CollectionFile[] | string) =>
44     typeof files === 'string'
45         ? undefined
46         : files.map(parse);
47
48 const parse = (file: CollectionFile): File => ({
49     class: CWLType.FILE,
50     basename: file.name,
51     location: `keep:${file.id}`,
52     path: file.path,
53 });
54
55 const formatFiles = (files: File[] = []) =>
56     files ? files.map(format) : [];
57
58 const format = (file: File): CollectionFile => ({
59     id: file.location
60         ? file.location.replace('keep:', '')
61         : '',
62     name: file.basename || '',
63     path: file.path || '',
64     size: 0,
65     type: CollectionFileType.FILE,
66     url: '',
67 });
68
69 const validationSelector = createSelector(
70     isRequiredInput,
71     isRequired => isRequired
72         ? [required]
73         : undefined
74 );
75
76 const required = (value?: File[]) =>
77     value && value.length > 0
78         ? undefined
79         : ERROR_MESSAGE;
80 interface FileArrayInputComponentState {
81     open: boolean;
82     files: CollectionFile[];
83 }
84
85 interface FileArrayInputComponentProps {
86     treePickerState: TreePicker;
87 }
88
89 const treePickerSelector = (state: RootState) => state.treePicker;
90
91 const mapStateToProps = createStructuredSelector({
92     treePickerState: treePickerSelector,
93 });
94
95 const FileArrayInputComponent = connect(mapStateToProps)(
96     class FileArrayInputComponent extends React.Component<FileArrayInputComponentProps & GenericInputProps & DispatchProp & {
97         options?: { showOnlyOwned: boolean, showOnlyWritable: boolean };
98     }, FileArrayInputComponentState> {
99         state: FileArrayInputComponentState = {
100             open: false,
101             files: [],
102         };
103
104         fileRefreshTimeout = -1;
105
106         componentDidMount() {
107             this.props.dispatch<any>(
108                 initProjectsTreePicker(this.props.commandInput.id));
109         }
110
111         render() {
112             return <>
113                 <this.input />
114                 <this.dialog />
115             </>;
116         }
117
118         openDialog = () => {
119             this.setFilesFromProps(this.props.input.value);
120             this.setState({ open: true });
121         }
122
123         closeDialog = () => {
124             this.setState({ open: false });
125         }
126
127         submit = () => {
128             this.closeDialog();
129             this.props.input.onChange(this.state.files);
130         }
131
132         setFiles = (files: CollectionFile[]) => {
133
134             const deletedFiles = this.state.files
135                 .reduce((deletedFiles, file) =>
136                     files.some(({ id }) => id === file.id)
137                         ? deletedFiles
138                         : [...deletedFiles, file]
139                     , []);
140
141             this.setState({ files });
142
143             const ids = values(getProjectsTreePickerIds(this.props.commandInput.id));
144             ids.forEach(pickerId => {
145                 this.props.dispatch(
146                     treePickerActions.DESELECT_TREE_PICKER_NODE({
147                         pickerId, id: deletedFiles.map(({ id }) => id),
148                     })
149                 );
150             });
151
152         }
153
154         setFilesFromProps = (files: CollectionFile[]) => {
155
156             const addedFiles = files
157                 .reduce((addedFiles, file) =>
158                     this.state.files.some(({ id }) => id === file.id)
159                         ? addedFiles
160                         : [...addedFiles, file]
161                     , []);
162
163             const ids = values(getProjectsTreePickerIds(this.props.commandInput.id));
164             ids.forEach(pickerId => {
165                 this.props.dispatch(
166                     treePickerActions.SELECT_TREE_PICKER_NODE({
167                         pickerId, id: addedFiles.map(({ id }) => id),
168                     })
169                 );
170             });
171
172             this.setFiles(files);
173         }
174
175         refreshFiles = () => {
176             clearTimeout(this.fileRefreshTimeout);
177             this.fileRefreshTimeout = window.setTimeout(this.setSelectedFiles);
178         }
179
180         setSelectedFiles = () => {
181             const nodes = getSelectedNodes<ProjectsTreePickerItem>(this.props.commandInput.id)(this.props.treePickerState);
182             const initialFiles: CollectionFile[] = [];
183             const files = nodes
184                 .reduce((files, { value }) =>
185                     'type' in value && value.type === CollectionFileType.FILE
186                         ? files.concat(value)
187                         : files, initialFiles);
188
189             this.setFiles(files);
190         }
191         input = () =>
192             <GenericInput
193                 component={this.chipsInput}
194                 {...this.props} />
195
196         chipsInput = () =>
197             <ChipsInput
198                 values={this.props.input.value}
199                 disabled={this.props.commandInput.disabled}
200                 onChange={noop}
201                 createNewValue={identity}
202                 getLabel={(file: CollectionFile) => file.name}
203                 inputComponent={this.textInput} />
204
205         textInput = (props: InputProps) =>
206             <Input
207                 {...props}
208                 error={this.props.meta.touched && !!this.props.meta.error}
209                 readOnly
210                 disabled={this.props.commandInput.disabled}
211                 onClick={!this.props.commandInput.disabled ? this.openDialog : undefined}
212                 onKeyPress={!this.props.commandInput.disabled ? this.openDialog : undefined}
213                 onBlur={this.props.input.onBlur} />
214
215         dialogContentStyles: StyleRulesCallback<DialogContentCssRules> = ({ spacing }) => ({
216             root: {
217                 display: 'flex',
218                 flexDirection: 'column',
219             },
220             pickerWrapper: {
221                 display: 'flex',
222                 flexDirection: 'column',
223                 flexBasis: `${spacing.unit * 8}vh`,
224                 flexShrink: 1,
225                 minHeight: 0,
226             },
227             tree: {
228                 flex: 3,
229                 overflow: 'auto',
230             },
231             divider: {
232                 margin: `${spacing.unit}px 0`,
233             },
234             chips: {
235                 flex: 1,
236                 overflow: 'auto',
237                 padding: `${spacing.unit}px 0`,
238                 overflowX: 'hidden',
239             },
240         })
241
242
243         dialog = withStyles(this.dialogContentStyles)(
244             ({ classes }: WithStyles<DialogContentCssRules>) =>
245                 <Dialog
246                     open={this.state.open}
247                     onClose={this.closeDialog}
248                     fullWidth
249                     maxWidth='md' >
250                     <DialogTitle>Choose files</DialogTitle>
251                     <DialogContent className={classes.root}>
252                         <div className={classes.pickerWrapper}>
253                             <div className={classes.tree}>
254                                 <ProjectsTreePicker
255                                     pickerId={this.props.commandInput.id}
256                                     includeCollections
257                                     includeFiles
258                                     showSelection
259                                     options={this.props.options}
260                                     toggleItemSelection={this.refreshFiles} />
261                             </div>
262                             <Divider />
263                             <div className={classes.chips}>
264                                 <Typography variant='subtitle1'>Selected files ({this.state.files.length}):</Typography>
265                                 <Chips
266                                     orderable
267                                     deletable
268                                     values={this.state.files}
269                                     onChange={this.setFiles}
270                                     getLabel={(file: CollectionFile) => file.name} />
271                             </div>
272                         </div>
273
274                     </DialogContent>
275                     <DialogActions>
276                         <Button onClick={this.closeDialog}>Cancel</Button>
277                         <Button
278                             data-cy='ok-button'
279                             variant='contained'
280                             color='primary'
281                             onClick={this.submit}>Ok</Button>
282                     </DialogActions>
283                 </Dialog>
284         );
285
286     });
287
288 type DialogContentCssRules = 'root' | 'pickerWrapper' | 'tree' | 'divider' | 'chips';