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';
38 } from 'components/icon/icon';
39 import { MPVPanelProps } from 'components/multi-panel-view/multi-panel-view';
41 BooleanCommandInputParameter,
42 CommandInputParameter,
45 DirectoryArrayCommandInputParameter,
46 DirectoryCommandInputParameter,
47 EnumCommandInputParameter,
48 FileArrayCommandInputParameter,
49 FileCommandInputParameter,
50 FloatArrayCommandInputParameter,
51 FloatCommandInputParameter,
52 IntArrayCommandInputParameter,
53 IntCommandInputParameter,
56 StringArrayCommandInputParameter,
57 StringCommandInputParameter,
58 } from "models/workflow";
59 import { CommandOutputParameter } from 'cwlts/mappings/v1.0/CommandOutputParameter';
60 import { File } from 'models/workflow';
61 import { getInlineFileUrl } from 'views-components/context-menu/actions/helpers';
62 import { AuthState } from 'store/auth/auth-reducer';
63 import mime from 'mime';
64 import { DefaultView } from 'components/default-view/default-view';
65 import { getNavUrl } from 'routes/routes';
66 import { Link as RouterLink } from 'react-router-dom';
67 import { Link as MuiLink } from '@material-ui/core';
68 import { InputCollectionMount } from 'store/processes/processes-actions';
69 import { connect } from 'react-redux';
70 import { RootState } from 'store/store';
71 import { ProcessOutputCollectionFiles } from './process-output-collection-files';
72 import { Process } from 'store/processes/process';
73 import { navigateTo } from 'store/navigation/navigation-action';
74 import classNames from 'classnames';
75 import { DefaultCodeSnippet } from 'components/default-code-snippet/default-code-snippet';
100 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
105 paddingTop: theme.spacing.unit,
109 fontSize: '1.875rem',
110 color: theme.customs.colors.green700,
113 alignSelf: 'flex-start',
114 paddingTop: theme.spacing.unit * 0.5
117 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
118 padding: theme.spacing.unit * 1.0,
121 paddingBottom: theme.spacing.unit * 1,
126 paddingTop: theme.spacing.unit * 0.5
129 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
135 verticalAlign: 'bottom',
136 paddingBottom: '10px',
139 paddingRight: '25px',
144 alignItems: 'flex-start',
145 flexDirection: 'column',
148 color: theme.palette.primary.main,
149 textDecoration: 'none',
150 overflowWrap: 'break-word',
156 color: theme.palette.primary.main,
157 textDecoration: 'none',
158 overflowWrap: 'break-word',
165 marginBottom: theme.spacing.unit,
180 verticalAlign: 'top',
181 position: 'relative',
185 color: theme.customs.colors.grey500,
189 borderBottom: 'none',
201 alignItems: 'center',
202 justifyContent: 'center',
203 backgroundColor: '#cecece',
204 borderRadius: '10px',
207 verticalAlign: 'bottom',
214 export enum ProcessIOCardType {
218 export interface ProcessIOCardDataProps {
220 label: ProcessIOCardType;
221 params: ProcessIOParameter[] | null;
223 mounts?: InputCollectionMount[];
227 export interface ProcessIOCardActionProps {
228 navigateTo: (uuid: string) => void;
231 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
232 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
235 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
237 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
238 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, doUnMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
239 const [mainProcTabState, setMainProcTabState] = useState(0);
240 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
241 setMainProcTabState(value);
244 const [showImagePreview, setShowImagePreview] = useState(false);
246 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
247 const mainProcess = !process.containerRequest.requestingContainerUuid;
249 const loading = raw === null || raw === undefined || params === null;
250 const hasRaw = !!(raw && Object.keys(raw).length > 0);
251 const hasParams = !!(params && params.length > 0);
253 return <Card className={classes.card} data-cy="process-io-card">
255 className={classes.header}
257 content: classes.title,
258 avatar: classes.avatar,
260 avatar={<PanelIcon className={classes.iconHeader} />}
262 <Typography noWrap variant='h6' color='inherit'>
268 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
269 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
271 { doUnMaximizePanel && panelMaximized &&
272 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
273 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
275 { doMaximizePanel && !panelMaximized &&
276 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
277 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
279 { doHidePanel && !panelMaximized &&
280 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
281 <IconButton onClick={doHidePanel}><CloseIcon /></IconButton>
285 <CardContent className={classes.content}>
288 {/* raw is undefined until params are loaded */}
289 {loading && <Grid container item alignItems='center' justify='center'>
292 {/* Once loaded, either raw or params may still be empty
293 * Raw when all params are empty
294 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
296 {(!loading && (hasRaw || hasParams)) &&
298 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
299 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
300 {hasParams && <Tab label="Parameters" />}
303 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
304 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
306 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
307 <ProcessIORaw data={raw} />
310 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
311 <DefaultView messages={["No parameters found"]} />
316 {((mounts && mounts.length) || outputUuid) ?
318 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
319 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
320 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
322 <div className={classes.tableWrapper}>
323 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
324 {label === ProcessIOCardType.OUTPUT && <>
325 {outputUuid && <Typography className={classes.collectionLink}>
326 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
328 </MuiLink></Typography>}
329 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
333 <Grid container item alignItems='center' justify='center'>
334 <DefaultView messages={["No collection(s) found"]} />
344 export type ProcessIOValue = {
345 display: ReactElement<any, any>;
347 collection?: ReactElement<any, any>;
351 export type ProcessIOParameter = {
354 value: ProcessIOValue[];
357 interface ProcessIOPreviewDataProps {
358 data: ProcessIOParameter[];
359 showImagePreview: boolean;
362 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
364 const ProcessIOPreview = withStyles(styles)(
365 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
366 const showLabel = data.some((param: ProcessIOParameter) => param.label);
367 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
370 <TableCell>Name</TableCell>
371 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
372 <TableCell>Value</TableCell>
373 <TableCell>Collection</TableCell>
377 {data.map((param: ProcessIOParameter) => {
378 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
379 const rest = param.value.slice(1);
380 const mainRowClasses = {
381 [classes.noBorderRow]: (rest.length > 0),
385 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
389 {showLabel && <TableCell >{param.label}</TableCell>}
391 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
393 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
394 <Typography className={classes.paramValue}>
395 {firstVal?.collection}
399 {rest.map((val, i) => {
401 [classes.noBorderRow]: (i < rest.length-1),
402 [classes.secondaryRow]: val.secondary,
404 return <TableRow className={classNames(rowClasses)}>
406 {showLabel && <TableCell />}
408 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
410 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
411 <Typography className={classes.paramValue}>
423 interface ProcessValuePreviewProps {
424 value: ProcessIOValue;
425 showImagePreview: boolean;
428 const ProcessValuePreview = withStyles(styles)(
429 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
430 <Typography className={classes.paramValue}>
431 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
432 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
433 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
439 interface ProcessIORawDataProps {
440 data: ProcessIOParameter[];
443 const ProcessIORaw = withStyles(styles)(
444 ({ data }: ProcessIORawDataProps) =>
445 <Paper elevation={0}>
446 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
450 interface ProcessInputMountsDataProps {
451 mounts: InputCollectionMount[];
454 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
456 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
458 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
459 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
462 <TableCell>Path</TableCell>
463 <TableCell>Portable Data Hash</TableCell>
467 {mounts.map(mount => (
468 <TableRow key={mount.path}>
469 <TableCell><pre>{mount.path}</pre></TableCell>
471 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
479 type FileWithSecondaryFiles = {
480 secondaryFiles: File[];
483 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
485 case isPrimitiveOfType(input, CWLType.BOOLEAN):
486 const boolValue = (input as BooleanCommandInputParameter).value;
488 return boolValue !== undefined &&
489 !(Array.isArray(boolValue) && boolValue.length === 0) ?
490 [{display: <pre>{String(boolValue)}</pre> }] :
491 [{display: <EmptyValue />}];
493 case isPrimitiveOfType(input, CWLType.INT):
494 case isPrimitiveOfType(input, CWLType.LONG):
495 const intValue = (input as IntCommandInputParameter).value;
497 return intValue !== undefined &&
498 // Missing values are empty array
499 !(Array.isArray(intValue) && intValue.length === 0) ?
500 [{display: <pre>{String(intValue)}</pre> }]
501 : [{display: <EmptyValue />}];
503 case isPrimitiveOfType(input, CWLType.FLOAT):
504 case isPrimitiveOfType(input, CWLType.DOUBLE):
505 const floatValue = (input as FloatCommandInputParameter).value;
507 return floatValue !== undefined &&
508 !(Array.isArray(floatValue) && floatValue.length === 0) ?
509 [{display: <pre>{String(floatValue)}</pre> }]:
510 [{display: <EmptyValue />}];
512 case isPrimitiveOfType(input, CWLType.STRING):
513 const stringValue = (input as StringCommandInputParameter).value || undefined;
515 return stringValue !== undefined &&
516 !(Array.isArray(stringValue) && stringValue.length === 0) ?
517 [{display: <pre>{stringValue}</pre> }] :
518 [{display: <EmptyValue />}];
520 case isPrimitiveOfType(input, CWLType.FILE):
521 const mainFile = (input as FileCommandInputParameter).value;
522 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
523 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
525 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
528 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
530 return files.length ?
531 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
532 [{display: <EmptyValue />}];
534 case isPrimitiveOfType(input, CWLType.DIRECTORY):
535 const directory = (input as DirectoryCommandInputParameter).value;
537 return directory !== undefined &&
538 !(Array.isArray(directory) && directory.length === 0) ?
539 [directoryToProcessIOValue(directory, auth, pdh)] :
540 [{display: <EmptyValue />}];
542 case typeof input.type === 'object' &&
543 !(input.type instanceof Array) &&
544 input.type.type === 'enum':
545 const enumValue = (input as EnumCommandInputParameter).value;
547 return enumValue !== undefined ?
548 [{ display: <pre>{(input as EnumCommandInputParameter).value || ''}</pre> }] :
549 [{display: <EmptyValue />}];
551 case isArrayOfType(input, CWLType.STRING):
552 const strArray = (input as StringArrayCommandInputParameter).value || [];
553 return strArray.length ?
554 [{ display: <>{((input as StringArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
555 [{display: <EmptyValue />}];
557 case isArrayOfType(input, CWLType.INT):
558 case isArrayOfType(input, CWLType.LONG):
559 const intArray = (input as IntArrayCommandInputParameter).value || [];
561 return intArray.length ?
562 [{ display: <>{((input as IntArrayCommandInputParameter).value || []).map((val) => <Chip label={val} />)}</> }] :
563 [{display: <EmptyValue />}];
565 case isArrayOfType(input, CWLType.FLOAT):
566 case isArrayOfType(input, CWLType.DOUBLE):
567 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
569 return floatArray.length ?
570 [{ display: <>{floatArray.map((val) => <Chip label={val} />)}</> }] :
571 [{display: <EmptyValue />}];
573 case isArrayOfType(input, CWLType.FILE):
574 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
575 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
577 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
578 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
579 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
581 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
582 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
583 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
585 // Reduce each mainFile/secondaryFile group into single array preserving ordering
586 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
588 return fileArrayValues.length ?
590 [{display: <EmptyValue />}];
592 case isArrayOfType(input, CWLType.DIRECTORY):
593 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
595 return directories.length ?
596 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
597 [{display: <EmptyValue />}];
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 const normalizedDirectory = normalizeDirectoryLocation(directory);
673 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
674 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
678 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
679 const resourcePdh = getResourcePdhUrl(file, pdh);
681 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
683 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
684 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
688 const EmptyValue = withStyles(styles)(
689 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
692 const ImagePlaceholder = withStyles(styles)(
693 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>