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[];
232 export interface ProcessIOCardActionProps {
233 navigateTo: (uuid: string) => void;
236 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
237 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
240 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
242 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
243 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, doUnMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
244 const [mainProcTabState, setMainProcTabState] = useState(0);
245 const [subProcTabState, setSubProcTabState] = useState(0);
246 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
247 setMainProcTabState(value);
249 const handleSubProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
250 setSubProcTabState(value);
253 const [showImagePreview, setShowImagePreview] = useState(false);
255 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
256 const mainProcess = !process.containerRequest.requestingContainerUuid;
258 const loading = raw === null || raw === undefined || params === null;
259 const hasRaw = !!(raw && Object.keys(raw).length > 0);
260 const hasParams = !!(params && params.length > 0);
263 const hasInputMounts = !!(label === ProcessIOCardType.INPUT && mounts && mounts.length);
264 const hasOutputCollecton = !!(label === ProcessIOCardType.OUTPUT && outputUuid);
266 return <Card className={classes.card} data-cy="process-io-card">
268 className={classes.header}
270 content: classes.title,
271 avatar: classes.avatar,
273 avatar={<PanelIcon className={classes.iconHeader} />}
275 <Typography noWrap variant='h6' color='inherit'>
281 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
282 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
284 { doUnMaximizePanel && panelMaximized &&
285 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
286 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
288 { doMaximizePanel && !panelMaximized &&
289 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
290 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
293 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
294 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
298 <CardContent className={classes.content}>
301 {/* raw is undefined until params are loaded */}
302 {loading && <Grid container item alignItems='center' justify='center'>
305 {/* Once loaded, either raw or params may still be empty
306 * Raw when all params are empty
307 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
309 {(!loading && (hasRaw || hasParams)) &&
311 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
312 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
313 {hasParams && <Tab label="Parameters" />}
316 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
317 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
319 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
320 <ProcessIORaw data={raw} />
323 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
324 <DefaultView messages={["No parameters found"]} />
329 {loading && <Grid container item alignItems='center' justify='center'>
332 {!loading && (hasInputMounts || hasOutputCollecton || hasRaw) ?
334 <Tabs value={subProcTabState} onChange={handleSubProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
335 {hasInputMounts && <Tab label="Collections" />}
336 {hasOutputCollecton && <Tab label="Collection" />}
339 <div className={classes.tableWrapper}>
340 {subProcTabState === 0 && hasInputMounts && <ProcessInputMounts mounts={mounts || []} />}
341 {subProcTabState === 0 && hasOutputCollecton && <>
342 {outputUuid && <Typography className={classes.collectionLink}>
343 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
345 </MuiLink></Typography>}
346 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
348 {(subProcTabState === 1 || (!hasInputMounts && !hasOutputCollecton)) && <div className={classes.tableWrapper}>
349 <ProcessIORaw data={raw} />
353 <Grid container item alignItems='center' justify='center'>
354 <DefaultView messages={["No data to display"]} />
364 export type ProcessIOValue = {
365 display: ReactElement<any, any>;
367 collection?: ReactElement<any, any>;
371 export type ProcessIOParameter = {
374 value: ProcessIOValue[];
377 interface ProcessIOPreviewDataProps {
378 data: ProcessIOParameter[];
379 showImagePreview: boolean;
382 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
384 const ProcessIOPreview = withStyles(styles)(
385 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
386 const showLabel = data.some((param: ProcessIOParameter) => param.label);
387 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
390 <TableCell>Name</TableCell>
391 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
392 <TableCell>Value</TableCell>
393 <TableCell>Collection</TableCell>
397 {data.map((param: ProcessIOParameter) => {
398 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
399 const rest = param.value.slice(1);
400 const mainRowClasses = {
401 [classes.noBorderRow]: (rest.length > 0),
405 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
409 {showLabel && <TableCell >{param.label}</TableCell>}
411 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
413 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
414 <Typography className={classes.paramValue}>
415 {firstVal?.collection}
419 {rest.map((val, i) => {
421 [classes.noBorderRow]: (i < rest.length-1),
422 [classes.secondaryRow]: val.secondary,
424 return <TableRow className={classNames(rowClasses)}>
426 {showLabel && <TableCell />}
428 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
430 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
431 <Typography className={classes.paramValue}>
443 interface ProcessValuePreviewProps {
444 value: ProcessIOValue;
445 showImagePreview: boolean;
448 const ProcessValuePreview = withStyles(styles)(
449 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
450 <Typography className={classes.paramValue}>
451 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
452 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
453 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
459 interface ProcessIORawDataProps {
460 data: ProcessIOParameter[];
463 const ProcessIORaw = withStyles(styles)(
464 ({ data }: ProcessIORawDataProps) =>
465 <Paper elevation={0}>
466 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
470 interface ProcessInputMountsDataProps {
471 mounts: InputCollectionMount[];
474 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
476 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
478 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
479 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
482 <TableCell>Path</TableCell>
483 <TableCell>Portable Data Hash</TableCell>
487 {mounts.map(mount => (
488 <TableRow key={mount.path}>
489 <TableCell><pre>{mount.path}</pre></TableCell>
491 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
499 type FileWithSecondaryFiles = {
500 secondaryFiles: File[];
503 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
505 case isPrimitiveOfType(input, CWLType.BOOLEAN):
506 const boolValue = (input as BooleanCommandInputParameter).value;
507 return boolValue !== undefined &&
508 !(Array.isArray(boolValue) && boolValue.length === 0) ?
509 [{display: renderPrimitiveValue(boolValue, false) }] :
510 [{display: <EmptyValue />}];
512 case isPrimitiveOfType(input, CWLType.INT):
513 case isPrimitiveOfType(input, CWLType.LONG):
514 const intValue = (input as IntCommandInputParameter).value;
515 return intValue !== undefined &&
516 // Missing values are empty array
517 !(Array.isArray(intValue) && intValue.length === 0) ?
518 [{display: renderPrimitiveValue(intValue, false) }]
519 : [{display: <EmptyValue />}];
521 case isPrimitiveOfType(input, CWLType.FLOAT):
522 case isPrimitiveOfType(input, CWLType.DOUBLE):
523 const floatValue = (input as FloatCommandInputParameter).value;
524 return floatValue !== undefined &&
525 !(Array.isArray(floatValue) && floatValue.length === 0) ?
526 [{display: renderPrimitiveValue(floatValue, false) }]:
527 [{display: <EmptyValue />}];
529 case isPrimitiveOfType(input, CWLType.STRING):
530 const stringValue = (input as StringCommandInputParameter).value || undefined;
531 return stringValue !== undefined &&
532 !(Array.isArray(stringValue) && stringValue.length === 0) ?
533 [{display: renderPrimitiveValue(stringValue, false) }] :
534 [{display: <EmptyValue />}];
536 case isPrimitiveOfType(input, CWLType.FILE):
537 const mainFile = (input as FileCommandInputParameter).value;
538 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
539 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
541 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
544 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
545 return files.length ?
546 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
547 [{display: <EmptyValue />}];
549 case isPrimitiveOfType(input, CWLType.DIRECTORY):
550 const directory = (input as DirectoryCommandInputParameter).value;
551 return directory !== undefined &&
552 !(Array.isArray(directory) && directory.length === 0) ?
553 [directoryToProcessIOValue(directory, auth, pdh)] :
554 [{display: <EmptyValue />}];
556 case typeof input.type === 'object' &&
557 !(input.type instanceof Array) &&
558 input.type.type === 'enum':
559 const enumValue = (input as EnumCommandInputParameter).value;
560 return enumValue !== undefined && enumValue ?
561 [{ display: <pre>{enumValue}</pre> }] :
562 [{display: <EmptyValue />}];
564 case isArrayOfType(input, CWLType.STRING):
565 const strArray = (input as StringArrayCommandInputParameter).value || [];
566 return strArray.length ?
567 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
568 [{display: <EmptyValue />}];
570 case isArrayOfType(input, CWLType.INT):
571 case isArrayOfType(input, CWLType.LONG):
572 const intArray = (input as IntArrayCommandInputParameter).value || [];
573 return intArray.length ?
574 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
575 [{display: <EmptyValue />}];
577 case isArrayOfType(input, CWLType.FLOAT):
578 case isArrayOfType(input, CWLType.DOUBLE):
579 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
580 return floatArray.length ?
581 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
582 [{display: <EmptyValue />}];
584 case isArrayOfType(input, CWLType.FILE):
585 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
586 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
588 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
589 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
590 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
592 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
593 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
594 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
596 // Reduce each mainFile/secondaryFile group into single array preserving ordering
597 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
599 return fileArrayValues.length ?
601 [{display: <EmptyValue />}];
603 case isArrayOfType(input, CWLType.DIRECTORY):
604 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
605 return directories.length ?
606 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
607 [{display: <EmptyValue />}];
610 return [{display: <UnsupportedValue />}];
614 const renderPrimitiveValue = (value: any, asChip: boolean) => {
615 const isObject = typeof value === 'object';
617 return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
619 return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
624 * @returns keep url without keep: prefix
626 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
627 const isKeepUrl = file.location?.startsWith('keep:') || false;
628 const keepUrl = isKeepUrl ?
629 file.location?.replace('keep:', '') :
630 pdh ? `${pdh}/${file.location}` : file.location;
631 return keepUrl || '';
634 interface KeepUrlProps {
636 res: File | Directory;
640 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
641 const keepUrl = getKeepUrl(res, pdh);
642 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
645 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
646 const pdhUrl = getResourcePdhUrl(res, pdh);
647 // Passing a pdh always returns a relative wb2 collection url
648 const pdhWbPath = getNavUrl(pdhUrl, auth);
649 return pdhUrl && pdhWbPath ?
650 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
654 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
655 const keepUrl = getKeepUrl(res, pdh);
656 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
657 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
659 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
660 return keepUrlPathNav ?
661 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
665 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
666 let keepUrl = getKeepUrl(file, pdh);
667 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
670 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
671 const keepUrl = getKeepUrl(file, pdh);
672 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
675 const isFileImage = (basename?: string): boolean => {
676 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
679 const isFileUrl = (location?: string): boolean => (
680 !!location && !KEEP_URL_REGEX.exec(location) &&
681 (location.startsWith("http://") || location.startsWith("https://"))
684 const normalizeDirectoryLocation = (directory: Directory): Directory => {
685 if (!directory.location) {
690 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
694 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
695 if (isExternalValue(directory)) {return {display: <UnsupportedValue />}}
697 const normalizedDirectory = normalizeDirectoryLocation(directory);
699 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
700 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
704 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
705 if (isExternalValue(file)) {return {display: <UnsupportedValue />}}
707 if (isFileUrl(file.location)) {
709 display: <MuiLink href={file.location} target="_blank">{file.location}</MuiLink>,
714 const resourcePdh = getResourcePdhUrl(file, pdh);
716 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
718 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
719 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
723 const isExternalValue = (val: any) =>
724 Object.keys(val).includes('$import') ||
725 Object.keys(val).includes('$include')
727 const EmptyValue = withStyles(styles)(
728 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
731 const UnsupportedValue = withStyles(styles)(
732 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
735 const UnsupportedValueChip = withStyles(styles)(
736 ({classes}: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
739 const ImagePlaceholder = withStyles(styles)(
740 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>