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';
39 } from 'components/icon/icon';
40 import { MPVPanelProps } from 'components/multi-panel-view/multi-panel-view';
42 BooleanCommandInputParameter,
43 CommandInputParameter,
46 DirectoryArrayCommandInputParameter,
47 DirectoryCommandInputParameter,
48 EnumCommandInputParameter,
49 FileArrayCommandInputParameter,
50 FileCommandInputParameter,
51 FloatArrayCommandInputParameter,
52 FloatCommandInputParameter,
53 IntArrayCommandInputParameter,
54 IntCommandInputParameter,
57 StringArrayCommandInputParameter,
58 StringCommandInputParameter,
59 } from "models/workflow";
60 import { CommandOutputParameter } from 'cwlts/mappings/v1.0/CommandOutputParameter';
61 import { File } from 'models/workflow';
62 import { getInlineFileUrl } from 'views-components/context-menu/actions/helpers';
63 import { AuthState } from 'store/auth/auth-reducer';
64 import mime from 'mime';
65 import { DefaultView } from 'components/default-view/default-view';
66 import { getNavUrl } from 'routes/routes';
67 import { Link as RouterLink } from 'react-router-dom';
68 import { Link as MuiLink } from '@material-ui/core';
69 import { InputCollectionMount } from 'store/processes/processes-actions';
70 import { connect } from 'react-redux';
71 import { RootState } from 'store/store';
72 import { ProcessOutputCollectionFiles } from './process-output-collection-files';
73 import { Process } from 'store/processes/process';
74 import { navigateTo } from 'store/navigation/navigation-action';
75 import classNames from 'classnames';
76 import { DefaultCodeSnippet } from 'components/default-code-snippet/default-code-snippet';
101 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
106 paddingTop: theme.spacing.unit,
110 fontSize: '1.875rem',
111 color: theme.customs.colors.green700,
114 alignSelf: 'flex-start',
115 paddingTop: theme.spacing.unit * 0.5
118 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
119 padding: theme.spacing.unit * 1.0,
122 paddingBottom: theme.spacing.unit * 1,
127 paddingTop: theme.spacing.unit * 0.5
130 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
136 verticalAlign: 'bottom',
137 paddingBottom: '10px',
140 paddingRight: '25px',
145 alignItems: 'flex-start',
146 flexDirection: 'column',
149 color: theme.palette.primary.main,
150 textDecoration: 'none',
151 overflowWrap: 'break-word',
157 color: theme.palette.primary.main,
158 textDecoration: 'none',
159 overflowWrap: 'break-word',
166 marginBottom: theme.spacing.unit,
181 verticalAlign: 'top',
182 position: 'relative',
186 color: theme.customs.colors.grey500,
190 borderBottom: 'none',
202 alignItems: 'center',
203 justifyContent: 'center',
204 backgroundColor: '#cecece',
205 borderRadius: '10px',
208 verticalAlign: 'bottom',
215 export enum ProcessIOCardType {
219 export interface ProcessIOCardDataProps {
221 label: ProcessIOCardType;
222 params: ProcessIOParameter[] | null;
224 mounts?: InputCollectionMount[];
228 export interface ProcessIOCardActionProps {
229 navigateTo: (uuid: string) => void;
232 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
233 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
236 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
238 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
239 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, doUnMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
240 const [mainProcTabState, setMainProcTabState] = useState(0);
241 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
242 setMainProcTabState(value);
245 const [showImagePreview, setShowImagePreview] = useState(false);
247 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
248 const mainProcess = !process.containerRequest.requestingContainerUuid;
250 const loading = raw === null || raw === undefined || params === null;
251 const hasRaw = !!(raw && Object.keys(raw).length > 0);
252 const hasParams = !!(params && params.length > 0);
254 return <Card className={classes.card} data-cy="process-io-card">
256 className={classes.header}
258 content: classes.title,
259 avatar: classes.avatar,
261 avatar={<PanelIcon className={classes.iconHeader} />}
263 <Typography noWrap variant='h6' color='inherit'>
269 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
270 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
272 { doUnMaximizePanel && panelMaximized &&
273 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
274 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
276 { doMaximizePanel && !panelMaximized &&
277 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
278 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
281 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
282 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
286 <CardContent className={classes.content}>
289 {/* raw is undefined until params are loaded */}
290 {loading && <Grid container item alignItems='center' justify='center'>
293 {/* Once loaded, either raw or params may still be empty
294 * Raw when all params are empty
295 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
297 {(!loading && (hasRaw || hasParams)) &&
299 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
300 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
301 {hasParams && <Tab label="Parameters" />}
304 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
305 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
307 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
308 <ProcessIORaw data={raw} />
311 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
312 <DefaultView messages={["No parameters found"]} />
317 {((mounts && mounts.length) || outputUuid) ?
319 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
320 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
321 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
323 <div className={classes.tableWrapper}>
324 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
325 {label === ProcessIOCardType.OUTPUT && <>
326 {outputUuid && <Typography className={classes.collectionLink}>
327 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
329 </MuiLink></Typography>}
330 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
334 <Grid container item alignItems='center' justify='center'>
335 <DefaultView messages={["No collection(s) found"]} />
345 export type ProcessIOValue = {
346 display: ReactElement<any, any>;
348 collection?: ReactElement<any, any>;
352 export type ProcessIOParameter = {
355 value: ProcessIOValue[];
358 interface ProcessIOPreviewDataProps {
359 data: ProcessIOParameter[];
360 showImagePreview: boolean;
363 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
365 const ProcessIOPreview = withStyles(styles)(
366 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
367 const showLabel = data.some((param: ProcessIOParameter) => param.label);
368 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
371 <TableCell>Name</TableCell>
372 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
373 <TableCell>Value</TableCell>
374 <TableCell>Collection</TableCell>
378 {data.map((param: ProcessIOParameter) => {
379 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
380 const rest = param.value.slice(1);
381 const mainRowClasses = {
382 [classes.noBorderRow]: (rest.length > 0),
386 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
390 {showLabel && <TableCell >{param.label}</TableCell>}
392 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
394 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
395 <Typography className={classes.paramValue}>
396 {firstVal?.collection}
400 {rest.map((val, i) => {
402 [classes.noBorderRow]: (i < rest.length-1),
403 [classes.secondaryRow]: val.secondary,
405 return <TableRow className={classNames(rowClasses)}>
407 {showLabel && <TableCell />}
409 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
411 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
412 <Typography className={classes.paramValue}>
424 interface ProcessValuePreviewProps {
425 value: ProcessIOValue;
426 showImagePreview: boolean;
429 const ProcessValuePreview = withStyles(styles)(
430 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
431 <Typography className={classes.paramValue}>
432 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
433 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
434 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
440 interface ProcessIORawDataProps {
441 data: ProcessIOParameter[];
444 const ProcessIORaw = withStyles(styles)(
445 ({ data }: ProcessIORawDataProps) =>
446 <Paper elevation={0}>
447 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
451 interface ProcessInputMountsDataProps {
452 mounts: InputCollectionMount[];
455 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
457 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
459 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
460 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
463 <TableCell>Path</TableCell>
464 <TableCell>Portable Data Hash</TableCell>
468 {mounts.map(mount => (
469 <TableRow key={mount.path}>
470 <TableCell><pre>{mount.path}</pre></TableCell>
472 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
480 type FileWithSecondaryFiles = {
481 secondaryFiles: File[];
484 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
486 case isPrimitiveOfType(input, CWLType.BOOLEAN):
487 const boolValue = (input as BooleanCommandInputParameter).value;
488 return boolValue !== undefined &&
489 !(Array.isArray(boolValue) && boolValue.length === 0) ?
490 [{display: renderPrimitiveValue(boolValue, false) }] :
491 [{display: <EmptyValue />}];
493 case isPrimitiveOfType(input, CWLType.INT):
494 case isPrimitiveOfType(input, CWLType.LONG):
495 const intValue = (input as IntCommandInputParameter).value;
496 return intValue !== undefined &&
497 // Missing values are empty array
498 !(Array.isArray(intValue) && intValue.length === 0) ?
499 [{display: renderPrimitiveValue(intValue, false) }]
500 : [{display: <EmptyValue />}];
502 case isPrimitiveOfType(input, CWLType.FLOAT):
503 case isPrimitiveOfType(input, CWLType.DOUBLE):
504 const floatValue = (input as FloatCommandInputParameter).value;
505 return floatValue !== undefined &&
506 !(Array.isArray(floatValue) && floatValue.length === 0) ?
507 [{display: renderPrimitiveValue(floatValue, false) }]:
508 [{display: <EmptyValue />}];
510 case isPrimitiveOfType(input, CWLType.STRING):
511 const stringValue = (input as StringCommandInputParameter).value || undefined;
512 return stringValue !== undefined &&
513 !(Array.isArray(stringValue) && stringValue.length === 0) ?
514 [{display: renderPrimitiveValue(stringValue, false) }] :
515 [{display: <EmptyValue />}];
517 case isPrimitiveOfType(input, CWLType.FILE):
518 const mainFile = (input as FileCommandInputParameter).value;
519 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
520 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
522 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
525 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
526 return files.length ?
527 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
528 [{display: <EmptyValue />}];
530 case isPrimitiveOfType(input, CWLType.DIRECTORY):
531 const directory = (input as DirectoryCommandInputParameter).value;
532 return directory !== undefined &&
533 !(Array.isArray(directory) && directory.length === 0) ?
534 [directoryToProcessIOValue(directory, auth, pdh)] :
535 [{display: <EmptyValue />}];
537 case typeof input.type === 'object' &&
538 !(input.type instanceof Array) &&
539 input.type.type === 'enum':
540 const enumValue = (input as EnumCommandInputParameter).value;
541 return enumValue !== undefined && enumValue ?
542 [{ display: <pre>{enumValue}</pre> }] :
543 [{display: <EmptyValue />}];
545 case isArrayOfType(input, CWLType.STRING):
546 const strArray = (input as StringArrayCommandInputParameter).value || [];
547 return strArray.length ?
548 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
549 [{display: <EmptyValue />}];
551 case isArrayOfType(input, CWLType.INT):
552 case isArrayOfType(input, CWLType.LONG):
553 const intArray = (input as IntArrayCommandInputParameter).value || [];
554 return intArray.length ?
555 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
556 [{display: <EmptyValue />}];
558 case isArrayOfType(input, CWLType.FLOAT):
559 case isArrayOfType(input, CWLType.DOUBLE):
560 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
561 return floatArray.length ?
562 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
563 [{display: <EmptyValue />}];
565 case isArrayOfType(input, CWLType.FILE):
566 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
567 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
569 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
570 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
571 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
573 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
574 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
575 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
577 // Reduce each mainFile/secondaryFile group into single array preserving ordering
578 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
580 return fileArrayValues.length ?
582 [{display: <EmptyValue />}];
584 case isArrayOfType(input, CWLType.DIRECTORY):
585 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
586 return directories.length ?
587 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
588 [{display: <EmptyValue />}];
591 return [{display: <UnsupportedValue />}];
595 const renderPrimitiveValue = (value: any, asChip: boolean) => {
596 const isObject = typeof value === 'object';
598 return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
600 return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
605 * @returns keep url without keep: prefix
607 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
608 const isKeepUrl = file.location?.startsWith('keep:') || false;
609 const keepUrl = isKeepUrl ?
610 file.location?.replace('keep:', '') :
611 pdh ? `${pdh}/${file.location}` : file.location;
612 return keepUrl || '';
615 interface KeepUrlProps {
617 res: File | Directory;
621 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
622 const keepUrl = getKeepUrl(res, pdh);
623 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
626 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
627 const pdhUrl = getResourcePdhUrl(res, pdh);
628 // Passing a pdh always returns a relative wb2 collection url
629 const pdhWbPath = getNavUrl(pdhUrl, auth);
630 return pdhUrl && pdhWbPath ?
631 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
635 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
636 const keepUrl = getKeepUrl(res, pdh);
637 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
638 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
640 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
641 return keepUrlPathNav ?
642 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
646 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
647 let keepUrl = getKeepUrl(file, pdh);
648 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
651 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
652 const keepUrl = getKeepUrl(file, pdh);
653 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
656 const isFileImage = (basename?: string): boolean => {
657 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
660 const normalizeDirectoryLocation = (directory: Directory): Directory => {
661 if (!directory.location) {
666 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
670 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
671 if (isExternalValue(directory)) {return {display: <UnsupportedValue />}}
673 const normalizedDirectory = normalizeDirectoryLocation(directory);
675 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
676 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
680 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
681 if (isExternalValue(file)) {return {display: <UnsupportedValue />}}
683 const resourcePdh = getResourcePdhUrl(file, pdh);
685 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
687 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
688 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
692 const isExternalValue = (val: any) =>
693 Object.keys(val).includes('$import') ||
694 Object.keys(val).includes('$include')
696 const EmptyValue = withStyles(styles)(
697 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
700 const UnsupportedValue = withStyles(styles)(
701 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
704 const UnsupportedValueChip = withStyles(styles)(
705 ({classes}: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
708 const ImagePlaceholder = withStyles(styles)(
709 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>