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
131 height: `calc(100% - ${theme.spacing.unit * 6}px)`,
137 verticalAlign: 'bottom',
138 paddingBottom: '10px',
141 paddingRight: '25px',
146 alignItems: 'flex-start',
147 flexDirection: 'column',
150 color: theme.palette.primary.main,
151 textDecoration: 'none',
152 overflowWrap: 'break-word',
158 color: theme.palette.primary.main,
159 textDecoration: 'none',
160 overflowWrap: 'break-word',
167 marginBottom: theme.spacing.unit,
182 verticalAlign: 'top',
183 position: 'relative',
187 color: theme.customs.colors.grey500,
191 borderBottom: 'none',
203 alignItems: 'center',
204 justifyContent: 'center',
205 backgroundColor: '#cecece',
206 borderRadius: '10px',
209 verticalAlign: 'bottom',
216 export enum ProcessIOCardType {
220 export interface ProcessIOCardDataProps {
222 label: ProcessIOCardType;
223 params: ProcessIOParameter[] | null;
225 mounts?: InputCollectionMount[];
229 export interface ProcessIOCardActionProps {
230 navigateTo: (uuid: string) => void;
233 const mapDispatchToProps = (dispatch: Dispatch): ProcessIOCardActionProps => ({
234 navigateTo: (uuid) => dispatch<any>(navigateTo(uuid)),
237 type ProcessIOCardProps = ProcessIOCardDataProps & ProcessIOCardActionProps & WithStyles<CssRules> & MPVPanelProps;
239 export const ProcessIOCard = withStyles(styles)(connect(null, mapDispatchToProps)(
240 ({ classes, label, params, raw, mounts, outputUuid, doHidePanel, doMaximizePanel, doUnMaximizePanel, panelMaximized, panelName, process, navigateTo }: ProcessIOCardProps) => {
241 const [mainProcTabState, setMainProcTabState] = useState(0);
242 const handleMainProcTabChange = (event: React.MouseEvent<HTMLElement>, value: number) => {
243 setMainProcTabState(value);
246 const [showImagePreview, setShowImagePreview] = useState(false);
248 const PanelIcon = label === ProcessIOCardType.INPUT ? InputIcon : OutputIcon;
249 const mainProcess = !process.containerRequest.requestingContainerUuid;
251 const loading = raw === null || raw === undefined || params === null;
252 const hasRaw = !!(raw && Object.keys(raw).length > 0);
253 const hasParams = !!(params && params.length > 0);
255 return <Card className={classes.card} data-cy="process-io-card">
257 className={classes.header}
259 content: classes.title,
260 avatar: classes.avatar,
262 avatar={<PanelIcon className={classes.iconHeader} />}
264 <Typography noWrap variant='h6' color='inherit'>
270 { mainProcess && <Tooltip title={"Toggle Image Preview"} disableFocusListener>
271 <IconButton data-cy="io-preview-image-toggle" onClick={() =>{setShowImagePreview(!showImagePreview)}}>{showImagePreview ? <ImageIcon /> : <ImageOffIcon />}</IconButton>
273 { doUnMaximizePanel && panelMaximized &&
274 <Tooltip title={`Unmaximize ${panelName || 'panel'}`} disableFocusListener>
275 <IconButton onClick={doUnMaximizePanel}><UnMaximizeIcon /></IconButton>
277 { doMaximizePanel && !panelMaximized &&
278 <Tooltip title={`Maximize ${panelName || 'panel'}`} disableFocusListener>
279 <IconButton onClick={doMaximizePanel}><MaximizeIcon /></IconButton>
282 <Tooltip title={`Close ${panelName || 'panel'}`} disableFocusListener>
283 <IconButton disabled={panelMaximized} onClick={doHidePanel}><CloseIcon /></IconButton>
287 <CardContent className={classes.content}>
290 {/* raw is undefined until params are loaded */}
291 {loading && <Grid container item alignItems='center' justify='center'>
294 {/* Once loaded, either raw or params may still be empty
295 * Raw when all params are empty
296 * Params when raw is provided by containerRequest properties but workflow mount is absent for preview
298 {(!loading && (hasRaw || hasParams)) &&
300 <Tabs value={mainProcTabState} onChange={handleMainProcTabChange} variant="fullWidth" className={classes.symmetricTabs}>
301 {/* params will be empty on processes without workflow definitions in mounts, so we only show raw */}
302 {hasParams && <Tab label="Parameters" />}
305 {(mainProcTabState === 0 && params && hasParams) && <div className={classes.tableWrapper}>
306 <ProcessIOPreview data={params} showImagePreview={showImagePreview} />
308 {(mainProcTabState === 1 || !hasParams) && <div className={classes.tableWrapper}>
309 <ProcessIORaw data={raw} />
312 {!loading && !hasRaw && !hasParams && <Grid container item alignItems='center' justify='center'>
313 <DefaultView messages={["No parameters found"]} />
318 {((mounts && mounts.length) || outputUuid) ?
320 <Tabs value={0} variant="fullWidth" className={classes.symmetricTabs}>
321 {label === ProcessIOCardType.INPUT && <Tab label="Collections" />}
322 {label === ProcessIOCardType.OUTPUT && <Tab label="Collection" />}
324 <div className={classes.tableWrapper}>
325 {label === ProcessIOCardType.INPUT && <ProcessInputMounts mounts={mounts || []} />}
326 {label === ProcessIOCardType.OUTPUT && <>
327 {outputUuid && <Typography className={classes.collectionLink}>
328 Output Collection: <MuiLink className={classes.keepLink} onClick={() => {navigateTo(outputUuid || "")}}>
330 </MuiLink></Typography>}
331 <ProcessOutputCollectionFiles isWritable={false} currentItemUuid={outputUuid} />
335 <Grid container item alignItems='center' justify='center'>
336 <DefaultView messages={["No collection(s) found"]} />
346 export type ProcessIOValue = {
347 display: ReactElement<any, any>;
349 collection?: ReactElement<any, any>;
353 export type ProcessIOParameter = {
356 value: ProcessIOValue[];
359 interface ProcessIOPreviewDataProps {
360 data: ProcessIOParameter[];
361 showImagePreview: boolean;
364 type ProcessIOPreviewProps = ProcessIOPreviewDataProps & WithStyles<CssRules>;
366 const ProcessIOPreview = withStyles(styles)(
367 ({ classes, data, showImagePreview }: ProcessIOPreviewProps) => {
368 const showLabel = data.some((param: ProcessIOParameter) => param.label);
369 return <Table className={classes.tableRoot} aria-label="Process IO Preview">
372 <TableCell>Name</TableCell>
373 {showLabel && <TableCell className={classes.labelColumn}>Label</TableCell>}
374 <TableCell>Value</TableCell>
375 <TableCell>Collection</TableCell>
379 {data.map((param: ProcessIOParameter) => {
380 const firstVal = param.value.length > 0 ? param.value[0] : undefined;
381 const rest = param.value.slice(1);
382 const mainRowClasses = {
383 [classes.noBorderRow]: (rest.length > 0),
387 <TableRow className={classNames(mainRowClasses)} data-cy="process-io-param">
391 {showLabel && <TableCell >{param.label}</TableCell>}
393 {firstVal && <ProcessValuePreview value={firstVal} showImagePreview={showImagePreview} />}
395 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
396 <Typography className={classes.paramValue}>
397 {firstVal?.collection}
401 {rest.map((val, i) => {
403 [classes.noBorderRow]: (i < rest.length-1),
404 [classes.secondaryRow]: val.secondary,
406 return <TableRow className={classNames(rowClasses)}>
408 {showLabel && <TableCell />}
410 <ProcessValuePreview value={val} showImagePreview={showImagePreview} />
412 <TableCell className={firstVal?.imageUrl ? classes.rowWithPreview : undefined}>
413 <Typography className={classes.paramValue}>
425 interface ProcessValuePreviewProps {
426 value: ProcessIOValue;
427 showImagePreview: boolean;
430 const ProcessValuePreview = withStyles(styles)(
431 ({value, showImagePreview, classes}: ProcessValuePreviewProps & WithStyles<CssRules>) =>
432 <Typography className={classes.paramValue}>
433 {value.imageUrl && showImagePreview ? <img className={classes.imagePreview} src={value.imageUrl} alt="Inline Preview" /> : ""}
434 {value.imageUrl && !showImagePreview ? <ImagePlaceholder /> : ""}
435 <span className={classNames(classes.valArray, value.secondary && classes.secondaryVal)}>
441 interface ProcessIORawDataProps {
442 data: ProcessIOParameter[];
445 const ProcessIORaw = withStyles(styles)(
446 ({ data }: ProcessIORawDataProps) =>
447 <Paper elevation={0}>
448 <DefaultCodeSnippet lines={[JSON.stringify(data, null, 2)]} linked />
452 interface ProcessInputMountsDataProps {
453 mounts: InputCollectionMount[];
456 type ProcessInputMountsProps = ProcessInputMountsDataProps & WithStyles<CssRules>;
458 const ProcessInputMounts = withStyles(styles)(connect((state: RootState) => ({
460 }))(({ mounts, classes, auth }: ProcessInputMountsProps & { auth: AuthState }) => (
461 <Table className={classes.tableRoot} aria-label="Process Input Mounts">
464 <TableCell>Path</TableCell>
465 <TableCell>Portable Data Hash</TableCell>
469 {mounts.map(mount => (
470 <TableRow key={mount.path}>
471 <TableCell><pre>{mount.path}</pre></TableCell>
473 <RouterLink to={getNavUrl(mount.pdh, auth)} className={classes.keepLink}>{mount.pdh}</RouterLink>
481 type FileWithSecondaryFiles = {
482 secondaryFiles: File[];
485 export const getIOParamDisplayValue = (auth: AuthState, input: CommandInputParameter | CommandOutputParameter, pdh?: string): ProcessIOValue[] => {
487 case isPrimitiveOfType(input, CWLType.BOOLEAN):
488 const boolValue = (input as BooleanCommandInputParameter).value;
489 return boolValue !== undefined &&
490 !(Array.isArray(boolValue) && boolValue.length === 0) ?
491 [{display: renderPrimitiveValue(boolValue, false) }] :
492 [{display: <EmptyValue />}];
494 case isPrimitiveOfType(input, CWLType.INT):
495 case isPrimitiveOfType(input, CWLType.LONG):
496 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: renderPrimitiveValue(intValue, false) }]
501 : [{display: <EmptyValue />}];
503 case isPrimitiveOfType(input, CWLType.FLOAT):
504 case isPrimitiveOfType(input, CWLType.DOUBLE):
505 const floatValue = (input as FloatCommandInputParameter).value;
506 return floatValue !== undefined &&
507 !(Array.isArray(floatValue) && floatValue.length === 0) ?
508 [{display: renderPrimitiveValue(floatValue, false) }]:
509 [{display: <EmptyValue />}];
511 case isPrimitiveOfType(input, CWLType.STRING):
512 const stringValue = (input as StringCommandInputParameter).value || undefined;
513 return stringValue !== undefined &&
514 !(Array.isArray(stringValue) && stringValue.length === 0) ?
515 [{display: renderPrimitiveValue(stringValue, false) }] :
516 [{display: <EmptyValue />}];
518 case isPrimitiveOfType(input, CWLType.FILE):
519 const mainFile = (input as FileCommandInputParameter).value;
520 // secondaryFiles: File[] is not part of CommandOutputParameter so we cast to access secondaryFiles
521 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
523 ...(mainFile && !(Array.isArray(mainFile) && mainFile.length === 0) ? [mainFile] : []),
526 const mainFilePdhUrl = mainFile ? getResourcePdhUrl(mainFile, pdh) : "";
527 return files.length ?
528 files.map((file, i) => fileToProcessIOValue(file, (i > 0), auth, pdh, (i > 0 ? mainFilePdhUrl : ""))) :
529 [{display: <EmptyValue />}];
531 case isPrimitiveOfType(input, CWLType.DIRECTORY):
532 const directory = (input as DirectoryCommandInputParameter).value;
533 return directory !== undefined &&
534 !(Array.isArray(directory) && directory.length === 0) ?
535 [directoryToProcessIOValue(directory, auth, pdh)] :
536 [{display: <EmptyValue />}];
538 case typeof input.type === 'object' &&
539 !(input.type instanceof Array) &&
540 input.type.type === 'enum':
541 const enumValue = (input as EnumCommandInputParameter).value;
542 return enumValue !== undefined && enumValue ?
543 [{ display: <pre>{enumValue}</pre> }] :
544 [{display: <EmptyValue />}];
546 case isArrayOfType(input, CWLType.STRING):
547 const strArray = (input as StringArrayCommandInputParameter).value || [];
548 return strArray.length ?
549 [{ display: <>{strArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
550 [{display: <EmptyValue />}];
552 case isArrayOfType(input, CWLType.INT):
553 case isArrayOfType(input, CWLType.LONG):
554 const intArray = (input as IntArrayCommandInputParameter).value || [];
555 return intArray.length ?
556 [{ display: <>{intArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
557 [{display: <EmptyValue />}];
559 case isArrayOfType(input, CWLType.FLOAT):
560 case isArrayOfType(input, CWLType.DOUBLE):
561 const floatArray = (input as FloatArrayCommandInputParameter).value || [];
562 return floatArray.length ?
563 [{ display: <>{floatArray.map((val) => renderPrimitiveValue(val, true))}</> }] :
564 [{display: <EmptyValue />}];
566 case isArrayOfType(input, CWLType.FILE):
567 const fileArrayMainFiles = ((input as FileArrayCommandInputParameter).value || []);
568 const firstMainFilePdh = (fileArrayMainFiles.length > 0 && fileArrayMainFiles[0]) ? getResourcePdhUrl(fileArrayMainFiles[0], pdh) : "";
570 // Convert each main file into separate arrays of ProcessIOValue to preserve secondaryFile grouping
571 const fileArrayValues = fileArrayMainFiles.map((mainFile: File, i): ProcessIOValue[] => {
572 const secondaryFiles = ((mainFile as unknown) as FileWithSecondaryFiles)?.secondaryFiles || [];
574 // Pass firstMainFilePdh to secondary files and every main file besides the first to hide pdh if equal
575 ...(mainFile ? [fileToProcessIOValue(mainFile, false, auth, pdh, i > 0 ? firstMainFilePdh : "")] : []),
576 ...(secondaryFiles.map(file => fileToProcessIOValue(file, true, auth, pdh, firstMainFilePdh)))
578 // Reduce each mainFile/secondaryFile group into single array preserving ordering
579 }).reduce((acc: ProcessIOValue[], mainFile: ProcessIOValue[]) => (acc.concat(mainFile)), []);
581 return fileArrayValues.length ?
583 [{display: <EmptyValue />}];
585 case isArrayOfType(input, CWLType.DIRECTORY):
586 const directories = (input as DirectoryArrayCommandInputParameter).value || [];
587 return directories.length ?
588 directories.map(directory => directoryToProcessIOValue(directory, auth, pdh)) :
589 [{display: <EmptyValue />}];
592 return [{display: <UnsupportedValue />}];
596 const renderPrimitiveValue = (value: any, asChip: boolean) => {
597 const isObject = typeof value === 'object';
599 return asChip ? <Chip label={String(value)} /> : <pre>{String(value)}</pre>;
601 return asChip ? <UnsupportedValueChip /> : <UnsupportedValue />;
606 * @returns keep url without keep: prefix
608 const getKeepUrl = (file: File | Directory, pdh?: string): string => {
609 const isKeepUrl = file.location?.startsWith('keep:') || false;
610 const keepUrl = isKeepUrl ?
611 file.location?.replace('keep:', '') :
612 pdh ? `${pdh}/${file.location}` : file.location;
613 return keepUrl || '';
616 interface KeepUrlProps {
618 res: File | Directory;
622 const getResourcePdhUrl = (res: File | Directory, pdh?: string): string => {
623 const keepUrl = getKeepUrl(res, pdh);
624 return keepUrl ? keepUrl.split('/').slice(0, 1)[0] : '';
627 const KeepUrlBase = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
628 const pdhUrl = getResourcePdhUrl(res, pdh);
629 // Passing a pdh always returns a relative wb2 collection url
630 const pdhWbPath = getNavUrl(pdhUrl, auth);
631 return pdhUrl && pdhWbPath ?
632 <Tooltip title={"View collection in Workbench"}><RouterLink to={pdhWbPath} className={classes.keepLink}>{pdhUrl}</RouterLink></Tooltip> :
636 const KeepUrlPath = withStyles(styles)(({auth, res, pdh, classes}: KeepUrlProps & WithStyles<CssRules>) => {
637 const keepUrl = getKeepUrl(res, pdh);
638 const keepUrlParts = keepUrl ? keepUrl.split('/') : [];
639 const keepUrlPath = keepUrlParts.length > 1 ? keepUrlParts.slice(1).join('/') : '';
641 const keepUrlPathNav = getKeepNavUrl(auth, res, pdh);
642 return keepUrlPathNav ?
643 <Tooltip title={"View in keep-web"}><a className={classes.keepLink} href={keepUrlPathNav} target="_blank" rel="noopener noreferrer">{keepUrlPath || '/'}</a></Tooltip> :
647 const getKeepNavUrl = (auth: AuthState, file: File | Directory, pdh?: string): string => {
648 let keepUrl = getKeepUrl(file, pdh);
649 return (getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl));
652 const getImageUrl = (auth: AuthState, file: File, pdh?: string): string => {
653 const keepUrl = getKeepUrl(file, pdh);
654 return getInlineFileUrl(`${auth.config.keepWebServiceUrl}/c=${keepUrl}?api_token=${auth.apiToken}`, auth.config.keepWebServiceUrl, auth.config.keepWebInlineServiceUrl);
657 const isFileImage = (basename?: string): boolean => {
658 return basename ? (mime.getType(basename) || "").startsWith('image/') : false;
661 const isFileUrl = (location?: string): boolean => (
662 !!location && !KEEP_URL_REGEX.exec(location) &&
663 (location.startsWith("http://") || location.startsWith("https://"))
666 const normalizeDirectoryLocation = (directory: Directory): Directory => {
667 if (!directory.location) {
672 location: (directory.location || '').endsWith('/') ? directory.location : directory.location + '/',
676 const directoryToProcessIOValue = (directory: Directory, auth: AuthState, pdh?: string): ProcessIOValue => {
677 if (isExternalValue(directory)) {return {display: <UnsupportedValue />}}
679 const normalizedDirectory = normalizeDirectoryLocation(directory);
681 display: <KeepUrlPath auth={auth} res={normalizedDirectory} pdh={pdh}/>,
682 collection: <KeepUrlBase auth={auth} res={normalizedDirectory} pdh={pdh}/>,
686 const fileToProcessIOValue = (file: File, secondary: boolean, auth: AuthState, pdh: string | undefined, mainFilePdh: string): ProcessIOValue => {
687 if (isExternalValue(file)) {return {display: <UnsupportedValue />}}
689 if (isFileUrl(file.location)) {
691 display: <MuiLink href={file.location} target="_blank">{file.location}</MuiLink>,
696 const resourcePdh = getResourcePdhUrl(file, pdh);
698 display: <KeepUrlPath auth={auth} res={file} pdh={pdh}/>,
700 imageUrl: isFileImage(file.basename) ? getImageUrl(auth, file, pdh) : undefined,
701 collection: (resourcePdh !== mainFilePdh) ? <KeepUrlBase auth={auth} res={file} pdh={pdh}/> : <></>,
705 const isExternalValue = (val: any) =>
706 Object.keys(val).includes('$import') ||
707 Object.keys(val).includes('$include')
709 const EmptyValue = withStyles(styles)(
710 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>No value</span>
713 const UnsupportedValue = withStyles(styles)(
714 ({classes}: WithStyles<CssRules>) => <span className={classes.emptyValue}>Cannot display value</span>
717 const UnsupportedValueChip = withStyles(styles)(
718 ({classes}: WithStyles<CssRules>) => <Chip icon={<InfoIcon />} label={"Cannot display value"} />
721 const ImagePlaceholder = withStyles(styles)(
722 ({classes}: WithStyles<CssRules>) => <span className={classes.imagePlaceholder}><ImageIcon /></span>