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