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';
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';
33 BooleanCommandInputParameter,
34 CommandInputParameter,
37 DirectoryArrayCommandInputParameter,
38 DirectoryCommandInputParameter,
39 EnumCommandInputParameter,
40 FileArrayCommandInputParameter,
41 FileCommandInputParameter,
42 FloatArrayCommandInputParameter,
43 FloatCommandInputParameter,
44 IntArrayCommandInputParameter,
45 IntCommandInputParameter,
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';
88 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
93 paddingTop: theme.spacing.unit,
94 paddingBottom: theme.spacing.unit,
98 color: theme.customs.colors.green700,
101 alignSelf: 'flex-start',
102 paddingTop: theme.spacing.unit * 0.5
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,
109 paddingBottom: theme.spacing.unit * 1,
114 paddingTop: theme.spacing.unit * 0.5
117 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
123 verticalAlign: 'bottom',
124 paddingBottom: '10px',
127 paddingRight: '25px',
132 alignItems: 'flex-start',
133 flexDirection: 'column',
136 color: theme.palette.primary.main,
137 textDecoration: 'none',
138 overflowWrap: 'break-word',
144 color: theme.palette.primary.main,
145 textDecoration: 'none',
146 overflowWrap: 'break-word',
153 marginBottom: theme.spacing.unit,
164 color: theme.customs.colors.grey500,
168 borderBottom: 'none',
180 alignItems: 'center',
181 justifyContent: 'center',
182 backgroundColor: '#cecece',
183 borderRadius: '10px',
186 verticalAlign: 'bottom',
193 export enum ProcessIOCardType {
197 export interface ProcessIOCardDataProps {
199 label: ProcessIOCardType;
200 params?: ProcessIOParameter[];
202 mounts?: InputCollectionMount[];
206 export interface ProcessIOCardActionProps {
207 navigateTo: (uuid: string) => void;
210 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
211 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
214 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
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);
223 const [showImagePreview, setShowImagePreview] = useState(false);
225 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
226 const mainProcess = !process.containerRequest.requestingContainerUuid;
228 return <Card className={classes.card} data-cy="process-io-card">
230 className={classes.header}
232 content: classes.title,
233 avatar: classes.avatar,
235 avatar={<PanelIcon className={classes.iconHeader} />}
237 <Typography noWrap variant='h6' color='inherit'>
243 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
244 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
246 { doMaximizePanel && !panelMaximized &&
247 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
248 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
251 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
252 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
256 <CardContent className={classes.content}>
259 {/* raw is undefined until params are loaded */}
260 {raw === undefined && <Grid container item alignItems='center' justify='center'>
263 {raw && Object.keys(raw).length > 0 &&
265 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
266 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
267 {(params && params.length) && <Tab label="Parameters" />}
270 {(mainProcTabState === 0 && params && params.length > 0) && <div className={classes.tableWrapper}>
271 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
273 {(mainProcTabState === 1 || !params || !(params.length > 0)) && <div className={classes.tableWrapper}>
274 <ProcessIORaw data={raw} />
277 {raw && Object.keys(raw).length === 0 && <Grid container item alignItems='center' justify='center'>
278 <DefaultView messages={["No parameters found"]} />
283 {((mounts && mounts.length) || outputUuid) ?
285 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
286 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
287 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
289 <div className={classes.tableWrapper}>
290 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
291 {label === ProcessIOCardType.OUTPUT && <>
292 {outputUuid && <Typography className={classes.collectionLink}>
293 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
295 </MuiLink></Typography>}
296 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
300 <Grid container item alignItems='center' justify='center'>
301 <DefaultView messages={["No collection(s) found"]} />
311 export type ProcessIOValue = {
312 display: ReactElement<any, any>;
314 collection?: ReactElement<any, any>;
317 export type ProcessIOParameter = {
320 value: ProcessIOValue[];
323 interface ProcessIOPreviewDataProps {
324 data: ProcessIOParameter[];
325 showImagePreview: boolean;
328 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
330 const ProcessIOPreview = withStyles(styles)(
331 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
332 const showLabel = data.some((param: ProcessIOParameter) => param.label);
333 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
336 <TableCell>Name</TableCell>
337 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
338 <TableCell>Value</TableCell>
339 <TableCell>Collection</TableCell>
343 {data.map((param: ProcessIOParameter) => {
344 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
345 const rest = param.value.slice(1);
346 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
349 <TableRow className={rowClass} data-cy="process-io-param">
353 {showLabel && <TableCell >{param.label}</TableCell>}
355 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
357 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
358 <Typography className={classes.paramValue}>
359 {firstVal?.collection}
363 {rest.map((val, i) => (
364 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
366 {showLabel && <TableCell />}
368 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
370 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
371 <Typography className={classes.paramValue}>
383 interface ProcessValuePreviewProps {
384 value: ProcessIOValue;
385 showImagePreview: boolean;
388 const ProcessValuePreview = withStyles(styles)(
389 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
390 <Typography className={classes.paramValue}>
391 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
392 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
393 <span className={classes.valArray}>
399 interface ProcessIORawDataProps {
400 data: ProcessIOParameter[];
403 const ProcessIORaw = withStyles(styles)(
404 ({ data }: ProcessIORawDataProps) =>
405 <Paper elevation={0}>
407 {JSON.stringify(data, null, 2)}
412 interface ProcessInputMountsDataProps {
413 mounts: InputCollectionMount[];
416 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
418 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
420 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
421 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
424 <TableCell>Path</TableCell>
425 <TableCell>Portable Data Hash</TableCell>
429 {mounts.map(mount => (
430 <TableRow key={mount.path}>
431 <TableCell><pre>{mount.path}</pre></TableCell>
433 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
441 type FileWithSecondaryFiles = {
442 secondaryFiles: File[];
445 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
447 case isPrimitiveOfType(input, CWLType.BOOLEAN):
448 const boolValue = (input as BooleanCommandInputParameter).value;
450 return boolValue !== undefined &&
451 !(Array.isArray(boolValue) && boolValue.length === 0) ?
452 [{display: <pre>{String(boolValue)}</pre> }] :
453 [{display: <EmptyValue />}];
455 case isPrimitiveOfType(input, CWLType.INT):
456 case isPrimitiveOfType(input, CWLType.LONG):
457 const intValue = (input as IntCommandInputParameter).value;
459 return intValue !== undefined &&
460 // Missing values are empty array
461 !(Array.isArray(intValue) && intValue.length === 0) ?
462 [{display: <pre>{String(intValue)}</pre> }]
463 : [{display: <EmptyValue />}];
465 case isPrimitiveOfType(input, CWLType.FLOAT):
466 case isPrimitiveOfType(input, CWLType.DOUBLE):
467 const floatValue = (input as FloatCommandInputParameter).value;
469 return floatValue !== undefined &&
470 !(Array.isArray(floatValue) && floatValue.length === 0) ?
471 [{display: <pre>{String(floatValue)}</pre> }]:
472 [{display: <EmptyValue />}];
474 case isPrimitiveOfType(input, CWLType.STRING):
475 const stringValue = (input as StringCommandInputParameter).value || undefined;
477 return stringValue !== undefined &&
478 !(Array.isArray(stringValue) && stringValue.length === 0) ?
479 [{display: <pre>{stringValue}</pre> }] :
480 [{display: <EmptyValue />}];
482 case isPrimitiveOfType(input, CWLType.FILE):
483 const mainFile = (input as FileCommandInputParameter).value;
484 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
485 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
487 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
491 return files.length ?
492 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
493 [{display: <EmptyValue />}];
495 case isPrimitiveOfType(input, CWLType.DIRECTORY):
496 const directory = (input as DirectoryCommandInputParameter).value;
498 return directory !== undefined &&
499 !(Array.isArray(directory) && directory.length === 0) ?
500 [directoryToProcessIOValue(directory, auth, pdh)] :
501 [{display: <EmptyValue />}];
503 case typeof input.type === 'object' &&
504 !(input.type instanceof Array) &&
505 input.type.type === 'enum':
506 const enumValue = (input as EnumCommandInputParameter).value;
508 return enumValue !== undefined ?
509 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
510 [{display: <EmptyValue />}];
512 case isArrayOfType(input, CWLType.STRING):
513 const strArray = (input as StringArrayCommandInputParameter).value || [];
514 return strArray.length ?
515 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
516 [{display: <EmptyValue />}];
518 case isArrayOfType(input, CWLType.INT):
519 case isArrayOfType(input, CWLType.LONG):
520 const intArray = (input as IntArrayCommandInputParameter).value || [];
522 return intArray.length ?
523 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
524 [{display: <EmptyValue />}];
526 case isArrayOfType(input, CWLType.FLOAT):
527 case isArrayOfType(input, CWLType.DOUBLE):
528 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
530 return floatArray.length ?
531 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
532 [{display: <EmptyValue />}];
534 case isArrayOfType(input, CWLType.FILE):
535 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
536 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
537 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
538 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
540 const fileArrayFiles = [
541 ...fileArrayMainFile,
542 ...fileArraySecondaryFiles
545 return fileArrayFiles.length ?
546 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
547 [{display: <EmptyValue />}];
549 case isArrayOfType(input, CWLType.DIRECTORY):
550 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
552 return directories.length ?
553 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
554 [{display: <EmptyValue />}];
562 * @returns keep url without keep: prefix
564 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
565 const isKeepUrl = file.location?.startsWith('keep:') || false;
566 const keepUrl = isKeepUrl ?
567 file.location?.replace('keep:', '') :
568 pdh ? `${pdh}/${file.location}` : file.location;
569 return keepUrl || '';
572 interface KeepUrlProps {
574 res: File | Directory;
578 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
579 const keepUrl = getKeepUrl(res, pdh);
580 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
581 // Passing a pdh always returns a relative wb2 collection url
582 const pdhWbPath = getNavUrl(pdhUrl, auth);
583 return pdhUrl && pdhWbPath ?
584 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
588 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
589 const keepUrl = getKeepUrl(res, pdh);
590 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
591 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
593 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
594 return keepUrlPath && keepUrlPathNav ?
595 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath}</a></Tooltip> :
596 // Show No value for root collection io that lacks path part
600 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
601 let keepUrl = getKeepUrl(file, pdh);
602 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
605 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
606 const keepUrl = getKeepUrl(file, pdh);
607 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
610 const isFileImage = (basename?: string): boolean => {
611 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
614 const normalizeDirectoryLocation = (directory: Directory): Directory => {
615 if (!directory.location) {
620 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
624 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
625 const normalizedDirectory = normalizeDirectoryLocation(directory);
627 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
628 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
632 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
634 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
635 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
636 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
640 const EmptyValue = withStyles(styles)(
641 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
644 const ImagePlaceholder = withStyles(styles)(
645 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>