1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React, { ReactElement, useState } from 'react';
6 import { Dispatch } from 'redux';
27 } from '@material-ui/core';
28 import { ArvadosTheme } from 'common/custom-theme';
29 import { CloseIcon, ImageIcon, InfoIcon, InputIcon, ImageOffIcon, OutputIcon } from 'components/icon/icon';
30 import { MPVPanelProps } from 'components/multi-panel-view/multi-panel-view';
32 BooleanCommandInputParameter,
33 CommandInputParameter,
36 DirectoryArrayCommandInputParameter,
37 DirectoryCommandInputParameter,
38 EnumCommandInputParameter,
39 FileArrayCommandInputParameter,
40 FileCommandInputParameter,
41 FloatArrayCommandInputParameter,
42 FloatCommandInputParameter,
43 IntArrayCommandInputParameter,
44 IntCommandInputParameter,
47 StringArrayCommandInputParameter,
48 StringCommandInputParameter,
49 } from "models/workflow";
50 import { CommandOutputParameter } from 'cwlts/mappings/v1.0/CommandOutputParameter';
51 import { File } from 'models/workflow';
52 import { getInlineFileUrl } from 'views-components/context-menu/actions/helpers';
53 import { AuthState } from 'store/auth/auth-reducer';
54 import mime from 'mime';
55 import { DefaultView } from 'components/default-view/default-view';
56 import { getNavUrl } from 'routes/routes';
57 import { Link as RouterLink } from 'react-router-dom';
58 import { Link as MuiLink } from '@material-ui/core';
59 import { InputCollectionMount } from 'store/processes/processes-actions';
60 import { connect } from 'react-redux';
61 import { RootState } from 'store/store';
62 import { ProcessOutputCollectionFiles } from './process-output-collection-files';
63 import { Process } from 'store/processes/process';
64 import { navigateTo } from 'store/navigation/navigation-action';
66 type CssRules = 'card' | 'content' | 'title' | 'header' | 'avatar' | 'iconHeader' | 'tableWrapper' | 'tableRoot' | 'paramValue' | 'keepLink' | 'collectionLink' | 'imagePreview' | 'valArray' | 'emptyValue' | 'halfRow' | 'symmetricTabs' | 'imagePlaceholder' | 'rowWithPreview';
68 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
73 paddingTop: theme.spacing.unit,
74 paddingBottom: theme.spacing.unit,
78 color: theme.customs.colors.green700,
81 alignSelf: 'flex-start',
82 paddingTop: theme.spacing.unit * 0.5
85 padding: theme.spacing.unit * 1.0,
86 paddingTop: theme.spacing.unit * 0.5,
88 paddingBottom: theme.spacing.unit * 1,
93 paddingTop: theme.spacing.unit * 0.5
101 verticalAlign: 'bottom',
102 paddingBottom: '10px',
107 alignItems: 'flex-start',
108 flexDirection: 'column',
111 color: theme.palette.primary.main,
112 textDecoration: 'none',
113 overflowWrap: 'break-word',
119 color: theme.palette.primary.main,
120 textDecoration: 'none',
121 overflowWrap: 'break-word',
128 marginBottom: theme.spacing.unit,
139 color: theme.customs.colors.grey500,
143 borderBottom: 'none',
155 alignItems: 'center',
156 justifyContent: 'center',
157 backgroundColor: '#cecece',
158 borderRadius: '10px',
161 verticalAlign: 'bottom',
165 export enum ProcessIOCardType {
169 export interface ProcessIOCardDataProps {
171 label: ProcessIOCardType;
172 params: ProcessIOParameter[];
174 mounts?: InputCollectionMount[];
178 export interface ProcessIOCardActionProps {
179 navigateTo: (uuid: string) => void;
182 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
183 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
186 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
188 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
189 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, panelName, process, navigateTo }: ProcessIOCardProps) => {
190 const [mainProcTabState, setMainProcTabState] = useState(0);
191 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
192 setMainProcTabState(value);
195 const [showImagePreview, setShowImagePreview] = useState(false);
197 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
198 const mainProcess = !process.containerRequest.requestingContainerUuid;
200 return <Card className={classes.card} data-cy="process-io-card">
202 className={classes.header}
204 content: classes.title,
205 avatar: classes.avatar,
207 avatar={<PanelIcon className={classes.iconHeader} />}
209 <Typography noWrap variant='h6' color='inherit'>
215 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
216 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
219 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
220 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
224 <CardContent className={classes.content}>
230 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
231 <Tab label="Parameters" />
234 {mainProcTabState === 0 && <div className={classes.tableWrapper}>
235 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
237 {mainProcTabState === 1 && <div className={classes.tableWrapper}>
238 <ProcessIORaw data={raw || params} />
241 <Grid container item alignItems='center' justify='center'>
242 <DefaultView messages={["No parameters found"]} />
247 {((mounts && mounts.length) || outputUuid) ?
249 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
250 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
251 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
253 <div className={classes.tableWrapper}>
254 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
255 {label === ProcessIOCardType.OUTPUT && <>
256 {outputUuid && <Typography className={classes.collectionLink}>
257 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
259 </MuiLink></Typography>}
260 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
264 <Grid container item alignItems='center' justify='center'>
265 <DefaultView messages={["No collection(s) found"]} />
276 export type ProcessIOValue = {
277 display: ReactElement<any, any>;
279 collection?: ReactElement<any, any>;
282 export type ProcessIOParameter = {
285 value: ProcessIOValue[];
288 interface ProcessIOPreviewDataProps {
289 data: ProcessIOParameter[];
290 showImagePreview: boolean;
293 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
295 const ProcessIOPreview = withStyles(styles)(
296 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
297 const showLabel = data.some((param: ProcessIOParameter) => param.label);
298 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
301 <TableCell>Name</TableCell>
302 {showLabel && <TableCell>Label</TableCell>}
303 <TableCell>Value</TableCell>
304 <TableCell>Collection</TableCell>
308 {data.map((param: ProcessIOParameter) => {
309 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
310 const rest = param.value.slice(1);
311 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
314 <TableRow className={rowClass} data-cy="process-io-param">
318 {showLabel && <TableCell >{param.label}</TableCell>}
320 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
322 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
323 <Typography className={classes.paramValue}>
324 {firstVal?.collection}
328 {rest.map((val, i) => (
329 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
331 {showLabel && <TableCell />}
333 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
335 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
336 <Typography className={classes.paramValue}>
348 interface ProcessValuePreviewProps {
349 value: ProcessIOValue;
350 showImagePreview: boolean;
353 const ProcessValuePreview = withStyles(styles)(
354 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
355 <Typography className={classes.paramValue}>
356 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
357 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
358 <span className={classes.valArray}>
364 const handleClick = (url) => {
365 window.open(url, '_blank');
369 interface ProcessIORawDataProps {
370 data: ProcessIOParameter[];
373 const ProcessIORaw = withStyles(styles)(
374 ({ data }: ProcessIORawDataProps) =>
375 <Paper elevation={0}>
377 {JSON.stringify(data, null, 2)}
382 interface ProcessInputMountsDataProps {
383 mounts: InputCollectionMount[];
386 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
388 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
390 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
391 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
394 <TableCell>Path</TableCell>
395 <TableCell>Portable Data Hash</TableCell>
399 {mounts.map(mount => (
400 <TableRow key={mount.path}>
401 <TableCell><pre>{mount.path}</pre></TableCell>
403 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
411 type FileWithSecondaryFiles = {
412 secondaryFiles: File[];
415 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
417 case isPrimitiveOfType(input, CWLType.BOOLEAN):
418 const boolValue = (input as BooleanCommandInputParameter).value;
420 return boolValue !== undefined &&
421 !(Array.isArray(boolValue) && boolValue.length === 0) ?
422 [{display: <pre>{String(boolValue)}</pre> }] :
423 [{display: <EmptyValue />}];
425 case isPrimitiveOfType(input, CWLType.INT):
426 case isPrimitiveOfType(input, CWLType.LONG):
427 const intValue = (input as IntCommandInputParameter).value;
429 return intValue !== undefined &&
430 // Missing values are empty array
431 !(Array.isArray(intValue) && intValue.length === 0) ?
432 [{display: <pre>{String(intValue)}</pre> }]
433 : [{display: <EmptyValue />}];
435 case isPrimitiveOfType(input, CWLType.FLOAT):
436 case isPrimitiveOfType(input, CWLType.DOUBLE):
437 const floatValue = (input as FloatCommandInputParameter).value;
439 return floatValue !== undefined &&
440 !(Array.isArray(floatValue) && floatValue.length === 0) ?
441 [{display: <pre>{String(floatValue)}</pre> }]:
442 [{display: <EmptyValue />}];
444 case isPrimitiveOfType(input, CWLType.STRING):
445 const stringValue = (input as StringCommandInputParameter).value || undefined;
447 return stringValue !== undefined &&
448 !(Array.isArray(stringValue) && stringValue.length === 0) ?
449 [{display: <pre>{stringValue}</pre> }] :
450 [{display: <EmptyValue />}];
452 case isPrimitiveOfType(input, CWLType.FILE):
453 const mainFile = (input as FileCommandInputParameter).value;
454 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
455 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
457 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
461 return files.length ?
462 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
463 [{display: <EmptyValue />}];
465 case isPrimitiveOfType(input, CWLType.DIRECTORY):
466 const directory = (input as DirectoryCommandInputParameter).value;
468 return directory !== undefined &&
469 !(Array.isArray(directory) && directory.length === 0) ?
470 [directoryToProcessIOValue(directory, auth, pdh)] :
471 [{display: <EmptyValue />}];
473 case typeof input.type === 'object' &&
474 !(input.type instanceof Array) &&
475 input.type.type === 'enum':
476 const enumValue = (input as EnumCommandInputParameter).value;
478 return enumValue !== undefined ?
479 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
480 [{display: <EmptyValue />}];
482 case isArrayOfType(input, CWLType.STRING):
483 const strArray = (input as StringArrayCommandInputParameter).value || [];
484 return strArray.length ?
485 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
486 [{display: <EmptyValue />}];
488 case isArrayOfType(input, CWLType.INT):
489 case isArrayOfType(input, CWLType.LONG):
490 const intArray = (input as IntArrayCommandInputParameter).value || [];
492 return intArray.length ?
493 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
494 [{display: <EmptyValue />}];
496 case isArrayOfType(input, CWLType.FLOAT):
497 case isArrayOfType(input, CWLType.DOUBLE):
498 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
500 return floatArray.length ?
501 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
502 [{display: <EmptyValue />}];
504 case isArrayOfType(input, CWLType.FILE):
505 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
506 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
507 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
508 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
510 const fileArrayFiles = [
511 ...fileArrayMainFile,
512 ...fileArraySecondaryFiles
515 return fileArrayFiles.length ?
516 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
517 [{display: <EmptyValue />}];
519 case isArrayOfType(input, CWLType.DIRECTORY):
520 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
522 return directories.length ?
523 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
524 [{display: <EmptyValue />}];
531 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
532 const isKeepUrl = file.location?.startsWith('keep:') || false;
533 const keepUrl = isKeepUrl ? file.location : pdh ? `keep:${pdh}/${file.location}` : file.location;
534 return keepUrl || '';
537 interface KeepUrlProps {
539 res: File | Directory;
543 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
544 const keepUrl = getKeepUrl(res, pdh);
545 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
546 // Passing a pdh always returns a relative wb2 collection url
547 const pdhWbPath = getNavUrl(pdhUrl.replace('keep:', ''), auth);
548 return pdhUrl && pdhWbPath ?
549 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
553 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
554 const keepUrl = getKeepUrl(res, pdh);
555 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
556 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
558 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
559 return keepUrlPath && keepUrlPathNav ?
560 <Tooltip title={"View in keep-web"}><MuiLink className={classes.keepLink} onClick={() => handleClick(keepUrlPathNav)}>{keepUrlPath}</MuiLink></Tooltip> :
561 // Show No value for root collection io that lacks path part
565 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
566 let keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
567 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
570 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
571 const keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
572 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
575 const isFileImage = (basename?: string): boolean => {
576 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
579 const normalizeDirectoryLocation = (directory: Directory): Directory => {
580 if (!directory.location) {
585 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
589 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
590 const normalizedDirectory = normalizeDirectoryLocation(directory);
592 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
593 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
597 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
599 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
600 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
601 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
605 const EmptyValue = withStyles(styles)(
606 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
609 const ImagePlaceholder = withStyles(styles)(
610 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>