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';
86 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
91 paddingTop: theme.spacing.unit,
92 paddingBottom: theme.spacing.unit,
96 color: theme.customs.colors.green700,
99 alignSelf: 'flex-start',
100 paddingTop: theme.spacing.unit * 0.5
103 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
104 padding: theme.spacing.unit * 1.0,
105 paddingTop: theme.spacing.unit * 0.5,
107 paddingBottom: theme.spacing.unit * 1,
112 paddingTop: theme.spacing.unit * 0.5
115 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
121 verticalAlign: 'bottom',
122 paddingBottom: '10px',
125 paddingRight: '25px',
130 alignItems: 'flex-start',
131 flexDirection: 'column',
134 color: theme.palette.primary.main,
135 textDecoration: 'none',
136 overflowWrap: 'break-word',
142 color: theme.palette.primary.main,
143 textDecoration: 'none',
144 overflowWrap: 'break-word',
151 marginBottom: theme.spacing.unit,
162 color: theme.customs.colors.grey500,
166 borderBottom: 'none',
178 alignItems: 'center',
179 justifyContent: 'center',
180 backgroundColor: '#cecece',
181 borderRadius: '10px',
184 verticalAlign: 'bottom',
188 export enum ProcessIOCardType {
192 export interface ProcessIOCardDataProps {
194 label: ProcessIOCardType;
195 params: ProcessIOParameter[];
197 mounts?: InputCollectionMount[];
201 export interface ProcessIOCardActionProps {
202 navigateTo: (uuid: string) => void;
205 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
206 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
209 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
211 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
212 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
213 const [mainProcTabState, setMainProcTabState] = useState(0);
214 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
215 setMainProcTabState(value);
218 const [showImagePreview, setShowImagePreview] = useState(false);
220 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
221 const mainProcess = !process.containerRequest.requestingContainerUuid;
223 return <Card className={classes.card} data-cy="process-io-card">
225 className={classes.header}
227 content: classes.title,
228 avatar: classes.avatar,
230 avatar={<PanelIcon className={classes.iconHeader} />}
232 <Typography noWrap variant='h6' color='inherit'>
238 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
239 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
241 { doMaximizePanel && !panelMaximized &&
242 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
243 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
246 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
247 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
251 <CardContent className={classes.content}>
256 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
257 <Tab label="Parameters" />
260 {mainProcTabState === 0 && <div className={classes.tableWrapper}>
261 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
263 {mainProcTabState === 1 && <div className={classes.tableWrapper}>
264 <ProcessIORaw data={raw || params} />
267 <Grid container item alignItems='center' justify='center'>
268 <DefaultView messages={["No parameters found"]} />
273 {((mounts && mounts.length) || outputUuid) ?
275 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
276 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
277 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
279 <div className={classes.tableWrapper}>
280 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
281 {label === ProcessIOCardType.OUTPUT && <>
282 {outputUuid && <Typography className={classes.collectionLink}>
283 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
285 </MuiLink></Typography>}
286 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
290 <Grid container item alignItems='center' justify='center'>
291 <DefaultView messages={["No collection(s) found"]} />
301 export type ProcessIOValue = {
302 display: ReactElement<any, any>;
304 collection?: ReactElement<any, any>;
307 export type ProcessIOParameter = {
310 value: ProcessIOValue[];
313 interface ProcessIOPreviewDataProps {
314 data: ProcessIOParameter[];
315 showImagePreview: boolean;
318 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
320 const ProcessIOPreview = withStyles(styles)(
321 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
322 const showLabel = data.some((param: ProcessIOParameter) => param.label);
323 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
326 <TableCell>Name</TableCell>
327 {showLabel && <TableCell>Label</TableCell>}
328 <TableCell>Value</TableCell>
329 <TableCell>Collection</TableCell>
333 {data.map((param: ProcessIOParameter) => {
334 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
335 const rest = param.value.slice(1);
336 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
339 <TableRow className={rowClass} data-cy="process-io-param">
343 {showLabel && <TableCell >{param.label}</TableCell>}
345 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
347 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
348 <Typography className={classes.paramValue}>
349 {firstVal?.collection}
353 {rest.map((val, i) => (
354 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
356 {showLabel && <TableCell />}
358 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
360 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
361 <Typography className={classes.paramValue}>
373 interface ProcessValuePreviewProps {
374 value: ProcessIOValue;
375 showImagePreview: boolean;
378 const ProcessValuePreview = withStyles(styles)(
379 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
380 <Typography className={classes.paramValue}>
381 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
382 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
383 <span className={classes.valArray}>
389 const handleClick = (url) => {
390 window.open(url, '_blank');
394 interface ProcessIORawDataProps {
395 data: ProcessIOParameter[];
398 const ProcessIORaw = withStyles(styles)(
399 ({ data }: ProcessIORawDataProps) =>
400 <Paper elevation={0}>
402 {JSON.stringify(data, null, 2)}
407 interface ProcessInputMountsDataProps {
408 mounts: InputCollectionMount[];
411 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
413 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
415 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
416 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
419 <TableCell>Path</TableCell>
420 <TableCell>Portable Data Hash</TableCell>
424 {mounts.map(mount => (
425 <TableRow key={mount.path}>
426 <TableCell><pre>{mount.path}</pre></TableCell>
428 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
436 type FileWithSecondaryFiles = {
437 secondaryFiles: File[];
440 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
442 case isPrimitiveOfType(input, CWLType.BOOLEAN):
443 const boolValue = (input as BooleanCommandInputParameter).value;
445 return boolValue !== undefined &&
446 !(Array.isArray(boolValue) && boolValue.length === 0) ?
447 [{display: <pre>{String(boolValue)}</pre> }] :
448 [{display: <EmptyValue />}];
450 case isPrimitiveOfType(input, CWLType.INT):
451 case isPrimitiveOfType(input, CWLType.LONG):
452 const intValue = (input as IntCommandInputParameter).value;
454 return intValue !== undefined &&
455 // Missing values are empty array
456 !(Array.isArray(intValue) && intValue.length === 0) ?
457 [{display: <pre>{String(intValue)}</pre> }]
458 : [{display: <EmptyValue />}];
460 case isPrimitiveOfType(input, CWLType.FLOAT):
461 case isPrimitiveOfType(input, CWLType.DOUBLE):
462 const floatValue = (input as FloatCommandInputParameter).value;
464 return floatValue !== undefined &&
465 !(Array.isArray(floatValue) && floatValue.length === 0) ?
466 [{display: <pre>{String(floatValue)}</pre> }]:
467 [{display: <EmptyValue />}];
469 case isPrimitiveOfType(input, CWLType.STRING):
470 const stringValue = (input as StringCommandInputParameter).value || undefined;
472 return stringValue !== undefined &&
473 !(Array.isArray(stringValue) && stringValue.length === 0) ?
474 [{display: <pre>{stringValue}</pre> }] :
475 [{display: <EmptyValue />}];
477 case isPrimitiveOfType(input, CWLType.FILE):
478 const mainFile = (input as FileCommandInputParameter).value;
479 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
480 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
482 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
486 return files.length ?
487 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
488 [{display: <EmptyValue />}];
490 case isPrimitiveOfType(input, CWLType.DIRECTORY):
491 const directory = (input as DirectoryCommandInputParameter).value;
493 return directory !== undefined &&
494 !(Array.isArray(directory) && directory.length === 0) ?
495 [directoryToProcessIOValue(directory, auth, pdh)] :
496 [{display: <EmptyValue />}];
498 case typeof input.type === 'object' &&
499 !(input.type instanceof Array) &&
500 input.type.type === 'enum':
501 const enumValue = (input as EnumCommandInputParameter).value;
503 return enumValue !== undefined ?
504 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
505 [{display: <EmptyValue />}];
507 case isArrayOfType(input, CWLType.STRING):
508 const strArray = (input as StringArrayCommandInputParameter).value || [];
509 return strArray.length ?
510 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
511 [{display: <EmptyValue />}];
513 case isArrayOfType(input, CWLType.INT):
514 case isArrayOfType(input, CWLType.LONG):
515 const intArray = (input as IntArrayCommandInputParameter).value || [];
517 return intArray.length ?
518 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
519 [{display: <EmptyValue />}];
521 case isArrayOfType(input, CWLType.FLOAT):
522 case isArrayOfType(input, CWLType.DOUBLE):
523 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
525 return floatArray.length ?
526 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
527 [{display: <EmptyValue />}];
529 case isArrayOfType(input, CWLType.FILE):
530 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
531 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
532 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
533 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
535 const fileArrayFiles = [
536 ...fileArrayMainFile,
537 ...fileArraySecondaryFiles
540 return fileArrayFiles.length ?
541 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
542 [{display: <EmptyValue />}];
544 case isArrayOfType(input, CWLType.DIRECTORY):
545 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
547 return directories.length ?
548 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
549 [{display: <EmptyValue />}];
556 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
557 const isKeepUrl = file.location?.startsWith('keep:') || false;
558 const keepUrl = isKeepUrl ? file.location : pdh ? `keep:${pdh}/${file.location}` : file.location;
559 return keepUrl || '';
562 interface KeepUrlProps {
564 res: File | Directory;
568 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
569 const keepUrl = getKeepUrl(res, pdh);
570 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
571 // Passing a pdh always returns a relative wb2 collection url
572 const pdhWbPath = getNavUrl(pdhUrl.replace('keep:', ''), auth);
573 return pdhUrl && pdhWbPath ?
574 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
578 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
579 const keepUrl = getKeepUrl(res, pdh);
580 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
581 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
583 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
584 return keepUrlPath && keepUrlPathNav ?
585 <Tooltip title={"View in keep-web"}><MuiLink className={classes.keepLink} onClick={() => handleClick(keepUrlPathNav)}>{keepUrlPath}</MuiLink></Tooltip> :
586 // Show No value for root collection io that lacks path part
590 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
591 let keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
592 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
595 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
596 const keepUrl = getKeepUrl(file, pdh).replace('keep:', '');
597 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
600 const isFileImage = (basename?: string): boolean => {
601 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
604 const normalizeDirectoryLocation = (directory: Directory): Directory => {
605 if (!directory.location) {
610 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
614 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
615 const normalizedDirectory = normalizeDirectoryLocation(directory);
617 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
618 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
622 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
624 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
625 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
626 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
630 const EmptyValue = withStyles(styles)(
631 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
634 const ImagePlaceholder = withStyles(styles)(
635 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>