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