Merge remote-tracking branch 'origin/main' into 18207-Workbench2-is-not-clearing...
[arvados-workbench2.git] / src / components / multi-panel-view / multi-panel-view.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React, { MutableRefObject, ReactElement, ReactNode, useEffect, useRef, useState } from 'react';
6 import {
7     Button,
8     Grid,
9     Paper,
10     StyleRulesCallback,
11     Tooltip,
12     withStyles,
13     WithStyles
14 } from "@material-ui/core";
15 import { GridProps } from '@material-ui/core/Grid';
16 import { isArray } from 'lodash';
17 import { DefaultView } from 'components/default-view/default-view';
18 import { InfoIcon, InvisibleIcon, VisibleIcon } from 'components/icon/icon';
19 import { ReactNodeArray } from 'prop-types';
20 import classNames from 'classnames';
21
22 type CssRules = 'button' | 'buttonIcon' | 'content';
23
24 const styles: StyleRulesCallback<CssRules> = theme => ({
25     button: {
26         padding: '2px 5px',
27         marginRight: '5px',
28     },
29     buttonIcon: {
30         boxShadow: 'none',
31         padding: '2px 0px 2px 5px',
32         fontSize: '1rem'
33     },
34     content: {
35         overflow: 'auto',
36     },
37 });
38
39 interface MPVHideablePanelDataProps {
40     name: string;
41     visible: boolean;
42     maximized: boolean;
43     illuminated: boolean;
44     children: ReactNode;
45     panelRef?: MutableRefObject<any>;
46 }
47
48 interface MPVHideablePanelActionProps {
49     doHidePanel: () => void;
50     doMaximizePanel: () => void;
51 }
52
53 type MPVHideablePanelProps = MPVHideablePanelDataProps & MPVHideablePanelActionProps;
54
55 const MPVHideablePanel = ({doHidePanel, doMaximizePanel, name, visible, maximized, illuminated, ...props}: MPVHideablePanelProps) =>
56     visible
57     ? <>
58         {React.cloneElement((props.children as ReactElement), { doHidePanel, doMaximizePanel, panelName: name, panelMaximized: maximized, panelIlluminated: illuminated, panelRef: props.panelRef })}
59     </>
60     : null;
61
62 interface MPVPanelDataProps {
63     panelName?: string;
64     panelMaximized?: boolean;
65     panelIlluminated?: boolean;
66     panelRef?: MutableRefObject<any>;
67     forwardProps?: boolean;
68 }
69
70 interface MPVPanelActionProps {
71     doHidePanel?: () => void;
72     doMaximizePanel?: () => void;
73 }
74
75 // Props received by panel implementors
76 export type MPVPanelProps = MPVPanelDataProps & MPVPanelActionProps;
77
78 type MPVPanelContentProps = {children: ReactElement} & MPVPanelProps & GridProps;
79
80 // Grid item compatible component for layout and MPV props passing
81 export const MPVPanelContent = ({doHidePanel, doMaximizePanel, panelName, panelMaximized, panelIlluminated, panelRef, forwardProps, ...props}: MPVPanelContentProps) => {
82     useEffect(() => {
83         if (panelRef && panelRef.current) {
84             panelRef.current.scrollIntoView({behavior: 'smooth'});
85         }
86     }, [panelRef]);
87
88     return <Grid item {...props}>
89         <span ref={panelRef} /> {/* Element to scroll to when the panel is selected */}
90         <Paper style={{height: '100%'}} elevation={panelIlluminated ? 8 : 0}>
91             { forwardProps
92                 ? React.cloneElement(props.children, { doHidePanel, doMaximizePanel, panelName, panelMaximized })
93                 : props.children }
94         </Paper>
95     </Grid>;
96 }
97
98 export interface MPVPanelState {
99     name: string;
100     visible?: boolean;
101 }
102 interface MPVContainerDataProps {
103     panelStates?: MPVPanelState[];
104 }
105 type MPVContainerProps = MPVContainerDataProps & GridProps;
106
107 // Grid container compatible component that also handles panel toggling.
108 const MPVContainerComponent = ({children, panelStates, classes, ...props}: MPVContainerProps & WithStyles<CssRules>) => {
109     if (children === undefined || children === null || children === {}) {
110         children = [];
111     } else if (!isArray(children)) {
112         children = [children];
113     }
114     const visibility = (children as ReactNodeArray).map((_, idx) =>
115         !!!panelStates || // if panelStates wasn't passed, default to all visible panels
116             (panelStates[idx] &&
117                 (panelStates[idx].visible || panelStates[idx].visible === undefined)));
118     const [panelVisibility, setPanelVisibility] = useState<boolean[]>(visibility);
119     const [brightenedPanel, setBrightenedPanel] = useState<number>(-1);
120     const panelRef = useRef<any>(null);
121
122     let panels: JSX.Element[] = [];
123     let toggles: JSX.Element[] = [];
124
125     if (isArray(children)) {
126         for (let idx = 0; idx < children.length; idx++) {
127             const showFn = (idx: number) => () => {
128                 setPanelVisibility([
129                     ...panelVisibility.slice(0, idx),
130                     true,
131                     ...panelVisibility.slice(idx+1)
132                 ]);
133             };
134             const hideFn = (idx: number) => () => {
135                 setPanelVisibility([
136                     ...panelVisibility.slice(0, idx),
137                     false,
138                     ...panelVisibility.slice(idx+1)
139                 ])
140             };
141             const maximizeFn = (idx: number) => () => {
142                 // Maximize X == hide all but X
143                 setPanelVisibility([
144                     ...panelVisibility.slice(0, idx).map(() => false),
145                     true,
146                     ...panelVisibility.slice(idx+1).map(() => false),
147                 ])
148             };
149             const toggleIcon = panelVisibility[idx]
150                 ? <VisibleIcon className={classNames(classes.buttonIcon)} />
151                 : <InvisibleIcon className={classNames(classes.buttonIcon)}/>
152             const panelName = panelStates === undefined
153                 ? `Panel ${idx+1}`
154                 : (panelStates[idx] && panelStates[idx].name) || `Panel ${idx+1}`;
155             const toggleVariant = "outlined";
156             const toggleTooltip = panelVisibility[idx]
157                 ? ''
158                 :`Show ${panelName} panel`;
159             const panelIsMaximized = panelVisibility[idx] &&
160                 panelVisibility.filter(e => e).length === 1;
161
162             toggles = [
163                 ...toggles,
164                 <Tooltip title={toggleTooltip} disableFocusListener>
165                     <Button variant={toggleVariant} size="small" color="primary"
166                         className={classNames(classes.button)}
167                         onMouseEnter={() => setBrightenedPanel(idx)}
168                         onMouseLeave={() => setBrightenedPanel(-1)}
169                         onClick={showFn(idx)}>
170                             {panelName}
171                             {toggleIcon}
172                     </Button>
173                 </Tooltip>
174             ];
175
176             const aPanel =
177                 <MPVHideablePanel key={idx} visible={panelVisibility[idx]} name={panelName}
178                     panelRef={(idx === brightenedPanel) ? panelRef : undefined}
179                     maximized={panelIsMaximized} illuminated={idx === brightenedPanel}
180                     doHidePanel={hideFn(idx)} doMaximizePanel={maximizeFn(idx)}>
181                     {children[idx]}
182                 </MPVHideablePanel>;
183             panels = [...panels, aPanel];
184         };
185     };
186
187     return <Grid container {...props}>
188         <Grid container item direction="row">
189             { toggles.map((tgl, idx) => <Grid item key={idx}>{tgl}</Grid>) }
190         </Grid>
191         <Grid container item {...props} xs className={classes.content}>
192             { panelVisibility.includes(true)
193                 ? panels
194                 : <Grid container item alignItems='center' justify='center'>
195                     <DefaultView messages={["All panels are hidden.", "Click on the buttons above to show them."]} icon={InfoIcon} />
196                 </Grid> }
197         </Grid>
198     </Grid>;
199 };
200
201 export const MPVContainer = withStyles(styles)(MPVContainerComponent);