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