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