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';
77 import { KEEP_URL_REGEX } from 'models/resource';
102 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
107 paddingTop: theme.spacing.unit,
111 fontSize: '1.875rem',
112 color: theme.customs.colors.green700,
115 alignSelf: 'flex-start',
116 paddingTop: theme.spacing.unit * 0.5
119 height: `calc(100% - ${theme.spacing.unit * 7}px - ${theme.spacing.unit * 1.5}px)`,
120 padding: theme.spacing.unit * 1.0,
123 paddingBottom: theme.spacing.unit * 1,
128 paddingTop: theme.spacing.unit * 0.5
132 maxHeight: `calc(100% - ${theme.spacing.unit * 4.5}px)`,
138 verticalAlign: 'bottom',
139 paddingBottom: '10px',
142 paddingRight: '25px',
147 alignItems: 'flex-start',
148 flexDirection: 'column',
151 color: theme.palette.primary.main,
152 textDecoration: 'none',
153 overflowWrap: 'break-word',
159 color: theme.palette.primary.main,
160 textDecoration: 'none',
161 overflowWrap: 'break-word',
168 marginBottom: theme.spacing.unit,
183 verticalAlign: 'top',
184 position: 'relative',
188 color: theme.customs.colors.grey500,
192 borderBottom: 'none',
204 alignItems: 'center',
205 justifyContent: 'center',
206 backgroundColor: '#cecece',
207 borderRadius: '10px',
210 verticalAlign: 'bottom',
217 export enum ProcessIOCardType {
221 export interface ProcessIOCardDataProps {
223 label: ProcessIOCardType;
224 params: ProcessIOParameter[] | null;
226 mounts?: InputCollectionMount[];
230 export interface ProcessIOCardActionProps {
231 navigateTo: (uuid: string) => void;
234 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
235 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
238 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
240 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
241 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, doUnMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
242 const [mainProcTabState, setMainProcTabState] = useState(0);
243 const [subProcTabState, setSubProcTabState] = useState(0);
244 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
245 setMainProcTabState(value);
247 const handleSubProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
248 setSubProcTabState(value);
251 const [showImagePreview, setShowImagePreview] = useState(false);
253 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
254 const mainProcess = !process.containerRequest.requestingContainerUuid;
256 const loading = raw === null || raw === undefined || params === null;
257 const hasRaw = !!(raw && Object.keys(raw).length > 0);
258 const hasParams = !!(params && params.length > 0);
261 const hasInputMounts = !!(label === ProcessIOCardType.INPUT && mounts && mounts.length);
262 const hasOutputCollecton = !!(label === ProcessIOCardType.OUTPUT && outputUuid);
264 return <Card className={classes.card} data-cy="process-io-card">
266 className={classes.header}
268 content: classes.title,
269 avatar: classes.avatar,
271 avatar={<PanelIcon className={classes.iconHeader} />}
273 <Typography noWrap variant='h6' color='inherit'>
279 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
280 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
282 { doUnMaximizePanel && panelMaximized &&
283 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
284 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
286 { doMaximizePanel && !panelMaximized &&
287 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
288 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
291 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
292 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
296 <CardContent className={classes.content}>
299 {/* raw is undefined until params are loaded */}
300 {loading && <Grid container item alignItems='center' justify='center'>
303 {/* Once loaded, either raw or params may still be empty
304 * Raw when all params are empty
305 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
307 {(!loading && (hasRaw || hasParams)) &&
309 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
310 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
311 {hasParams && <Tab label="Parameters" />}
314 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
315 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
317 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
318 <ProcessIORaw data={raw} />
321 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
322 <DefaultView messages={["No parameters found"]} />
327 {loading && <Grid container item alignItems='center' justify='center'>
330 {!loading && (hasInputMounts || hasOutputCollecton || hasRaw) ?
332 <Tabs value={subProcTabState} onChange={handleSubProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
333 {hasInputMounts && <Tab label="Collections" />}
334 {hasOutputCollecton && <Tab label="Collection" />}
337 <div className={classes.tableWrapper}>
338 {subProcTabState === 0 && hasInputMounts && <ProcessInputMounts mounts={mounts || []} />}
339 {subProcTabState === 0 && hasOutputCollecton && <>
340 {outputUuid && <Typography className={classes.collectionLink}>
341 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
343 </MuiLink></Typography>}
344 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
346 {(subProcTabState === 1 || (!hasInputMounts && !hasOutputCollecton)) && <div className={classes.tableWrapper}>
347 <ProcessIORaw data={raw} />
351 <Grid container item alignItems='center' justify='center'>
352 <DefaultView messages={["No data to display"]} />
362 export type ProcessIOValue = {
363 display: ReactElement<any, any>;
365 collection?: ReactElement<any, any>;
369 export type ProcessIOParameter = {
372 value: ProcessIOValue[];
375 interface ProcessIOPreviewDataProps {
376 data: ProcessIOParameter[];
377 showImagePreview: boolean;
380 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
382 const ProcessIOPreview = withStyles(styles)(
383 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
384 const showLabel = data.some((param: ProcessIOParameter) => param.label);
385 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
388 <TableCell>Name</TableCell>
389 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
390 <TableCell>Value</TableCell>
391 <TableCell>Collection</TableCell>
395 {data.map((param: ProcessIOParameter) => {
396 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
397 const rest = param.value.slice(1);
398 const mainRowClasses = {
399 [classes.noBorderRow]: (rest.length > 0),
403 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
407 {showLabel && <TableCell >{param.label}</TableCell>}
409 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
411 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
412 <Typography className={classes.paramValue}>
413 {firstVal?.collection}
417 {rest.map((val, i) => {
419 [classes.noBorderRow]: (i < rest.length-1),
420 [classes.secondaryRow]: val.secondary,
422 return <TableRow className={classNames(rowClasses)}>
424 {showLabel && <TableCell />}
426 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
428 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
429 <Typography className={classes.paramValue}>
441 interface ProcessValuePreviewProps {
442 value: ProcessIOValue;
443 showImagePreview: boolean;
446 const ProcessValuePreview = withStyles(styles)(
447 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
448 <Typography className={classes.paramValue}>
449 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
450 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
451 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
457 interface ProcessIORawDataProps {
458 data: ProcessIOParameter[];
461 const ProcessIORaw = withStyles(styles)(
462 ({ data }: ProcessIORawDataProps) =>
463 <Paper elevation={0}>
464 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
468 interface ProcessInputMountsDataProps {
469 mounts: InputCollectionMount[];
472 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
474 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
476 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
477 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
480 <TableCell>Path</TableCell>
481 <TableCell>Portable Data Hash</TableCell>
485 {mounts.map(mount => (
486 <TableRow key={mount.path}>
487 <TableCell><pre>{mount.path}</pre></TableCell>
489 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
497 type FileWithSecondaryFiles = {
498 secondaryFiles: File[];
501 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
503 case isPrimitiveOfType(input, CWLType.BOOLEAN):
504 const boolValue = (input as BooleanCommandInputParameter).value;
505 return boolValue !== undefined &&
506 !(Array.isArray(boolValue) && boolValue.length === 0) ?
507 [{display: renderPrimitiveValue(boolValue, false) }] :
508 [{display: <EmptyValue />}];
510 case isPrimitiveOfType(input, CWLType.INT):
511 case isPrimitiveOfType(input, CWLType.LONG):
512 const intValue = (input as IntCommandInputParameter).value;
513 return intValue !== undefined &&
514 // Missing values are empty array
515 !(Array.isArray(intValue) && intValue.length === 0) ?
516 [{display: renderPrimitiveValue(intValue, false) }]
517 : [{display: <EmptyValue />}];
519 case isPrimitiveOfType(input, CWLType.FLOAT):
520 case isPrimitiveOfType(input, CWLType.DOUBLE):
521 const floatValue = (input as FloatCommandInputParameter).value;
522 return floatValue !== undefined &&
523 !(Array.isArray(floatValue) && floatValue.length === 0) ?
524 [{display: renderPrimitiveValue(floatValue, false) }]:
525 [{display: <EmptyValue />}];
527 case isPrimitiveOfType(input, CWLType.STRING):
528 const stringValue = (input as StringCommandInputParameter).value || undefined;
529 return stringValue !== undefined &&
530 !(Array.isArray(stringValue) && stringValue.length === 0) ?
531 [{display: renderPrimitiveValue(stringValue, false) }] :
532 [{display: <EmptyValue />}];
534 case isPrimitiveOfType(input, CWLType.FILE):
535 const mainFile = (input as FileCommandInputParameter).value;
536 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
537 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
539 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
542 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
543 return files.length ?
544 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
545 [{display: <EmptyValue />}];
547 case isPrimitiveOfType(input, CWLType.DIRECTORY):
548 const directory = (input as DirectoryCommandInputParameter).value;
549 return directory !== undefined &&
550 !(Array.isArray(directory) && directory.length === 0) ?
551 [directoryToProcessIOValue(directory, auth, pdh)] :
552 [{display: <EmptyValue />}];
554 case typeof input.type === 'object' &&
555 !(input.type instanceof Array) &&
556 input.type.type === 'enum':
557 const enumValue = (input as EnumCommandInputParameter).value;
558 return enumValue !== undefined && enumValue ?
559 [{ display: <pre>{enumValue}</pre> }] :
560 [{display: <EmptyValue />}];
562 case isArrayOfType(input, CWLType.STRING):
563 const strArray = (input as StringArrayCommandInputParameter).value || [];
564 return strArray.length ?
565 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
566 [{display: <EmptyValue />}];
568 case isArrayOfType(input, CWLType.INT):
569 case isArrayOfType(input, CWLType.LONG):
570 const intArray = (input as IntArrayCommandInputParameter).value || [];
571 return intArray.length ?
572 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
573 [{display: <EmptyValue />}];
575 case isArrayOfType(input, CWLType.FLOAT):
576 case isArrayOfType(input, CWLType.DOUBLE):
577 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
578 return floatArray.length ?
579 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
580 [{display: <EmptyValue />}];
582 case isArrayOfType(input, CWLType.FILE):
583 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
584 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
586 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
587 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
588 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
590 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
591 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
592 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
594 // Reduce each mainFile/secondaryFile group into single array preserving ordering
595 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
597 return fileArrayValues.length ?
599 [{display: <EmptyValue />}];
601 case isArrayOfType(input, CWLType.DIRECTORY):
602 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
603 return directories.length ?
604 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
605 [{display: <EmptyValue />}];
608 return [{display: <UnsupportedValue />}];
612 const renderPrimitiveValue = (value: any, asChip: boolean) => {
613 const isObject = typeof value === 'object';
615 return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
617 return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
622 * @returns keep url without keep: prefix
624 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
625 const isKeepUrl = file.location?.startsWith('keep:') || false;
626 const keepUrl = isKeepUrl ?
627 file.location?.replace('keep:', '') :
628 pdh ? `${pdh}/${file.location}` : file.location;
629 return keepUrl || '';
632 interface KeepUrlProps {
634 res: File | Directory;
638 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
639 const keepUrl = getKeepUrl(res, pdh);
640 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
643 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
644 const pdhUrl = getResourcePdhUrl(res, pdh);
645 // Passing a pdh always returns a relative wb2 collection url
646 const pdhWbPath = getNavUrl(pdhUrl, auth);
647 return pdhUrl && pdhWbPath ?
648 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
652 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
653 const keepUrl = getKeepUrl(res, pdh);
654 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
655 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
657 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
658 return keepUrlPathNav ?
659 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
663 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
664 let keepUrl = getKeepUrl(file, pdh);
665 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
668 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
669 const keepUrl = getKeepUrl(file, pdh);
670 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
673 const isFileImage = (basename?: string): boolean => {
674 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
677 const isFileUrl = (location?: string): boolean => (
678 !!location && !KEEP_URL_REGEX.exec(location) &&
679 (location.startsWith("http://") || location.startsWith("https://"))
682 const normalizeDirectoryLocation = (directory: Directory): Directory => {
683 if (!directory.location) {
688 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
692 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
693 if (isExternalValue(directory)) {return {display: <UnsupportedValue />}}
695 const normalizedDirectory = normalizeDirectoryLocation(directory);
697 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
698 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
702 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
703 if (isExternalValue(file)) {return {display: <UnsupportedValue />}}
705 if (isFileUrl(file.location)) {
707 display: <MuiLink href={file.location} target="_blank">{file.location}</MuiLink>,
712 const resourcePdh = getResourcePdhUrl(file, pdh);
714 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
716 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
717 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
721 const isExternalValue = (val: any) =>
722 Object.keys(val).includes('$import') ||
723 Object.keys(val).includes('$include')
725 const EmptyValue = withStyles(styles)(
726 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
729 const UnsupportedValue = withStyles(styles)(
730 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
733 const UnsupportedValueChip = withStyles(styles)(
734 ({classes}: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
737 const ImagePlaceholder = withStyles(styles)(
738 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>