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