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';
66 import classNames from 'classnames';
90 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
95 paddingTop: theme.spacing.unit,
96 paddingBottom: theme.spacing.unit,
100 color: theme.customs.colors.green700,
103 alignSelf: 'flex-start',
104 paddingTop: theme.spacing.unit * 0.5
107 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
108 padding: theme.spacing.unit * 1.0,
109 paddingTop: theme.spacing.unit * 0.5,
111 paddingBottom: theme.spacing.unit * 1,
116 paddingTop: theme.spacing.unit * 0.5
119 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
125 verticalAlign: 'bottom',
126 paddingBottom: '10px',
129 paddingRight: '25px',
134 alignItems: 'flex-start',
135 flexDirection: 'column',
138 color: theme.palette.primary.main,
139 textDecoration: 'none',
140 overflowWrap: 'break-word',
146 color: theme.palette.primary.main,
147 textDecoration: 'none',
148 overflowWrap: 'break-word',
155 marginBottom: theme.spacing.unit,
169 color: theme.customs.colors.grey500,
173 borderBottom: 'none',
185 alignItems: 'center',
186 justifyContent: 'center',
187 backgroundColor: '#cecece',
188 borderRadius: '10px',
191 verticalAlign: 'bottom',
198 export enum ProcessIOCardType {
202 export interface ProcessIOCardDataProps {
204 label: ProcessIOCardType;
205 params?: ProcessIOParameter[];
207 mounts?: InputCollectionMount[];
211 export interface ProcessIOCardActionProps {
212 navigateTo: (uuid: string) => void;
215 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
216 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
219 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
221 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
222 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
223 const [mainProcTabState, setMainProcTabState] = useState(0);
224 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
225 setMainProcTabState(value);
228 const [showImagePreview, setShowImagePreview] = useState(false);
230 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
231 const mainProcess = !process.containerRequest.requestingContainerUuid;
233 const loading = raw === undefined || params === undefined;
234 const hasRaw = !!(raw && Object.keys(raw).length > 0);
235 const hasParams = !!(params && params.length > 0);
237 return <Card className={classes.card} data-cy="process-io-card">
239 className={classes.header}
241 content: classes.title,
242 avatar: classes.avatar,
244 avatar={<PanelIcon className={classes.iconHeader} />}
246 <Typography noWrap variant='h6' color='inherit'>
252 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
253 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
255 { doMaximizePanel && !panelMaximized &&
256 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
257 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
260 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
261 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
265 <CardContent className={classes.content}>
268 {/* raw is undefined until params are loaded */}
269 {loading && <Grid container item alignItems='center' justify='center'>
272 {/* Once loaded, either raw or params may still be empty
273 * Raw when all params are empty
274 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
276 {(!loading && (hasRaw || hasParams)) &&
278 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
279 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
280 {hasParams && <Tab label="Parameters" />}
283 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
284 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
286 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
287 <ProcessIORaw data={raw} />
290 {raw && Object.keys(raw).length === 0 && <Grid container item alignItems='center' justify='center'>
291 <DefaultView messages={["No parameters found"]} />
296 {((mounts && mounts.length) || outputUuid) ?
298 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
299 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
300 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
302 <div className={classes.tableWrapper}>
303 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
304 {label === ProcessIOCardType.OUTPUT && <>
305 {outputUuid && <Typography className={classes.collectionLink}>
306 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
308 </MuiLink></Typography>}
309 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
313 <Grid container item alignItems='center' justify='center'>
314 <DefaultView messages={["No collection(s) found"]} />
324 export type ProcessIOValue = {
325 display: ReactElement<any, any>;
327 collection?: ReactElement<any, any>;
331 export type ProcessIOParameter = {
334 value: ProcessIOValue[];
337 interface ProcessIOPreviewDataProps {
338 data: ProcessIOParameter[];
339 showImagePreview: boolean;
342 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
344 const ProcessIOPreview = withStyles(styles)(
345 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
346 const showLabel = data.some((param: ProcessIOParameter) => param.label);
347 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
350 <TableCell>Name</TableCell>
351 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
352 <TableCell>Value</TableCell>
353 <TableCell>Collection</TableCell>
357 {data.map((param: ProcessIOParameter) => {
358 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
359 const rest = param.value.slice(1);
360 const rowClass = rest.length > 0 ? classes.halfRow : undefined;
363 <TableRow className={rowClass} data-cy="process-io-param">
367 {showLabel && <TableCell >{param.label}</TableCell>}
369 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
371 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
372 <Typography className={classes.paramValue}>
373 {firstVal?.collection}
377 {rest.map((val, i) => (
378 <TableRow className={(i < rest.length-1) ? rowClass : undefined}>
380 {showLabel && <TableCell />}
382 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
384 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
385 <Typography className={classes.paramValue}>
397 interface ProcessValuePreviewProps {
398 value: ProcessIOValue;
399 showImagePreview: boolean;
402 const ProcessValuePreview = withStyles(styles)(
403 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
404 <Typography className={classes.paramValue}>
405 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
406 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
407 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
413 interface ProcessIORawDataProps {
414 data: ProcessIOParameter[];
417 const ProcessIORaw = withStyles(styles)(
418 ({ data }: ProcessIORawDataProps) =>
419 <Paper elevation={0}>
421 {JSON.stringify(data, null, 2)}
426 interface ProcessInputMountsDataProps {
427 mounts: InputCollectionMount[];
430 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
432 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
434 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
435 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
438 <TableCell>Path</TableCell>
439 <TableCell>Portable Data Hash</TableCell>
443 {mounts.map(mount => (
444 <TableRow key={mount.path}>
445 <TableCell><pre>{mount.path}</pre></TableCell>
447 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
455 type FileWithSecondaryFiles = {
456 secondaryFiles: File[];
459 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
461 case isPrimitiveOfType(input, CWLType.BOOLEAN):
462 const boolValue = (input as BooleanCommandInputParameter).value;
464 return boolValue !== undefined &&
465 !(Array.isArray(boolValue) && boolValue.length === 0) ?
466 [{display: <pre>{String(boolValue)}</pre> }] :
467 [{display: <EmptyValue />}];
469 case isPrimitiveOfType(input, CWLType.INT):
470 case isPrimitiveOfType(input, CWLType.LONG):
471 const intValue = (input as IntCommandInputParameter).value;
473 return intValue !== undefined &&
474 // Missing values are empty array
475 !(Array.isArray(intValue) && intValue.length === 0) ?
476 [{display: <pre>{String(intValue)}</pre> }]
477 : [{display: <EmptyValue />}];
479 case isPrimitiveOfType(input, CWLType.FLOAT):
480 case isPrimitiveOfType(input, CWLType.DOUBLE):
481 const floatValue = (input as FloatCommandInputParameter).value;
483 return floatValue !== undefined &&
484 !(Array.isArray(floatValue) && floatValue.length === 0) ?
485 [{display: <pre>{String(floatValue)}</pre> }]:
486 [{display: <EmptyValue />}];
488 case isPrimitiveOfType(input, CWLType.STRING):
489 const stringValue = (input as StringCommandInputParameter).value || undefined;
491 return stringValue !== undefined &&
492 !(Array.isArray(stringValue) && stringValue.length === 0) ?
493 [{display: <pre>{stringValue}</pre> }] :
494 [{display: <EmptyValue />}];
496 case isPrimitiveOfType(input, CWLType.FILE):
497 const mainFile = (input as FileCommandInputParameter).value;
498 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
499 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
501 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
504 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
506 return files.length ?
507 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
508 [{display: <EmptyValue />}];
510 case isPrimitiveOfType(input, CWLType.DIRECTORY):
511 const directory = (input as DirectoryCommandInputParameter).value;
513 return directory !== undefined &&
514 !(Array.isArray(directory) && directory.length === 0) ?
515 [directoryToProcessIOValue(directory, auth, pdh)] :
516 [{display: <EmptyValue />}];
518 case typeof input.type === 'object' &&
519 !(input.type instanceof Array) &&
520 input.type.type === 'enum':
521 const enumValue = (input as EnumCommandInputParameter).value;
523 return enumValue !== undefined ?
524 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
525 [{display: <EmptyValue />}];
527 case isArrayOfType(input, CWLType.STRING):
528 const strArray = (input as StringArrayCommandInputParameter).value || [];
529 return strArray.length ?
530 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
531 [{display: <EmptyValue />}];
533 case isArrayOfType(input, CWLType.INT):
534 case isArrayOfType(input, CWLType.LONG):
535 const intArray = (input as IntArrayCommandInputParameter).value || [];
537 return intArray.length ?
538 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
539 [{display: <EmptyValue />}];
541 case isArrayOfType(input, CWLType.FLOAT):
542 case isArrayOfType(input, CWLType.DOUBLE):
543 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
545 return floatArray.length ?
546 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
547 [{display: <EmptyValue />}];
549 case isArrayOfType(input, CWLType.FILE):
550 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
551 const firstMainFilePdh = fileArrayMainFiles.length > 0 ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
553 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
554 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
555 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
557 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
558 fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : ""),
559 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
561 // Reduce each mainFile/secondaryFile group into single array preserving ordering
562 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
564 return fileArrayValues.length ?
566 [{display: <EmptyValue />}];
568 case isArrayOfType(input, CWLType.DIRECTORY):
569 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
571 return directories.length ?
572 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
573 [{display: <EmptyValue />}];
581 * @returns keep url without keep: prefix
583 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
584 const isKeepUrl = file.location?.startsWith('keep:') || false;
585 const keepUrl = isKeepUrl ?
586 file.location?.replace('keep:', '') :
587 pdh ? `${pdh}/${file.location}` : file.location;
588 return keepUrl || '';
591 interface KeepUrlProps {
593 res: File | Directory;
597 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
598 const keepUrl = getKeepUrl(res, pdh);
599 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
602 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
603 const pdhUrl = getResourcePdhUrl(res, pdh);
604 // Passing a pdh always returns a relative wb2 collection url
605 const pdhWbPath = getNavUrl(pdhUrl, auth);
606 return pdhUrl && pdhWbPath ?
607 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
611 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
612 const keepUrl = getKeepUrl(res, pdh);
613 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
614 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
616 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
617 return keepUrlPath && keepUrlPathNav ?
618 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath}</a></Tooltip> :
619 // Show No value for root collection io that lacks path part
623 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
624 let keepUrl = getKeepUrl(file, pdh);
625 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
628 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
629 const keepUrl = getKeepUrl(file, pdh);
630 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
633 const isFileImage = (basename?: string): boolean => {
634 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
637 const normalizeDirectoryLocation = (directory: Directory): Directory => {
638 if (!directory.location) {
643 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
647 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
648 const normalizedDirectory = normalizeDirectoryLocation(directory);
650 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
651 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
655 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
656 const resourcePdh = getResourcePdhUrl(file, pdh);
658 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
660 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
661 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
665 const EmptyValue = withStyles(styles)(
666 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
669 const ImagePlaceholder = withStyles(styles)(
670 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>