Merge branch '21815-trigrams-exclude-ids'
[arvados.git] / services / workbench2 / 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     Tab,
12     Tabs,
13     Tooltip,
14     withStyles,
15     WithStyles
16 } from "@material-ui/core";
17 import { GridProps } from '@material-ui/core/Grid';
18 import { isArray } from 'lodash';
19 import { DefaultView } from 'components/default-view/default-view';
20 import { InfoIcon } from 'components/icon/icon';
21 import { ReactNodeArray } from 'prop-types';
22 import classNames from 'classnames';
23
24 type CssRules =
25     | 'gridContainerRoot'
26     | 'exclusiveGridContainerRoot'
27     | 'gridItemRoot'
28     | 'paperRoot'
29     | 'button'
30     | 'buttonIcon'
31     | 'content'
32     | 'exclusiveContentPaper'
33     | 'tabs';
34
35 const styles: StyleRulesCallback<CssRules> = theme => ({
36     gridContainerRoot: {
37         marginTop: '10px',
38     },
39     exclusiveGridContainerRoot: {
40         marginTop: 0,
41     },
42     gridItemRoot: {
43         paddingTop: '0 !important',
44     },
45     paperRoot: {
46         height: '100%',
47         display: 'flex',
48         flexDirection: 'column',
49     },
50     button: {
51         padding: '2px 5px',
52         marginRight: '5px',
53     },
54     buttonIcon: {
55         boxShadow: 'none',
56         padding: '2px 0px 2px 5px',
57         fontSize: '1rem'
58     },
59     content: {
60         overflow: 'auto',
61         maxWidth: 'initial',
62     },
63     exclusiveContentPaper: {
64         boxShadow: 'none',
65     },
66     tabs: {
67         flexGrow: 1,
68         flexShrink: 1,
69         maxWidth: 'initial',
70         borderBottom: `1px solid ${theme.palette.grey[300]}`,
71     },
72 });
73
74 interface MPVHideablePanelDataProps {
75     name: string;
76     visible: boolean;
77     maximized: boolean;
78     illuminated: boolean;
79     children: ReactNode;
80     panelRef?: MutableRefObject<any>;
81     paperClassName?: string;
82 }
83
84 interface MPVHideablePanelActionProps {
85     doHidePanel: () => void;
86     doMaximizePanel: () => void;
87     doUnMaximizePanel: () => void;
88 }
89
90 type MPVHideablePanelProps = MPVHideablePanelDataProps & MPVHideablePanelActionProps;
91
92 const MPVHideablePanel = ({ doHidePanel, doMaximizePanel, doUnMaximizePanel, name, visible, maximized, illuminated, paperClassName, ...props }: MPVHideablePanelProps) =>
93     visible
94         ? <>
95             {React.cloneElement((props.children as ReactElement), {
96                 doHidePanel,
97                 doMaximizePanel,
98                 doUnMaximizePanel,
99                 panelName: name,
100                 panelMaximized: maximized,
101                 panelIlluminated: illuminated,
102                 panelRef: props.panelRef,
103                 paperClassName,
104             })}
105         </>
106         : null;
107
108 interface MPVPanelDataProps {
109     panelName?: string;
110     panelMaximized?: boolean;
111     panelIlluminated?: boolean;
112     panelRef?: MutableRefObject<any>;
113     forwardProps?: boolean;
114     maxHeight?: string;
115     minHeight?: string;
116     paperClassName?: string;
117 }
118
119 interface MPVPanelActionProps {
120     doHidePanel?: () => void;
121     doMaximizePanel?: () => void;
122     doUnMaximizePanel?: () => void;
123 }
124
125 // Props received by panel implementors
126 export type MPVPanelProps = MPVPanelDataProps & MPVPanelActionProps;
127
128 type MPVPanelContentProps = { children: ReactElement } & MPVPanelProps & GridProps;
129
130 // Grid item compatible component for layout and MPV props passing
131 export const MPVPanelContent = ({ doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName,
132     panelMaximized, panelIlluminated, panelRef, forwardProps, maxHeight, minHeight, paperClassName,
133     ...props }: MPVPanelContentProps) => {
134     useEffect(() => {
135         if (panelRef && panelRef.current) {
136             panelRef.current.scrollIntoView({ alignToTop: true });
137         }
138     }, [panelRef]);
139
140     const maxH = panelMaximized
141         ? '100%'
142         : maxHeight;
143
144     return <Grid item style={{ maxHeight: maxH, minHeight }} {...props}>
145         <span ref={panelRef} /> {/* Element to scroll to when the panel is selected */}
146         <Paper style={{ height: '100%' }} elevation={panelIlluminated ? 8 : 0}>
147             {forwardProps
148                 ? React.cloneElement(props.children, { doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName, panelMaximized, paperClassName })
149                 : React.cloneElement(props.children, { paperClassName })}
150         </Paper>
151     </Grid>;
152 }
153
154 export interface MPVPanelState {
155     name: string;
156     visible?: boolean;
157 }
158 interface MPVContainerDataProps {
159     panelStates?: MPVPanelState[];
160     mutuallyExclusive?: boolean;
161 }
162 type MPVContainerProps = MPVContainerDataProps & GridProps;
163
164 // Grid container compatible component that also handles panel toggling.
165 const MPVContainerComponent = ({ children, panelStates, classes, ...props }: MPVContainerProps & WithStyles<CssRules>) => {
166     if (children === undefined || children === null || Object.keys(children).length === 0) {
167         children = [];
168     } else if (!isArray(children)) {
169         children = [children];
170     }
171     const initialVisibility = (children as ReactNodeArray).map((_, idx) =>
172         !panelStates || // if panelStates wasn't passed, default to all visible panels
173         (panelStates[idx] &&
174             (panelStates[idx].visible || panelStates[idx].visible === undefined)));
175     const [panelVisibility, setPanelVisibility] = useState<boolean[]>(initialVisibility);
176     const [previousPanelVisibility, setPreviousPanelVisibility] = useState<boolean[]>(initialVisibility);
177     const [highlightedPanel, setHighlightedPanel] = useState<number>(-1);
178     const currentSelectedPanel = panelVisibility.findIndex(Boolean);
179     const [selectedPanel, setSelectedPanel] = useState<number>(-1);
180     const panelRef = useRef<any>(null);
181
182     let panels: JSX.Element[] = [];
183     let buttons: JSX.Element[] = [];
184     let tabs: JSX.Element[] = [];
185     let buttonBar: JSX.Element = <></>;
186
187     if (isArray(children)) {
188         const showFn = (idx: number) => () => {
189             setPreviousPanelVisibility(initialVisibility);
190             if (props.mutuallyExclusive) {
191                 // Hide all other panels
192                 setPanelVisibility([
193                     ...(new Array(idx).fill(false)),
194                     true,
195                     ...(new Array(panelVisibility.length-(idx+1)).fill(false)),
196                 ]);
197             } else {
198                 setPanelVisibility([
199                     ...panelVisibility.slice(0, idx),
200                     true,
201                     ...panelVisibility.slice(idx + 1)
202                 ]);
203             }
204             setSelectedPanel(idx);
205         };
206         const hideFn = (idx: number) => () => {
207             setPreviousPanelVisibility(initialVisibility);
208             setPanelVisibility([
209                 ...panelVisibility.slice(0, idx),
210                 false,
211                 ...panelVisibility.slice(idx+1)
212             ])
213         };
214         const maximizeFn = (idx: number) => () => {
215             setPreviousPanelVisibility(panelVisibility);
216             // Maximize X == hide all but X
217             setPanelVisibility([
218                 ...panelVisibility.slice(0, idx).map(() => false),
219                 true,
220                 ...panelVisibility.slice(idx+1).map(() => false),
221             ]);
222         };
223         const unMaximizeFn = (idx: number) => () => {
224             setPanelVisibility(previousPanelVisibility);
225             setSelectedPanel(idx);
226         }
227         for (let idx = 0; idx < children.length; idx++) {
228             const panelName = panelStates === undefined
229                 ? `Panel ${idx + 1}`
230                 : (panelStates[idx] && panelStates[idx].name) || `Panel ${idx + 1}`;
231             const btnVariant = panelVisibility[idx]
232                 ? "contained"
233                 : "outlined";
234             const btnTooltip = panelVisibility[idx]
235                 ? ``
236                 : `Open ${panelName} panel`;
237             const panelIsMaximized = panelVisibility[idx] &&
238                 panelVisibility.filter(e => e).length === 1;
239
240             buttons = [
241                 ...buttons,
242                 <Tooltip title={btnTooltip} disableFocusListener>
243                     <Button variant={btnVariant} size="small" color="primary"
244                         className={classNames(classes.button)}
245                         onMouseEnter={() => {
246                             setHighlightedPanel(idx);
247                         }}
248                         onMouseLeave={() => {
249                             setHighlightedPanel(-1);
250                         }}
251                         onClick={showFn(idx)}>
252                         {panelName}
253                     </Button>
254                 </Tooltip>
255             ];
256
257             tabs = [
258                 ...tabs,
259                 <>{panelName}</>
260             ];
261
262             const aPanel =
263                 <MPVHideablePanel
264                     key={idx}
265                     visible={panelVisibility[idx]}
266                     name={panelName}
267                     paperClassName={props.mutuallyExclusive ? classes.exclusiveContentPaper : undefined}
268                     panelRef={(idx === selectedPanel) ? panelRef : undefined}
269                     maximized={panelIsMaximized} illuminated={idx === highlightedPanel}
270                     doHidePanel={hideFn(idx)} doMaximizePanel={maximizeFn(idx)} doUnMaximizePanel={panelIsMaximized ? unMaximizeFn(idx) : () => null}>
271                     {children[idx]}
272                 </MPVHideablePanel>;
273             panels = [...panels, aPanel];
274         };
275
276         buttonBar = props.mutuallyExclusive ?
277             <Tabs value={currentSelectedPanel} onChange={(e, val) => showFn(val)()} data-cy={"mpv-tabs"}>
278                 {tabs.map((tgl, idx) => <Tab className={classes.tabs} key={idx} label={tgl} />)}
279             </Tabs> :
280             <Grid container item direction="row">
281                 {buttons.map((tgl, idx) => <Grid item key={idx}>{tgl}</Grid>)}
282             </Grid>;
283     };
284
285     const content = <Grid container item {...props} xs className={classes.content}
286         onScroll={() => setSelectedPanel(-1)}>
287         {panelVisibility.includes(true)
288             ? panels
289             : <Grid container item alignItems='center' justify='center'>
290                 <DefaultView messages={["All panels are hidden.", "Click on the buttons above to show them."]} icon={InfoIcon} />
291             </Grid>}
292     </Grid>;
293
294     if (props.mutuallyExclusive) {
295         return <Grid container {...props} className={classNames(classes.exclusiveGridContainerRoot, props.className)}>
296             <Grid item {...props} className={classes.gridItemRoot}>
297                 <Paper className={classes.paperRoot}>
298                     {buttonBar}
299                     {content}
300                 </Paper>
301             </Grid>
302         </Grid>;
303     } else {
304         return <Grid container {...props} className={classNames(classes.gridContainerRoot, props.className)}>
305             {buttonBar}
306             {content}
307         </Grid>;
308     }
309 };
310
311 export const MPVContainer = withStyles(styles)(MPVContainerComponent);