19231: Add smaller page sizes (10 and 20 items) to load faster
[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 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 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         dialog = () =>
216             <Dialog
217                 open={this.state.open}
218                 onClose={this.closeDialog}
219                 fullWidth
220                 maxWidth='md' >
221                 <DialogTitle>Choose files</DialogTitle>
222                 <DialogContent>
223                     <this.dialogContent />
224                 </DialogContent>
225                 <DialogActions>
226                     <Button onClick={this.closeDialog}>Cancel</Button>
227                     <Button
228                         data-cy='ok-button'
229                         variant='contained'
230                         color='primary'
231                         onClick={this.submit}>Ok</Button>
232                 </DialogActions>
233             </Dialog>
234
235         dialogContentStyles: StyleRulesCallback<DialogContentCssRules> = ({ spacing }) => ({
236             root: {
237                 display: 'flex',
238                 flexDirection: 'column',
239                 height: `${spacing.unit * 8}vh`,
240             },
241             tree: {
242                 flex: 3,
243                 overflow: 'auto',
244             },
245             divider: {
246                 margin: `${spacing.unit}px 0`,
247             },
248             chips: {
249                 flex: 1,
250                 overflow: 'auto',
251                 padding: `${spacing.unit}px 0`,
252                 overflowX: 'hidden',
253             },
254         })
255
256         dialogContent = withStyles(this.dialogContentStyles)(
257             ({ classes }: WithStyles<DialogContentCssRules>) =>
258                 <div className={classes.root}>
259                     <div className={classes.tree}>
260                         <ProjectsTreePicker
261                             pickerId={this.props.commandInput.id}
262                             includeCollections
263                             includeFiles
264                             showSelection
265                             options={this.props.options}
266                             toggleItemSelection={this.refreshFiles} />
267                     </div>
268                     <Divider />
269                     <div className={classes.chips}>
270                         <Typography variant='subtitle1'>Selected files ({this.state.files.length}):</Typography>
271                         <Chips
272                             orderable
273                             deletable
274                             values={this.state.files}
275                             onChange={this.setFiles}
276                             getLabel={(file: CollectionFile) => file.name} />
277                     </div>
278                 </div>
279         );
280
281     });
282
283 type DialogContentCssRules = 'root' | 'tree' | 'divider' | 'chips';