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 const loading = raw === undefined || params === undefined;
229 const hasRaw = !!(raw && Object.keys(raw).length > 0);
230 const hasParams = !!(params && params.length > 0);
232 return <Card className={classes.card} data-cy="process-io-card">
234 className={classes.header}
236 content: classes.title,
237 avatar: classes.avatar,
239 avatar={<PanelIcon className={classes.iconHeader} />}
241 <Typography noWrap variant='h6' color='inherit'>
247 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
248 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
250 { doMaximizePanel && !panelMaximized &&
251 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
252 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
255 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
256 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
260 <CardContent className={classes.content}>
263 {/* raw is undefined until params are loaded */}
264 {loading && <Grid container item alignItems='center' justify='center'>
267 {/* Once loaded, either raw or params may still be empty
268 * Raw when all params are empty
269 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
271 {(!loading && (hasRaw || hasParams)) &&
273 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
274 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
275 {hasParams && <Tab label="Parameters" />}
278 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
279 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
281 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
282 <ProcessIORaw data={raw} />
285 {raw && Object.keys(raw).length === 0 && <Grid container item alignItems='center' justify='center'>
286 <DefaultView messages={["No parameters found"]} />
291 {((mounts && mounts.length) || outputUuid) ?
293 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
294 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
295 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
297 <div className={classes.tableWrapper}>
298 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
299 {label === ProcessIOCardType.OUTPUT && <>
300 {outputUuid && <Typography className={classes.collectionLink}>
301 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
303 </MuiLink></Typography>}
304 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
308 <Grid container item alignItems='center' justify='center'>
309 <DefaultView messages={["No collection(s) found"]} />
319 export type ProcessIOValue = {
320 display: ReactElement<any, any>;
322 collection?: ReactElement<any, any>;
325 export type ProcessIOParameter = {
328 value: ProcessIOValue[];
331 interface ProcessIOPreviewDataProps {
332 data: ProcessIOParameter[];
333 showImagePreview: boolean;
336 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
338 const ProcessIOPreview = withStyles(styles)(
339 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
340 const showLabel = data.some((param: ProcessIOParameter) => param.label);
341 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
344 <TableCell>Name</TableCell>
345 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
346 <TableCell>Value</TableCell>
347 <TableCell>Collection</TableCell>
351 {data.map((param: ProcessIOParameter) => {
352 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
353 const rest = param.value.slice(1);
354 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
357 <TableRow className={rowClass} data-cy="process-io-param">
361 {showLabel && <TableCell >{param.label}</TableCell>}
363 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
365 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
366 <Typography className={classes.paramValue}>
367 {firstVal?.collection}
371 {rest.map((val, i) => (
372 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
374 {showLabel && <TableCell />}
376 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
378 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
379 <Typography className={classes.paramValue}>
391 interface ProcessValuePreviewProps {
392 value: ProcessIOValue;
393 showImagePreview: boolean;
396 const ProcessValuePreview = withStyles(styles)(
397 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
398 <Typography className={classes.paramValue}>
399 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
400 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
401 <span className={classes.valArray}>
407 interface ProcessIORawDataProps {
408 data: ProcessIOParameter[];
411 const ProcessIORaw = withStyles(styles)(
412 ({ data }: ProcessIORawDataProps) =>
413 <Paper elevation={0}>
415 {JSON.stringify(data, null, 2)}
420 interface ProcessInputMountsDataProps {
421 mounts: InputCollectionMount[];
424 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
426 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
428 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
429 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
432 <TableCell>Path</TableCell>
433 <TableCell>Portable Data Hash</TableCell>
437 {mounts.map(mount => (
438 <TableRow key={mount.path}>
439 <TableCell><pre>{mount.path}</pre></TableCell>
441 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
449 type FileWithSecondaryFiles = {
450 secondaryFiles: File[];
453 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
455 case isPrimitiveOfType(input, CWLType.BOOLEAN):
456 const boolValue = (input as BooleanCommandInputParameter).value;
458 return boolValue !== undefined &&
459 !(Array.isArray(boolValue) && boolValue.length === 0) ?
460 [{display: <pre>{String(boolValue)}</pre> }] :
461 [{display: <EmptyValue />}];
463 case isPrimitiveOfType(input, CWLType.INT):
464 case isPrimitiveOfType(input, CWLType.LONG):
465 const intValue = (input as IntCommandInputParameter).value;
467 return intValue !== undefined &&
468 // Missing values are empty array
469 !(Array.isArray(intValue) && intValue.length === 0) ?
470 [{display: <pre>{String(intValue)}</pre> }]
471 : [{display: <EmptyValue />}];
473 case isPrimitiveOfType(input, CWLType.FLOAT):
474 case isPrimitiveOfType(input, CWLType.DOUBLE):
475 const floatValue = (input as FloatCommandInputParameter).value;
477 return floatValue !== undefined &&
478 !(Array.isArray(floatValue) && floatValue.length === 0) ?
479 [{display: <pre>{String(floatValue)}</pre> }]:
480 [{display: <EmptyValue />}];
482 case isPrimitiveOfType(input, CWLType.STRING):
483 const stringValue = (input as StringCommandInputParameter).value || undefined;
485 return stringValue !== undefined &&
486 !(Array.isArray(stringValue) && stringValue.length === 0) ?
487 [{display: <pre>{stringValue}</pre> }] :
488 [{display: <EmptyValue />}];
490 case isPrimitiveOfType(input, CWLType.FILE):
491 const mainFile = (input as FileCommandInputParameter).value;
492 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
493 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
495 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
499 return files.length ?
500 files.map(file => fileToProcessIOValue(file, auth, pdh)) :
501 [{display: <EmptyValue />}];
503 case isPrimitiveOfType(input, CWLType.DIRECTORY):
504 const directory = (input as DirectoryCommandInputParameter).value;
506 return directory !== undefined &&
507 !(Array.isArray(directory) && directory.length === 0) ?
508 [directoryToProcessIOValue(directory, auth, pdh)] :
509 [{display: <EmptyValue />}];
511 case typeof input.type === 'object' &&
512 !(input.type instanceof Array) &&
513 input.type.type === 'enum':
514 const enumValue = (input as EnumCommandInputParameter).value;
516 return enumValue !== undefined ?
517 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
518 [{display: <EmptyValue />}];
520 case isArrayOfType(input, CWLType.STRING):
521 const strArray = (input as StringArrayCommandInputParameter).value || [];
522 return strArray.length ?
523 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
524 [{display: <EmptyValue />}];
526 case isArrayOfType(input, CWLType.INT):
527 case isArrayOfType(input, CWLType.LONG):
528 const intArray = (input as IntArrayCommandInputParameter).value || [];
530 return intArray.length ?
531 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
532 [{display: <EmptyValue />}];
534 case isArrayOfType(input, CWLType.FLOAT):
535 case isArrayOfType(input, CWLType.DOUBLE):
536 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
538 return floatArray.length ?
539 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
540 [{display: <EmptyValue />}];
542 case isArrayOfType(input, CWLType.FILE):
543 const fileArrayMainFile = ((input as FileArrayCommandInputParameter).value || []);
544 const fileArraySecondaryFiles = fileArrayMainFile.map((file) => (
545 ((file as unknown) as FileWithSecondaryFiles)?.secondaryFiles || []
546 )).reduce((acc: File[], params: File[]) => (acc.concat(params)), []);
548 const fileArrayFiles = [
549 ...fileArrayMainFile,
550 ...fileArraySecondaryFiles
553 return fileArrayFiles.length ?
554 fileArrayFiles.map(file => fileToProcessIOValue(file, auth, pdh)) :
555 [{display: <EmptyValue />}];
557 case isArrayOfType(input, CWLType.DIRECTORY):
558 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
560 return directories.length ?
561 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
562 [{display: <EmptyValue />}];
570 * @returns keep url without keep: prefix
572 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
573 const isKeepUrl = file.location?.startsWith('keep:') || false;
574 const keepUrl = isKeepUrl ?
575 file.location?.replace('keep:', '') :
576 pdh ? `${pdh}/${file.location}` : file.location;
577 return keepUrl || '';
580 interface KeepUrlProps {
582 res: File | Directory;
586 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
587 const keepUrl = getKeepUrl(res, pdh);
588 const pdhUrl = keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
589 // Passing a pdh always returns a relative wb2 collection url
590 const pdhWbPath = getNavUrl(pdhUrl, auth);
591 return pdhUrl && pdhWbPath ?
592 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
596 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
597 const keepUrl = getKeepUrl(res, pdh);
598 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
599 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
601 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
602 return keepUrlPath && keepUrlPathNav ?
603 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath}</a></Tooltip> :
604 // Show No value for root collection io that lacks path part
608 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
609 let keepUrl = getKeepUrl(file, pdh);
610 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
613 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
614 const keepUrl = getKeepUrl(file, pdh);
615 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
618 const isFileImage = (basename?: string): boolean => {
619 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
622 const normalizeDirectoryLocation = (directory: Directory): Directory => {
623 if (!directory.location) {
628 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
632 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
633 const normalizedDirectory = normalizeDirectoryLocation(directory);
635 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
636 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
640 const fileToProcessIOValue = (file: File, auth: AuthState, pdh?: string): ProcessIOValue => {
642 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
643 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
644 collection: <KeepUrlBase auth={auth} res={file} pdh={pdh}/>,
648 const EmptyValue = withStyles(styles)(
649 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
652 const ImagePlaceholder = withStyles(styles)(
653 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>