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.greyL,
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,
129 color: theme.customs.colors.greyD,
134 maxHeight: `calc(100% - ${theme.spacing.unit * 4.5}px)`,
140 verticalAlign: 'bottom',
141 paddingBottom: '10px',
144 paddingRight: '25px',
149 alignItems: 'flex-start',
150 flexDirection: 'column',
153 color: theme.palette.primary.main,
154 textDecoration: 'none',
155 overflowWrap: 'break-word',
161 color: theme.palette.primary.main,
162 textDecoration: 'none',
163 overflowWrap: 'break-word',
170 marginBottom: theme.spacing.unit,
185 verticalAlign: 'top',
186 position: 'relative',
190 color: theme.customs.colors.grey700,
194 borderBottom: 'none',
206 alignItems: 'center',
207 justifyContent: 'center',
208 backgroundColor: '#cecece',
209 borderRadius: '10px',
212 verticalAlign: 'bottom',
219 export enum ProcessIOCardType {
223 export interface ProcessIOCardDataProps {
225 label: ProcessIOCardType;
226 params: ProcessIOParameter[] | null;
228 mounts?: InputCollectionMount[];
230 showParams?: boolean;
233 export interface ProcessIOCardActionProps {
234 navigateTo: (uuid: string) => void;
237 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
238 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
241 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
243 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
244 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel,
245 doUnMaximizePanel, panelMaximized, panelName, process, navigateTo, showParams }: ProcessIOCardProps) => {
246 const [mainProcTabState, setMainProcTabState] = useState(0);
247 const [subProcTabState, setSubProcTabState] = useState(0);
248 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
249 setMainProcTabState(value);
251 const handleSubProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
252 setSubProcTabState(value);
255 const [showImagePreview, setShowImagePreview] = useState(false);
257 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
258 const mainProcess = !(process && process!.containerRequest.requestingContainerUuid);
260 const loading = raw === null || raw === undefined || params === null;
261 const hasRaw = !!(raw && Object.keys(raw).length > 0);
262 const hasParams = !!(params && params.length > 0);
265 const hasInputMounts = !!(label === ProcessIOCardType.INPUT && mounts && mounts.length);
266 const hasOutputCollecton = !!(label === ProcessIOCardType.OUTPUT && outputUuid);
268 return <Card className={classes.card} data-cy="process-io-card">
270 className={classes.header}
272 content: classes.title,
273 avatar: classes.avatar,
275 avatar={<PanelIcon className={classes.iconHeader} />}
277 <Typography noWrap variant='h6' color='inherit'>
283 {mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
284 <IconButton data-cy="io-preview-image-toggle" onClick={() => { setShowImagePreview(!showImagePreview) }}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
286 {doUnMaximizePanel && panelMaximized &&
287 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
288 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
290 {doMaximizePanel && !panelMaximized &&
291 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
292 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
295 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
296 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
300 <CardContent className={classes.content}>
301 {(mainProcess || showParams) ?
303 {/* raw is undefined until params are loaded */}
304 {loading && <Grid container item alignItems='center' justify='center'>
307 {/* Once loaded, either raw or params may still be empty
308 * Raw when all params are empty
309 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
311 {(!loading && (hasRaw || hasParams)) &&
313 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
314 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
315 {hasParams && <Tab label="Parameters" />}
316 {!showParams && <Tab label="JSON" />}
318 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
319 <ProcessIOPreview data={params} showImagePreview={showImagePreview} valueLabel={showParams ? "Default value" : "Value"} />
321 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
322 <ProcessIORaw data={raw} />
325 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
326 <DefaultView messages={["No parameters found"]} />
331 {loading && <Grid container item alignItems='center' justify='center'>
334 {!loading && (hasInputMounts || hasOutputCollecton || hasRaw) ?
336 <Tabs value={subProcTabState} onChange={handleSubProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
337 {hasInputMounts && <Tab label="Collections" />}
338 {hasOutputCollecton && <Tab label="Collection" />}
341 <div className={classes.tableWrapper}>
342 {subProcTabState === 0 && hasInputMounts && <ProcessInputMounts mounts={mounts || []} />}
343 {subProcTabState === 0 && hasOutputCollecton && <>
344 {outputUuid && <Typography className={classes.collectionLink}>
345 Output Collection: <MuiLink className={classes.keepLink} onClick={() => { navigateTo(outputUuid || "") }}>
347 </MuiLink></Typography>}
348 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
350 {(subProcTabState === 1 || (!hasInputMounts && !hasOutputCollecton)) && <div className={classes.tableWrapper}>
351 <ProcessIORaw data={raw} />
355 <Grid container item alignItems='center' justify='center'>
356 <DefaultView messages={["No data to display"]} />
366 export type ProcessIOValue = {
367 display: ReactElement<any, any>;
369 collection?: ReactElement<any, any>;
373 export type ProcessIOParameter = {
376 value: ProcessIOValue[];
379 interface ProcessIOPreviewDataProps {
380 data: ProcessIOParameter[];
381 showImagePreview: boolean;
385 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
387 const ProcessIOPreview = withStyles(styles)(
388 ({ classes, data, showImagePreview, valueLabel }: ProcessIOPreviewProps) => {
389 const showLabel = data.some((param: ProcessIOParameter) => param.label);
390 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
393 <TableCell>Name</TableCell>
394 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
395 <TableCell>{valueLabel}</TableCell>
396 <TableCell>Collection</TableCell>
400 {data.map((param: ProcessIOParameter) => {
401 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
402 const rest = param.value.slice(1);
403 const mainRowClasses = {
404 [classes.noBorderRow]: (rest.length > 0),
407 return <React.Fragment key={param.id}>
408 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
412 {showLabel && <TableCell >{param.label}</TableCell>}
414 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
416 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
417 <Typography className={classes.paramValue}>
418 {firstVal?.collection}
422 {rest.map((val, i) => {
424 [classes.noBorderRow]: (i < rest.length - 1),
425 [classes.secondaryRow]: val.secondary,
427 return <TableRow className={classNames(rowClasses)} key={i}>
429 {showLabel && <TableCell />}
431 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
433 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
434 <Typography className={classes.paramValue}>
446 interface ProcessValuePreviewProps {
447 value: ProcessIOValue;
448 showImagePreview: boolean;
451 const ProcessValuePreview = withStyles(styles)(
452 ({ value, showImagePreview, classes }: ProcessValuePreviewProps & WithStyles<CssRules>) =>
453 <Typography className={classes.paramValue}>
454 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
455 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
456 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
462 interface ProcessIORawDataProps {
463 data: ProcessIOParameter[];
466 const ProcessIORaw = withStyles(styles)(
467 ({ data }: ProcessIORawDataProps) =>
468 <Paper elevation={0}>
469 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
473 interface ProcessInputMountsDataProps {
474 mounts: InputCollectionMount[];
477 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
479 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
481 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
482 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
485 <TableCell>Path</TableCell>
486 <TableCell>Portable Data Hash</TableCell>
490 {mounts.map(mount => (
491 <TableRow key={mount.path}>
492 <TableCell><pre>{mount.path}</pre></TableCell>
494 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
502 type FileWithSecondaryFiles = {
503 secondaryFiles: File[];
506 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
508 case isPrimitiveOfType(input, CWLType.BOOLEAN):
509 const boolValue = (input as BooleanCommandInputParameter).value;
510 return boolValue !== undefined &&
511 !(Array.isArray(boolValue) && boolValue.length === 0) ?
512 [{ display: renderPrimitiveValue(boolValue, false) }] :
513 [{ display: <EmptyValue /> }];
515 case isPrimitiveOfType(input, CWLType.INT):
516 case isPrimitiveOfType(input, CWLType.LONG):
517 const intValue = (input as IntCommandInputParameter).value;
518 return intValue !== undefined &&
519 // Missing values are empty array
520 !(Array.isArray(intValue) && intValue.length === 0) ?
521 [{ display: renderPrimitiveValue(intValue, false) }]
522 : [{ display: <EmptyValue /> }];
524 case isPrimitiveOfType(input, CWLType.FLOAT):
525 case isPrimitiveOfType(input, CWLType.DOUBLE):
526 const floatValue = (input as FloatCommandInputParameter).value;
527 return floatValue !== undefined &&
528 !(Array.isArray(floatValue) && floatValue.length === 0) ?
529 [{ display: renderPrimitiveValue(floatValue, false) }] :
530 [{ display: <EmptyValue /> }];
532 case isPrimitiveOfType(input, CWLType.STRING):
533 const stringValue = (input as StringCommandInputParameter).value || undefined;
534 return stringValue !== undefined &&
535 !(Array.isArray(stringValue) && stringValue.length === 0) ?
536 [{ display: renderPrimitiveValue(stringValue, false) }] :
537 [{ display: <EmptyValue /> }];
539 case isPrimitiveOfType(input, CWLType.FILE):
540 const mainFile = (input as FileCommandInputParameter).value;
541 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
542 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
544 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
547 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
548 return files.length ?
549 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
550 [{ display: <EmptyValue /> }];
552 case isPrimitiveOfType(input, CWLType.DIRECTORY):
553 const directory = (input as DirectoryCommandInputParameter).value;
554 return directory !== undefined &&
555 !(Array.isArray(directory) && directory.length === 0) ?
556 [directoryToProcessIOValue(directory, auth, pdh)] :
557 [{ display: <EmptyValue /> }];
559 case typeof input.type === 'object' &&
560 !(input.type instanceof Array) &&
561 input.type.type === 'enum':
562 const enumValue = (input as EnumCommandInputParameter).value;
563 return enumValue !== undefined && enumValue ?
564 [{ display: <pre>{enumValue}</pre> }] :
565 [{ display: <EmptyValue /> }];
567 case isArrayOfType(input, CWLType.STRING):
568 const strArray = (input as StringArrayCommandInputParameter).value || [];
569 return strArray.length ?
570 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
571 [{ display: <EmptyValue /> }];
573 case isArrayOfType(input, CWLType.INT):
574 case isArrayOfType(input, CWLType.LONG):
575 const intArray = (input as IntArrayCommandInputParameter).value || [];
576 return intArray.length ?
577 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
578 [{ display: <EmptyValue /> }];
580 case isArrayOfType(input, CWLType.FLOAT):
581 case isArrayOfType(input, CWLType.DOUBLE):
582 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
583 return floatArray.length ?
584 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
585 [{ display: <EmptyValue /> }];
587 case isArrayOfType(input, CWLType.FILE):
588 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
589 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
591 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
592 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
593 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
595 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
596 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
597 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
599 // Reduce each mainFile/secondaryFile group into single array preserving ordering
600 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
602 return fileArrayValues.length ?
604 [{ display: <EmptyValue /> }];
606 case isArrayOfType(input, CWLType.DIRECTORY):
607 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
608 return directories.length ?
609 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
610 [{ display: <EmptyValue /> }];
613 return [{ display: <UnsupportedValue /> }];
617 const renderPrimitiveValue = (value: any, asChip: boolean) => {
618 const isObject = typeof value === 'object';
620 return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
622 return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
627 * @returns keep url without keep: prefix
629 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
630 const isKeepUrl = file.location?.startsWith('keep:') || false;
631 const keepUrl = isKeepUrl ?
632 file.location?.replace('keep:', '') :
633 pdh ? `${pdh}/${file.location}` : file.location;
634 return keepUrl || '';
637 interface KeepUrlProps {
639 res: File | Directory;
643 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
644 const keepUrl = getKeepUrl(res, pdh);
645 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
648 const KeepUrlBase = withStyles(styles)(({ auth, res, pdh, classes }: KeepUrlProps & WithStyles<CssRules>) => {
649 const pdhUrl = getResourcePdhUrl(res, pdh);
650 // Passing a pdh always returns a relative wb2 collection url
651 const pdhWbPath = getNavUrl(pdhUrl, auth);
652 return pdhUrl && pdhWbPath ?
653 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
657 const KeepUrlPath = withStyles(styles)(({ auth, res, pdh, classes }: KeepUrlProps & WithStyles<CssRules>) => {
658 const keepUrl = getKeepUrl(res, pdh);
659 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
660 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
662 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
663 return keepUrlPathNav ?
664 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
668 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
669 let keepUrl = getKeepUrl(file, pdh);
670 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
673 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
674 const keepUrl = getKeepUrl(file, pdh);
675 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
678 const isFileImage = (basename?: string): boolean => {
679 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
682 const isFileUrl = (location?: string): boolean => (
683 !!location && !KEEP_URL_REGEX.exec(location) &&
684 (location.startsWith("http://") || location.startsWith("https://"))
687 const normalizeDirectoryLocation = (directory: Directory): Directory => {
688 if (!directory.location) {
693 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
697 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
698 if (isExternalValue(directory)) { return { display: <UnsupportedValue /> } }
700 const normalizedDirectory = normalizeDirectoryLocation(directory);
702 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh} />,
703 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh} />,
707 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
708 if (isExternalValue(file)) { return { display: <UnsupportedValue /> } }
710 if (isFileUrl(file.location)) {
712 display: <MuiLink href={file.location} target="_blank">{file.location}</MuiLink>,
717 const resourcePdh = getResourcePdhUrl(file, pdh);
719 display: <KeepUrlPath auth={auth} res={file} pdh={pdh} />,
721 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
722 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh} /> : <></>,
726 const isExternalValue = (val: any) =>
727 Object.keys(val).includes('$import') ||
728 Object.keys(val).includes('$include')
730 export const EmptyValue = withStyles(styles)(
731 ({ classes }: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
734 const UnsupportedValue = withStyles(styles)(
735 ({ classes }: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
738 const UnsupportedValueChip = withStyles(styles)(
739 ({ classes }: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
742 const ImagePlaceholder = withStyles(styles)(
743 ({ classes }: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>