20424: Process io parameter parsing in single loop to optimize performance
[arvados-workbench2.git] / src / views / process-panel / process-io-card.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React, { ReactElement, memo, useState } from 'react';
6 import { Dispatch } from 'redux';
7 import {
8     StyleRulesCallback,
9     WithStyles,
10     withStyles,
11     Card,
12     CardHeader,
13     IconButton,
14     CardContent,
15     Tooltip,
16     Typography,
17     Tabs,
18     Tab,
19     Table,
20     TableHead,
21     TableBody,
22     TableRow,
23     TableCell,
24     Paper,
25     Grid,
26     Chip,
27     CircularProgress,
28 } from '@material-ui/core';
29 import { ArvadosTheme } from 'common/custom-theme';
30 import {
31     CloseIcon,
32     ImageIcon,
33     InputIcon,
34     ImageOffIcon,
35     OutputIcon,
36     MaximizeIcon,
37     UnMaximizeIcon,
38     InfoIcon
39 } from 'components/icon/icon';
40 import { MPVPanelProps } from 'components/multi-panel-view/multi-panel-view';
41 import {
42     BooleanCommandInputParameter,
43     CommandInputParameter,
44     CWLType,
45     Directory,
46     DirectoryArrayCommandInputParameter,
47     DirectoryCommandInputParameter,
48     EnumCommandInputParameter,
49     FileArrayCommandInputParameter,
50     FileCommandInputParameter,
51     FloatArrayCommandInputParameter,
52     FloatCommandInputParameter,
53     IntArrayCommandInputParameter,
54     IntCommandInputParameter,
55     isArrayOfType,
56     isPrimitiveOfType,
57     StringArrayCommandInputParameter,
58     StringCommandInputParameter,
59 } from "models/workflow";
60 import { CommandOutputParameter } from 'cwlts/mappings/v1.0/CommandOutputParameter';
61 import { File } from 'models/workflow';
62 import { getInlineFileUrl } from 'views-components/context-menu/actions/helpers';
63 import { AuthState } from 'store/auth/auth-reducer';
64 import mime from 'mime';
65 import { DefaultView } from 'components/default-view/default-view';
66 import { getNavUrl } from 'routes/routes';
67 import { Link as RouterLink } from 'react-router-dom';
68 import { Link as MuiLink } from '@material-ui/core';
69 import { InputCollectionMount } from 'store/processes/processes-actions';
70 import { connect } from 'react-redux';
71 import { RootState } from 'store/store';
72 import { ProcessOutputCollectionFiles } from './process-output-collection-files';
73 import { Process } from 'store/processes/process';
74 import { navigateTo } from 'store/navigation/navigation-action';
75 import classNames from 'classnames';
76 import { DefaultCodeSnippet } from 'components/default-code-snippet/default-code-snippet';
77 import { KEEP_URL_REGEX } from 'models/resource';
78
79 type CssRules =
80     | "card"
81     | "content"
82     | "title"
83     | "header"
84     | "avatar"
85     | "iconHeader"
86     | "tableWrapper"
87     | "tableRoot"
88     | "paramValue"
89     | "keepLink"
90     | "collectionLink"
91     | "imagePreview"
92     | "valArray"
93     | "secondaryVal"
94     | "secondaryRow"
95     | "emptyValue"
96     | "noBorderRow"
97     | "symmetricTabs"
98     | "imagePlaceholder"
99     | "rowWithPreview"
100     | "labelColumn";
101
102 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
103     card: {
104         height: '100%'
105     },
106     header: {
107         paddingTop: theme.spacing.unit,
108         paddingBottom: 0,
109     },
110     iconHeader: {
111         fontSize: '1.875rem',
112         color: theme.customs.colors.greyL,
113     },
114     avatar: {
115         alignSelf: 'flex-start',
116         paddingTop: theme.spacing.unit * 0.5
117     },
118     content: {
119         height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
120         padding: theme.spacing.unit * 1.0,
121         paddingTop: 0,
122         '&:last-child': {
123             paddingBottom: theme.spacing.unit * 1,
124         }
125     },
126     title: {
127         overflow: 'hidden',
128         paddingTop: theme.spacing.unit * 0.5,
129         color: theme.customs.colors.greyD,
130         fontSize: '1.875rem'
131     },
132     tableWrapper: {
133         height: 'auto',
134         maxHeight: `calc(100% - ${theme.spacing.unit * 4.5}px)`,
135         overflow: 'auto',
136     },
137     tableRoot: {
138         width: '100%',
139         '& thead th': {
140             verticalAlign: 'bottom',
141             paddingBottom: '10px',
142         },
143         '& td, & th': {
144             paddingRight: '25px',
145         }
146     },
147     paramValue: {
148         display: 'flex',
149         alignItems: 'flex-start',
150         flexDirection: 'column',
151     },
152     keepLink: {
153         color: theme.palette.primary.main,
154         textDecoration: 'none',
155         overflowWrap: 'break-word',
156         cursor: 'pointer',
157     },
158     collectionLink: {
159         margin: '10px',
160         '& a': {
161             color: theme.palette.primary.main,
162             textDecoration: 'none',
163             overflowWrap: 'break-word',
164             cursor: 'pointer',
165         }
166     },
167     imagePreview: {
168         maxHeight: '15em',
169         maxWidth: '15em',
170         marginBottom: theme.spacing.unit,
171     },
172     valArray: {
173         display: 'flex',
174         gap: '10px',
175         flexWrap: 'wrap',
176         '& span': {
177             display: 'inline',
178         }
179     },
180     secondaryVal: {
181         paddingLeft: '20px',
182     },
183     secondaryRow: {
184         height: '29px',
185         verticalAlign: 'top',
186         position: 'relative',
187         top: '-9px',
188     },
189     emptyValue: {
190         color: theme.customs.colors.grey700,
191     },
192     noBorderRow: {
193         '& td': {
194             borderBottom: 'none',
195         }
196     },
197     symmetricTabs: {
198         '& button': {
199             flexBasis: '0',
200         }
201     },
202     imagePlaceholder: {
203         width: '60px',
204         height: '60px',
205         display: 'flex',
206         alignItems: 'center',
207         justifyContent: 'center',
208         backgroundColor: '#cecece',
209         borderRadius: '10px',
210     },
211     rowWithPreview: {
212         verticalAlign: 'bottom',
213     },
214     labelColumn: {
215         minWidth: '120px',
216     },
217 });
218
219 export enum ProcessIOCardType {
220     INPUT = 'Inputs',
221     OUTPUT = 'Outputs',
222 }
223 export interface ProcessIOCardDataProps {
224     process?: Process;
225     label: ProcessIOCardType;
226     params: ProcessIOParameter[] | null;
227     raw: any;
228     mounts?: InputCollectionMount[];
229     outputUuid?: string;
230     showParams?: boolean;
231 }
232
233 export interface ProcessIOCardActionProps {
234     navigateTo: (uuid: string) => void;
235 }
236
237 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
238     navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
239 });
240
241 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
242
243 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
244     ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel,
245         doUnMaximizePanel, panelMaximized, panelName, process, navigateTo, showParams }: ProcessIOCardProps) => {
246         const [mainProcTabState, setMainProcTabState] = useState(0);
247         const [subProcTabState, setSubProcTabState] = useState(0);
248         const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
249             setMainProcTabState(value);
250         }
251         const handleSubProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
252             setSubProcTabState(value);
253         }
254
255         const [showImagePreview, setShowImagePreview] = useState(false);
256
257         const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
258         const mainProcess = !(process && process!.containerRequest.requestingContainerUuid);
259
260         const loading = raw === null || raw === undefined || params === null;
261         const hasRaw = !!(raw && Object.keys(raw).length > 0);
262         const hasParams = !!(params && params.length > 0);
263
264         // Subprocess
265         const hasInputMounts = !!(label === ProcessIOCardType.INPUT && mounts && mounts.length);
266         const hasOutputCollecton = !!(label === ProcessIOCardType.OUTPUT && outputUuid);
267
268         return <Card className={classes.card} data-cy="process-io-card">
269             <CardHeader
270                 className={classes.header}
271                 classes={{
272                     content: classes.title,
273                     avatar: classes.avatar,
274                 }}
275                 avatar={<PanelIcon className={classes.iconHeader} />}
276                 title={
277                     <Typography noWrap variant='h6' color='inherit'>
278                         {label}
279                     </Typography>
280                 }
281                 action={
282                     <div>
283                         {mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
284                             <IconButton data-cy="io-preview-image-toggle" onClick={() => { setShowImagePreview(!showImagePreview) }}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
285                         </Tooltip>}
286                         {doUnMaximizePanel && panelMaximized &&
287                             <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
288                                 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
289                             </Tooltip>}
290                         {doMaximizePanel && !panelMaximized &&
291                             <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
292                                 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
293                             </Tooltip>}
294                         {doHidePanel &&
295                             <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
296                                 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
297                             </Tooltip>}
298                     </div>
299                 } />
300             <CardContent className={classes.content}>
301                 {(mainProcess || showParams) ?
302                     (<>
303                         {/* raw is undefined until params are loaded */}
304                         {loading && <Grid container item alignItems='center' justify='center'>
305                             <CircularProgress />
306                         </Grid>}
307                         {/* Once loaded, either raw or params may still be empty
308                            *   Raw when all params are empty
309                            *   Params when raw is provided by containerRequest properties but workflow mount is absent for preview
310                            */}
311                         {(!loading && (hasRaw || hasParams)) &&
312                             <>
313                                 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
314                                     {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
315                                     {hasParams && <Tab label="Parameters" />}
316                                     {!showParams && <Tab label="JSON" />}
317                                 </Tabs>
318                                 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
319                                     <ProcessIOPreview data={params} showImagePreview={showImagePreview} valueLabel={showParams ? "Default value" : "Value"} />
320                                 </div>}
321                                 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
322                                     <ProcessIORaw data={raw} />
323                                 </div>}
324                             </>}
325                         {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
326                             <DefaultView messages={["No parameters found"]} />
327                         </Grid>}
328                     </>) :
329                     // Subprocess
330                     (<>
331                         {loading && <Grid container item alignItems='center' justify='center'>
332                             <CircularProgress />
333                         </Grid>}
334                         {!loading && (hasInputMounts || hasOutputCollecton || hasRaw) ?
335                             <>
336                                 <Tabs value={subProcTabState} onChange={handleSubProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
337                                     {hasInputMounts && <Tab label="Collections" />}
338                                     {hasOutputCollecton && <Tab label="Collection" />}
339                                     <Tab label="JSON" />
340                                 </Tabs>
341                                 <div className={classes.tableWrapper}>
342                                     {subProcTabState === 0 && hasInputMounts && <ProcessInputMounts mounts={mounts || []} />}
343                                     {subProcTabState === 0 && hasOutputCollecton && <>
344                                         {outputUuid && <Typography className={classes.collectionLink}>
345                                             Output Collection: <MuiLink className={classes.keepLink} onClick={() => { navigateTo(outputUuid || "") }}>
346                                                 {outputUuid}
347                                             </MuiLink></Typography>}
348                                         <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
349                                     </>}
350                                     {(subProcTabState === 1 || (!hasInputMounts && !hasOutputCollecton)) && <div className={classes.tableWrapper}>
351                                         <ProcessIORaw data={raw} />
352                                     </div>}
353                                 </div>
354                             </> :
355                             <Grid container item alignItems='center' justify='center'>
356                                 <DefaultView messages={["No data to display"]} />
357                             </Grid>
358                         }
359                     </>)
360                 }
361             </CardContent>
362         </Card>;
363     }
364 ));
365
366 export type ProcessIOValue = {
367     display: ReactElement<any, any>;
368     imageUrl?: string;
369     collection?: ReactElement<any, any>;
370     secondary?: boolean;
371 }
372
373 export type ProcessIOParameter = {
374     id: string;
375     label: string;
376     value: ProcessIOValue[];
377 }
378
379 interface ProcessIOPreviewDataProps {
380     data: ProcessIOParameter[];
381     showImagePreview: boolean;
382     valueLabel: string;
383 }
384
385 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
386
387 const ProcessIOPreview = memo(withStyles(styles)(
388     ({ classes, data, showImagePreview, valueLabel }: ProcessIOPreviewProps) => {
389         const showLabel = data.some((param: ProcessIOParameter) => param.label);
390         return <Table className={classes.tableRoot} aria-label="Process IO Preview">
391             <TableHead>
392                 <TableRow>
393                     <TableCell>Name</TableCell>
394                     {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
395                     <TableCell>{valueLabel}</TableCell>
396                     <TableCell>Collection</TableCell>
397                 </TableRow>
398             </TableHead>
399             <TableBody>
400                 {data.map((param: ProcessIOParameter) => {
401                     const firstVal = param.value.length > 0 ? param.value[0] : undefined;
402                     const rest = param.value.slice(1);
403                     const mainRowClasses = {
404                         [classes.noBorderRow]: (rest.length > 0),
405                     };
406
407                     return <React.Fragment key={param.id}>
408                         <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
409                             <TableCell>
410                                 {param.id}
411                             </TableCell>
412                             {showLabel && <TableCell >{param.label}</TableCell>}
413                             <TableCell>
414                                 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
415                             </TableCell>
416                             <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
417                                 <Typography className={classes.paramValue}>
418                                     {firstVal?.collection}
419                                 </Typography>
420                             </TableCell>
421                         </TableRow>
422                         {rest.map((val, i) => {
423                             const rowClasses = {
424                                 [classes.noBorderRow]: (i < rest.length - 1),
425                                 [classes.secondaryRow]: val.secondary,
426                             };
427                             return <TableRow className={classNames(rowClasses)} key={i}>
428                                 <TableCell />
429                                 {showLabel && <TableCell />}
430                                 <TableCell>
431                                     <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
432                                 </TableCell>
433                                 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
434                                     <Typography className={classes.paramValue}>
435                                         {val.collection}
436                                     </Typography>
437                                 </TableCell>
438                             </TableRow>
439                         })}
440                     </React.Fragment>;
441                 })}
442             </TableBody>
443         </Table >;
444     }));
445
446 interface ProcessValuePreviewProps {
447     value: ProcessIOValue;
448     showImagePreview: boolean;
449 }
450
451 const ProcessValuePreview = withStyles(styles)(
452     ({ value, showImagePreview, classes }: ProcessValuePreviewProps & WithStyles<CssRules>) =>
453         <Typography className={classes.paramValue}>
454             {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
455             {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
456             <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
457                 {value.display}
458             </span>
459         </Typography>
460 )
461
462 interface ProcessIORawDataProps {
463     data: ProcessIOParameter[];
464 }
465
466 const ProcessIORaw = withStyles(styles)(
467     ({ data }: ProcessIORawDataProps) =>
468         <Paper elevation={0}>
469             <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
470         </Paper>
471 );
472
473 interface ProcessInputMountsDataProps {
474     mounts: InputCollectionMount[];
475 }
476
477 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
478
479 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
480     auth: state.auth,
481 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
482     <Table className={classes.tableRoot} aria-label="Process Input Mounts">
483         <TableHead>
484             <TableRow>
485                 <TableCell>Path</TableCell>
486                 <TableCell>Portable Data Hash</TableCell>
487             </TableRow>
488         </TableHead>
489         <TableBody>
490             {mounts.map(mount => (
491                 <TableRow key={mount.path}>
492                     <TableCell><pre>{mount.path}</pre></TableCell>
493                     <TableCell>
494                         <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
495                     </TableCell>
496                 </TableRow>
497             ))}
498         </TableBody>
499     </Table>
500 )));
501
502 type FileWithSecondaryFiles = {
503     secondaryFiles: File[];
504 }
505
506 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
507     switch (true) {
508         case isPrimitiveOfType(input, CWLType.BOOLEAN):
509             const boolValue = (input as BooleanCommandInputParameter).value;
510             return boolValue !== undefined &&
511                 !(Array.isArray(boolValue) && boolValue.length === 0) ?
512                 [{ display: renderPrimitiveValue(boolValue, false) }] :
513                 [{ display: <EmptyValue /> }];
514
515         case isPrimitiveOfType(input, CWLType.INT):
516         case isPrimitiveOfType(input, CWLType.LONG):
517             const intValue = (input as IntCommandInputParameter).value;
518             return intValue !== undefined &&
519                 // Missing values are empty array
520                 !(Array.isArray(intValue) && intValue.length === 0) ?
521                 [{ display: renderPrimitiveValue(intValue, false) }]
522                 : [{ display: <EmptyValue /> }];
523
524         case isPrimitiveOfType(input, CWLType.FLOAT):
525         case isPrimitiveOfType(input, CWLType.DOUBLE):
526             const floatValue = (input as FloatCommandInputParameter).value;
527             return floatValue !== undefined &&
528                 !(Array.isArray(floatValue) && floatValue.length === 0) ?
529                 [{ display: renderPrimitiveValue(floatValue, false) }] :
530                 [{ display: <EmptyValue /> }];
531
532         case isPrimitiveOfType(input, CWLType.STRING):
533             const stringValue = (input as StringCommandInputParameter).value || undefined;
534             return stringValue !== undefined &&
535                 !(Array.isArray(stringValue) && stringValue.length === 0) ?
536                 [{ display: renderPrimitiveValue(stringValue, false) }] :
537                 [{ display: <EmptyValue /> }];
538
539         case isPrimitiveOfType(input, CWLType.FILE):
540             const mainFile = (input as FileCommandInputParameter).value;
541             // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
542             const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
543             const files = [
544                 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
545                 ...secondaryFiles
546             ];
547             const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
548             return files.length ?
549                 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
550                 [{ display: <EmptyValue /> }];
551
552         case isPrimitiveOfType(input, CWLType.DIRECTORY):
553             const directory = (input as DirectoryCommandInputParameter).value;
554             return directory !== undefined &&
555                 !(Array.isArray(directory) && directory.length === 0) ?
556                 [directoryToProcessIOValue(directory, auth, pdh)] :
557                 [{ display: <EmptyValue /> }];
558
559         case typeof input.type === 'object' &&
560             !(input.type instanceof Array) &&
561             input.type.type === 'enum':
562             const enumValue = (input as EnumCommandInputParameter).value;
563             return enumValue !== undefined && enumValue ?
564                 [{ display: <pre>{enumValue}</pre> }] :
565                 [{ display: <EmptyValue /> }];
566
567         case isArrayOfType(input, CWLType.STRING):
568             const strArray = (input as StringArrayCommandInputParameter).value || [];
569             return strArray.length ?
570                 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
571                 [{ display: <EmptyValue /> }];
572
573         case isArrayOfType(input, CWLType.INT):
574         case isArrayOfType(input, CWLType.LONG):
575             const intArray = (input as IntArrayCommandInputParameter).value || [];
576             return intArray.length ?
577                 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
578                 [{ display: <EmptyValue /> }];
579
580         case isArrayOfType(input, CWLType.FLOAT):
581         case isArrayOfType(input, CWLType.DOUBLE):
582             const floatArray = (input as FloatArrayCommandInputParameter).value || [];
583             return floatArray.length ?
584                 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
585                 [{ display: <EmptyValue /> }];
586
587         case isArrayOfType(input, CWLType.FILE):
588             const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
589             const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
590
591             // Convert each main and secondaryFiles into array of ProcessIOValue preserving ordering
592             let fileArrayValues: ProcessIOValue[] = [];
593             for(let i = 0; i < fileArrayMainFiles.length; i++) {
594                 const secondaryFiles = ((fileArrayMainFiles[i] as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
595                 fileArrayValues.push(
596                     // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
597                     ...(fileArrayMainFiles[i] ? [fileToProcessIOValue(fileArrayMainFiles[i], false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
598                     ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
599                 );
600             }
601
602             return fileArrayValues.length ?
603                 fileArrayValues :
604                 [{ display: <EmptyValue /> }];
605
606         case isArrayOfType(input, CWLType.DIRECTORY):
607             const directories = (input as DirectoryArrayCommandInputParameter).value || [];
608             return directories.length ?
609                 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
610                 [{ display: <EmptyValue /> }];
611
612         default:
613             return [{ display: <UnsupportedValue /> }];
614     }
615 };
616
617 const renderPrimitiveValue = (value: any, asChip: boolean) => {
618     const isObject = typeof value === 'object';
619     if (!isObject) {
620         return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
621     } else {
622         return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
623     }
624 };
625
626 /*
627  * @returns keep url without keep: prefix
628  */
629 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
630     const isKeepUrl = file.location?.startsWith('keep:') || false;
631     const keepUrl = isKeepUrl ?
632         file.location?.replace('keep:', '') :
633         pdh ? `${pdh}/${file.location}` : file.location;
634     return keepUrl || '';
635 };
636
637 interface KeepUrlProps {
638     auth: AuthState;
639     res: File | Directory;
640     pdh?: string;
641 }
642
643 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
644     const keepUrl = getKeepUrl(res, pdh);
645     return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
646 };
647
648 const KeepUrlBase = withStyles(styles)(({ auth, res, pdh, classes }: KeepUrlProps & WithStyles<CssRules>) => {
649     const pdhUrl = getResourcePdhUrl(res, pdh);
650     // Passing a pdh always returns a relative wb2 collection url
651     const pdhWbPath = getNavUrl(pdhUrl, auth);
652     return pdhUrl && pdhWbPath ?
653         <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
654         <></>;
655 });
656
657 const KeepUrlPath = withStyles(styles)(({ auth, res, pdh, classes }: KeepUrlProps & WithStyles<CssRules>) => {
658     const keepUrl = getKeepUrl(res, pdh);
659     const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
660     const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
661
662     const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
663     return keepUrlPathNav ?
664         <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
665         <EmptyValue />;
666 });
667
668 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
669     let keepUrl = getKeepUrl(file, pdh);
670     return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
671 };
672
673 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
674     const keepUrl = getKeepUrl(file, pdh);
675     return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
676 };
677
678 const isFileImage = (basename?: string): boolean => {
679     return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
680 };
681
682 const isFileUrl = (location?: string): boolean => (
683     !!location && !KEEP_URL_REGEX.exec(location) &&
684     (location.startsWith("http://") || location.startsWith("https://"))
685 );
686
687 const normalizeDirectoryLocation = (directory: Directory): Directory => {
688     if (!directory.location) {
689         return directory;
690     }
691     return {
692         ...directory,
693         location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
694     };
695 };
696
697 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
698     if (isExternalValue(directory)) { return { display: <UnsupportedValue /> } }
699
700     const normalizedDirectory = normalizeDirectoryLocation(directory);
701     return {
702         display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh} />,
703         collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh} />,
704     };
705 };
706
707 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
708     if (isExternalValue(file)) { return { display: <UnsupportedValue /> } }
709
710     if (isFileUrl(file.location)) {
711         return {
712             display: <MuiLink href={file.location} target="_blank">{file.location}</MuiLink>,
713             secondary,
714         };
715     }
716
717     const resourcePdh = getResourcePdhUrl(file, pdh);
718     return {
719         display: <KeepUrlPath auth={auth} res={file} pdh={pdh} />,
720         secondary,
721         imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
722         collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh} /> : <></>,
723     }
724 };
725
726 const isExternalValue = (val: any) =>
727     Object.keys(val).includes('$import') ||
728     Object.keys(val).includes('$include')
729
730 export const EmptyValue = withStyles(styles)(
731     ({ classes }: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
732 );
733
734 const UnsupportedValue = withStyles(styles)(
735     ({ classes }: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
736 );
737
738 const UnsupportedValueChip = withStyles(styles)(
739     ({ classes }: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
740 );
741
742 const ImagePlaceholder = withStyles(styles)(
743     ({ classes }: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>
744 );