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';
87 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
92 paddingTop: theme.spacing.unit,
93 paddingBottom: theme.spacing.unit,
97 color: theme.customs.colors.green700,
100 alignSelf: 'flex-start',
101 paddingTop: theme.spacing.unit * 0.5
104 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
105 padding: theme.spacing.unit * 1.0,
106 paddingTop: theme.spacing.unit * 0.5,
108 paddingBottom: theme.spacing.unit * 1,
113 paddingTop: theme.spacing.unit * 0.5
116 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
122 verticalAlign: 'bottom',
123 paddingBottom: '10px',
126 paddingRight: '25px',
131 alignItems: 'flex-start',
132 flexDirection: 'column',
135 color: theme.palette.primary.main,
136 textDecoration: 'none',
137 overflowWrap: 'break-word',
143 color: theme.palette.primary.main,
144 textDecoration: 'none',
145 overflowWrap: 'break-word',
152 marginBottom: theme.spacing.unit,
163 color: theme.customs.colors.grey500,
167 borderBottom: 'none',
179 alignItems: 'center',
180 justifyContent: 'center',
181 backgroundColor: '#cecece',
182 borderRadius: '10px',
185 verticalAlign: 'bottom',
189 export enum ProcessIOCardType {
193 export interface ProcessIOCardDataProps {
195 label: ProcessIOCardType;
196 params?: ProcessIOParameter[];
198 mounts?: InputCollectionMount[];
202 export interface ProcessIOCardActionProps {
203 navigateTo: (uuid: string) => void;
206 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
207 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
210 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
212 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
213 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
214 const [mainProcTabState, setMainProcTabState] = useState(0);
215 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
216 setMainProcTabState(value);
219 const [showImagePreview, setShowImagePreview] = useState(false);
221 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
222 const mainProcess = !process.containerRequest.requestingContainerUuid;
224 return <Card className={classes.card} data-cy="process-io-card">
226 className={classes.header}
228 content: classes.title,
229 avatar: classes.avatar,
231 avatar={<PanelIcon className={classes.iconHeader} />}
233 <Typography noWrap variant='h6' color='inherit'>
239 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
240 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
242 { doMaximizePanel && !panelMaximized &&
243 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
244 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
247 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
248 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
252 <CardContent className={classes.content}>
255 {params === undefined && <Grid container item alignItems='center' justify='center'>
258 {params && params.length > 0 &&
260 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
261 <Tab label="Parameters" />
264 {mainProcTabState === 0 && <div className={classes.tableWrapper}>
265 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
267 {mainProcTabState === 1 && <div className={classes.tableWrapper}>
268 <ProcessIORaw data={raw || params} />
271 {params && params.length === 0 && <Grid container item alignItems='center' justify='center'>
272 <DefaultView messages={["No parameters found"]} />
277 {((mounts && mounts.length) || outputUuid) ?
279 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
280 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
281 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
283 <div className={classes.tableWrapper}>
284 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
285 {label === ProcessIOCardType.OUTPUT && <>
286 {outputUuid && <Typography className={classes.collectionLink}>
287 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
289 </MuiLink></Typography>}
290 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
294 <Grid container item alignItems='center' justify='center'>
295 <DefaultView messages={["No collection(s) found"]} />
305 export type ProcessIOValue = {
306 display: ReactElement<any, any>;
308 collection?: ReactElement<any, any>;
311 export type ProcessIOParameter = {
314 value: ProcessIOValue[];
317 interface ProcessIOPreviewDataProps {
318 data: ProcessIOParameter[];
319 showImagePreview: boolean;
322 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
324 const ProcessIOPreview = withStyles(styles)(
325 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
326 const showLabel = data.some((param: ProcessIOParameter) => param.label);
327 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
330 <TableCell>Name</TableCell>
331 {showLabel && <TableCell>Label</TableCell>}
332 <TableCell>Value</TableCell>
333 <TableCell>Collection</TableCell>
337 {data.map((param: ProcessIOParameter) => {
338 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
339 const rest = param.value.slice(1);
340 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
343 <TableRow className={rowClass} data-cy="process-io-param">
347 {showLabel && <TableCell >{param.label}</TableCell>}
349 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
351 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
352 <Typography className={classes.paramValue}>
353 {firstVal?.collection}
357 {rest.map((val, i) => (
358 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
360 {showLabel && <TableCell />}
362 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
364 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
365 <Typography className={classes.paramValue}>
377 interface ProcessValuePreviewProps {
378 value: ProcessIOValue;
379 showImagePreview: boolean;
382 const ProcessValuePreview = withStyles(styles)(
383 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
384 <Typography className={classes.paramValue}>
385 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
386 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
387 <span className={classes.valArray}>
393 const handleClick = (url) => {
394 window.open(url, '_blank');
398 interface ProcessIORawDataProps {
399 data: ProcessIOParameter[];
402 const ProcessIORaw = withStyles(styles)(
403 ({ data }: ProcessIORawDataProps) =>
404 <Paper elevation={0}>
406 {JSON.stringify(data, null, 2)}
411 interface ProcessInputMountsDataProps {
412 mounts: InputCollectionMount[];
415 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
417 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
419 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
420 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
423 <TableCell>Path</TableCell>
424 <TableCell>Portable Data Hash</TableCell>
428 {mounts.map(mount => (
429 <TableRow key={mount.path}>
430 <TableCell><pre>{mount.path}</pre></TableCell>
432 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
440 type FileWithSecondaryFiles = {
441 secondaryFiles: File[];
444 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
446 case isPrimitiveOfType(input, CWLType.BOOLEAN):
447 const boolValue = (input as BooleanCommandInputParameter).value;
449 return boolValue !== undefined &&
450 !(Array.isArray(boolValue) && boolValue.length === 0) ?
451 [{display: <pre>{String(boolValue)}</pre> }] :
452 [{display: <EmptyValue />}];
454 case isPrimitiveOfType(input, CWLType.INT):
455 case isPrimitiveOfType(input, CWLType.LONG):
456 const intValue = (input as IntCommandInputParameter).value;
458 return intValue !== undefined &&
459 // Missing values are empty array
460 !(Array.isArray(intValue) && intValue.length === 0) ?
461 [{display: <pre>{String(intValue)}</pre> }]
462 : [{display: <EmptyValue />}];
464 case isPrimitiveOfType(input, CWLType.FLOAT):
465 case isPrimitiveOfType(input, CWLType.DOUBLE):
466 const floatValue = (input as FloatCommandInputParameter).value;
468 return floatValue !== undefined &&
469 !(Array.isArray(floatValue) && floatValue.length === 0) ?
470 [{display: <pre>{String(floatValue)}</pre> }]:
471 [{display: <EmptyValue />}];
473 case isPrimitiveOfType(input, CWLType.STRING):
474 const stringValue = (input as StringCommandInputParameter).value || undefined;
476 return stringValue !== undefined &&
477 !(Array.isArray(stringValue) && stringValue.length === 0) ?
478 [{display: <pre>{stringValue}</pre> }] :
479 [{display: <EmptyValue />}];
481 case isPrimitiveOfType(input, CWLType.FILE):
482 const mainFile = (input as FileCommandInputParameter).value;
483 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
484 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
486 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
490 return files.length ?
491 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
492 [{display: <EmptyValue />}];
494 case isPrimitiveOfType(input, CWLType.DIRECTORY):
495 const directory = (input as DirectoryCommandInputParameter).value;
497 return directory !== undefined &&
498 !(Array.isArray(directory) && directory.length === 0) ?
499 [directoryToProcessIOValue(directory, auth, pdh)] :
500 [{display: <EmptyValue />}];
502 case typeof input.type === 'object' &&
503 !(input.type instanceof Array) &&
504 input.type.type === 'enum':
505 const enumValue = (input as EnumCommandInputParameter).value;
507 return enumValue !== undefined ?
508 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
509 [{display: <EmptyValue />}];
511 case isArrayOfType(input, CWLType.STRING):
512 const strArray = (input as StringArrayCommandInputParameter).value || [];
513 return strArray.length ?
514 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
515 [{display: <EmptyValue />}];
517 case isArrayOfType(input, CWLType.INT):
518 case isArrayOfType(input, CWLType.LONG):
519 const intArray = (input as IntArrayCommandInputParameter).value || [];
521 return intArray.length ?
522 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
523 [{display: <EmptyValue />}];
525 case isArrayOfType(input, CWLType.FLOAT):
526 case isArrayOfType(input, CWLType.DOUBLE):
527 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
529 return floatArray.length ?
530 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
531 [{display: <EmptyValue />}];
533 case isArrayOfType(input, CWLType.FILE):
534 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
535 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
536 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
537 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
539 const fileArrayFiles = [
540 ...fileArrayMainFile,
541 ...fileArraySecondaryFiles
544 return fileArrayFiles.length ?
545 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
546 [{display: <EmptyValue />}];
548 case isArrayOfType(input, CWLType.DIRECTORY):
549 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
551 return directories.length ?
552 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
553 [{display: <EmptyValue />}];
561 * @returns keep url without keep: prefix
563 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
564 const isKeepUrl = file.location?.startsWith('keep:') || false;
565 const keepUrl = isKeepUrl ?
566 file.location?.replace('keep:', '') :
567 pdh ? `${pdh}/${file.location}` : file.location;
568 return keepUrl || '';
571 interface KeepUrlProps {
573 res: File | Directory;
577 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
578 const keepUrl = getKeepUrl(res, pdh);
579 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
580 // Passing a pdh always returns a relative wb2 collection url
581 const pdhWbPath = getNavUrl(pdhUrl, auth);
582 return pdhUrl && pdhWbPath ?
583 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
587 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
588 const keepUrl = getKeepUrl(res, pdh);
589 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
590 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
592 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
593 return keepUrlPath && keepUrlPathNav ?
594 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank">{keepUrlPath}</a></Tooltip> :
595 // Show No value for root collection io that lacks path part
599 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
600 let keepUrl = getKeepUrl(file, pdh);
601 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
604 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
605 const keepUrl = getKeepUrl(file, pdh);
606 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
609 const isFileImage = (basename?: string): boolean => {
610 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
613 const normalizeDirectoryLocation = (directory: Directory): Directory => {
614 if (!directory.location) {
619 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
623 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
624 const normalizedDirectory = normalizeDirectoryLocation(directory);
626 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
627 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
631 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
633 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
634 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
635 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
639 const EmptyValue = withStyles(styles)(
640 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
643 const ImagePlaceholder = withStyles(styles)(
644 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>