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