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