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