173e6b5e91be64e577c631a216b94b63f25223f7
[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, 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     options?: { showOnlyOwned: boolean, showOnlyWritable: boolean };
33 }
34 export const FileArrayInput = ({ input }: FileArrayInputProps) =>
35     <Field
36         name={input.id}
37         commandInput={input}
38         component={FileArrayInputComponent}
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.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
176         refreshFiles = () => {
177             clearTimeout(this.fileRefreshTimeout);
178             this.fileRefreshTimeout = setTimeout(this.setSelectedFiles);
179         }
180
181         setSelectedFiles = () => {
182             const nodes = getSelectedNodes<ProjectsTreePickerItem>(this.props.commandInput.id)(this.props.treePickerState);
183             const initialFiles: CollectionFile[] = [];
184             const files = nodes
185                 .reduce((files, { value }) =>
186                     'type' in value && value.type === CollectionFileType.FILE
187                         ? files.concat(value)
188                         : files, initialFiles);
189
190             this.setFiles(files);
191         }
192         input = () =>
193             <GenericInput
194                 component={this.chipsInput}
195                 {...this.props} />
196
197         chipsInput = () =>
198             <ChipsInput
199                 values={this.props.input.value}
200                 disabled={this.props.commandInput.disabled}
201                 onChange={noop}
202                 createNewValue={identity}
203                 getLabel={(file: CollectionFile) => file.name}
204                 inputComponent={this.textInput} />
205
206         textInput = (props: InputProps) =>
207             <Input
208                 {...props}
209                 error={this.props.meta.touched && !!this.props.meta.error}
210                 readOnly
211                 disabled={this.props.commandInput.disabled}
212                 onClick={!this.props.commandInput.disabled ? this.openDialog : undefined}
213                 onKeyPress={!this.props.commandInput.disabled ? this.openDialog : undefined}
214                 onBlur={this.props.input.onBlur} />
215
216         dialog = () =>
217             <Dialog
218                 open={this.state.open}
219                 onClose={this.closeDialog}
220                 fullWidth
221                 maxWidth='md' >
222                 <DialogTitle>Choose files</DialogTitle>
223                 <DialogContent>
224                     <this.dialogContent />
225                 </DialogContent>
226                 <DialogActions>
227                     <Button onClick={this.closeDialog}>Cancel</Button>
228                     <Button
229                         data-cy='ok-button'
230                         variant='contained'
231                         color='primary'
232                         onClick={this.submit}>Ok</Button>
233                 </DialogActions>
234             </Dialog>
235
236         dialogContentStyles: StyleRulesCallback<DialogContentCssRules> = ({ spacing }) => ({
237             root: {
238                 display: 'flex',
239                 flexDirection: 'column',
240                 height: `${spacing.unit * 8}vh`,
241             },
242             tree: {
243                 flex: 3,
244                 overflow: 'auto',
245             },
246             divider: {
247                 margin: `${spacing.unit}px 0`,
248             },
249             chips: {
250                 flex: 1,
251                 overflow: 'auto',
252                 padding: `${spacing.unit}px 0`,
253                 overflowX: 'hidden',
254             },
255         })
256
257         dialogContent = withStyles(this.dialogContentStyles)(
258             ({ classes }: WithStyles<DialogContentCssRules>) =>
259                 <div className={classes.root}>
260                     <div className={classes.tree}>
261                         <ProjectsTreePicker
262                             pickerId={this.props.commandInput.id}
263                             includeCollections
264                             includeFiles
265                             showSelection
266                             options={this.props.options}
267                             toggleItemSelection={this.refreshFiles} />
268                     </div>
269                     <Divider />
270                     <div className={classes.chips}>
271                         <Typography variant='subtitle1'>Selected files ({this.state.files.length}):</Typography>
272                         <Chips
273                             orderable
274                             deletable
275                             values={this.state.files}
276                             onChange={this.setFiles}
277                             getLabel={(file: CollectionFile) => file.name} />
278                     </div>
279                 </div>
280         );
281
282     });
283
284 type DialogContentCssRules = 'root' | 'tree' | 'divider' | 'chips';
285
286
287