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