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