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, InputIcon, ImageOffIcon, OutputIcon, MaximizeIcon } 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 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
86 padding: theme.spacing.unit * 1.0,
87 paddingTop: theme.spacing.unit * 0.5,
89 paddingBottom: theme.spacing.unit * 1,
94 paddingTop: theme.spacing.unit * 0.5
97 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
103 verticalAlign: 'bottom',
104 paddingBottom: '10px',
109 alignItems: 'flex-start',
110 flexDirection: 'column',
113 color: theme.palette.primary.main,
114 textDecoration: 'none',
115 overflowWrap: 'break-word',
121 color: theme.palette.primary.main,
122 textDecoration: 'none',
123 overflowWrap: 'break-word',
130 marginBottom: theme.spacing.unit,
141 color: theme.customs.colors.grey500,
145 borderBottom: 'none',
157 alignItems: 'center',
158 justifyContent: 'center',
159 backgroundColor: '#cecece',
160 borderRadius: '10px',
163 verticalAlign: 'bottom',
167 export enum ProcessIOCardType {
171 export interface ProcessIOCardDataProps {
173 label: ProcessIOCardType;
174 params: ProcessIOParameter[];
176 mounts?: InputCollectionMount[];
180 export interface ProcessIOCardActionProps {
181 navigateTo: (uuid: string) => void;
184 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
185 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
188 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
190 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
191 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
192 const [mainProcTabState, setMainProcTabState] = useState(0);
193 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
194 setMainProcTabState(value);
197 const [showImagePreview, setShowImagePreview] = useState(false);
199 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
200 const mainProcess = !process.containerRequest.requestingContainerUuid;
202 return <Card className={classes.card} data-cy="process-io-card">
204 className={classes.header}
206 content: classes.title,
207 avatar: classes.avatar,
209 avatar={<PanelIcon className={classes.iconHeader} />}
211 <Typography noWrap variant='h6' color='inherit'>
217 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
218 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
220 { doMaximizePanel && !panelMaximized &&
221 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
222 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
225 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
226 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
230 <CardContent className={classes.content}>
235 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
236 <Tab label="Parameters" />
239 {mainProcTabState === 0 && <div className={classes.tableWrapper}>
240 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
242 {mainProcTabState === 1 && <div className={classes.tableWrapper}>
243 <ProcessIORaw data={raw || params} />
246 <Grid container item alignItems='center' justify='center'>
247 <DefaultView messages={["No parameters found"]} />
252 {((mounts && mounts.length) || outputUuid) ?
254 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
255 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
256 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
258 <div className={classes.tableWrapper}>
259 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
260 {label === ProcessIOCardType.OUTPUT && <>
261 {outputUuid && <Typography className={classes.collectionLink}>
262 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
264 </MuiLink></Typography>}
265 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
269 <Grid container item alignItems='center' justify='center'>
270 <DefaultView messages={["No collection(s) found"]} />
280 export type ProcessIOValue = {
281 display: ReactElement<any, any>;
283 collection?: ReactElement<any, any>;
286 export type ProcessIOParameter = {
289 value: ProcessIOValue[];
292 interface ProcessIOPreviewDataProps {
293 data: ProcessIOParameter[];
294 showImagePreview: boolean;
297 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
299 const ProcessIOPreview = withStyles(styles)(
300 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
301 const showLabel = data.some((param: ProcessIOParameter) => param.label);
302 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
305 <TableCell>Name</TableCell>
306 {showLabel && <TableCell>Label</TableCell>}
307 <TableCell>Value</TableCell>
308 <TableCell>Collection</TableCell>
312 {data.map((param: ProcessIOParameter) => {
313 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
314 const rest = param.value.slice(1);
315 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
318 <TableRow className={rowClass} data-cy="process-io-param">
322 {showLabel && <TableCell >{param.label}</TableCell>}
324 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
326 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
327 <Typography className={classes.paramValue}>
328 {firstVal?.collection}
332 {rest.map((val, i) => (
333 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
335 {showLabel && <TableCell />}
337 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
339 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
340 <Typography className={classes.paramValue}>
352 interface ProcessValuePreviewProps {
353 value: ProcessIOValue;
354 showImagePreview: boolean;
357 const ProcessValuePreview = withStyles(styles)(
358 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
359 <Typography className={classes.paramValue}>
360 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
361 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
362 <span className={classes.valArray}>
368 const handleClick = (url) => {
369 window.open(url, '_blank');
373 interface ProcessIORawDataProps {
374 data: ProcessIOParameter[];
377 const ProcessIORaw = withStyles(styles)(
378 ({ data }: ProcessIORawDataProps) =>
379 <Paper elevation={0}>
381 {JSON.stringify(data, null, 2)}
386 interface ProcessInputMountsDataProps {
387 mounts: InputCollectionMount[];
390 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
392 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
394 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
395 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
398 <TableCell>Path</TableCell>
399 <TableCell>Portable Data Hash</TableCell>
403 {mounts.map(mount => (
404 <TableRow key={mount.path}>
405 <TableCell><pre>{mount.path}</pre></TableCell>
407 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
415 type FileWithSecondaryFiles = {
416 secondaryFiles: File[];
419 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
421 case isPrimitiveOfType(input, CWLType.BOOLEAN):
422 const boolValue = (input as BooleanCommandInputParameter).value;
424 return boolValue !== undefined &&
425 !(Array.isArray(boolValue) && boolValue.length === 0) ?
426 [{display: <pre>{String(boolValue)}</pre> }] :
427 [{display: <EmptyValue />}];
429 case isPrimitiveOfType(input, CWLType.INT):
430 case isPrimitiveOfType(input, CWLType.LONG):
431 const intValue = (input as IntCommandInputParameter).value;
433 return intValue !== undefined &&
434 // Missing values are empty array
435 !(Array.isArray(intValue) && intValue.length === 0) ?
436 [{display: <pre>{String(intValue)}</pre> }]
437 : [{display: <EmptyValue />}];
439 case isPrimitiveOfType(input, CWLType.FLOAT):
440 case isPrimitiveOfType(input, CWLType.DOUBLE):
441 const floatValue = (input as FloatCommandInputParameter).value;
443 return floatValue !== undefined &&
444 !(Array.isArray(floatValue) && floatValue.length === 0) ?
445 [{display: <pre>{String(floatValue)}</pre> }]:
446 [{display: <EmptyValue />}];
448 case isPrimitiveOfType(input, CWLType.STRING):
449 const stringValue = (input as StringCommandInputParameter).value || undefined;
451 return stringValue !== undefined &&
452 !(Array.isArray(stringValue) && stringValue.length === 0) ?
453 [{display: <pre>{stringValue}</pre> }] :
454 [{display: <EmptyValue />}];
456 case isPrimitiveOfType(input, CWLType.FILE):
457 const mainFile = (input as FileCommandInputParameter).value;
458 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
459 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
461 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
465 return files.length ?
466 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
467 [{display: <EmptyValue />}];
469 case isPrimitiveOfType(input, CWLType.DIRECTORY):
470 const directory = (input as DirectoryCommandInputParameter).value;
472 return directory !== undefined &&
473 !(Array.isArray(directory) && directory.length === 0) ?
474 [directoryToProcessIOValue(directory, auth, pdh)] :
475 [{display: <EmptyValue />}];
477 case typeof input.type === 'object' &&
478 !(input.type instanceof Array) &&
479 input.type.type === 'enum':
480 const enumValue = (input as EnumCommandInputParameter).value;
482 return enumValue !== undefined ?
483 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
484 [{display: <EmptyValue />}];
486 case isArrayOfType(input, CWLType.STRING):
487 const strArray = (input as StringArrayCommandInputParameter).value || [];
488 return strArray.length ?
489 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
490 [{display: <EmptyValue />}];
492 case isArrayOfType(input, CWLType.INT):
493 case isArrayOfType(input, CWLType.LONG):
494 const intArray = (input as IntArrayCommandInputParameter).value || [];
496 return intArray.length ?
497 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
498 [{display: <EmptyValue />}];
500 case isArrayOfType(input, CWLType.FLOAT):
501 case isArrayOfType(input, CWLType.DOUBLE):
502 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
504 return floatArray.length ?
505 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
506 [{display: <EmptyValue />}];
508 case isArrayOfType(input, CWLType.FILE):
509 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
510 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
511 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
512 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
514 const fileArrayFiles = [
515 ...fileArrayMainFile,
516 ...fileArraySecondaryFiles
519 return fileArrayFiles.length ?
520 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
521 [{display: <EmptyValue />}];
523 case isArrayOfType(input, CWLType.DIRECTORY):
524 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
526 return directories.length ?
527 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
528 [{display: <EmptyValue />}];
535 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
536 const isKeepUrl = file.location?.startsWith('keep:') || false;
537 const keepUrl = isKeepUrl ? file.location : pdh ? `keep:${pdh}/${file.location}` : file.location;
538 return keepUrl || '';
541 interface KeepUrlProps {
543 res: File | Directory;
547 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
548 const keepUrl = getKeepUrl(res, pdh);
549 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
550 // Passing a pdh always returns a relative wb2 collection url
551 const pdhWbPath = getNavUrl(pdhUrl.replace('keep:', ''), auth);
552 return pdhUrl && pdhWbPath ?
553 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
557 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
558 const keepUrl = getKeepUrl(res, pdh);
559 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
560 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
562 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
563 return keepUrlPath && keepUrlPathNav ?
564 <Tooltip title={"View in keep-web"}><MuiLink className={classes.keepLink} onClick={() => handleClick(keepUrlPathNav)}>{keepUrlPath}</MuiLink></Tooltip> :
565 // Show No value for root collection io that lacks path part
569 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
570 let keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
571 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
574 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
575 const keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
576 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
579 const isFileImage = (basename?: string): boolean => {
580 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
583 const normalizeDirectoryLocation = (directory: Directory): Directory => {
584 if (!directory.location) {
589 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
593 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
594 const normalizedDirectory = normalizeDirectoryLocation(directory);
596 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
597 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
601 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
603 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
604 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
605 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
609 const EmptyValue = withStyles(styles)(
610 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
613 const ImagePlaceholder = withStyles(styles)(
614 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>