19300: Adds un-maximize functionality to the MPV component suite.
[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 } 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     doUnMaximizePanel: () => void;
52 }
53
54 type MPVHideablePanelProps = MPVHideablePanelDataProps & MPVHideablePanelActionProps;
55
56 const MPVHideablePanel = ({doHidePanel, doMaximizePanel, doUnMaximizePanel, name, visible, maximized, illuminated, ...props}: MPVHideablePanelProps) =>
57     visible
58     ? <>
59         {React.cloneElement((props.children as ReactElement), { doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName: name, panelMaximized: maximized, panelIlluminated: illuminated, panelRef: props.panelRef })}
60     </>
61     : null;
62
63 interface MPVPanelDataProps {
64     panelName?: string;
65     panelMaximized?: boolean;
66     panelIlluminated?: boolean;
67     panelRef?: MutableRefObject<any>;
68     forwardProps?: boolean;
69     maxHeight?: string;
70 }
71
72 interface MPVPanelActionProps {
73     doHidePanel?: () => void;
74     doMaximizePanel?: () => void;
75     doUnMaximizePanel?: () => void;
76 }
77
78 // Props received by panel implementors
79 export type MPVPanelProps = MPVPanelDataProps & MPVPanelActionProps;
80
81 type MPVPanelContentProps = {children: ReactElement} & MPVPanelProps & GridProps;
82
83 // Grid item compatible component for layout and MPV props passing
84 export const MPVPanelContent = ({doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName,
85     panelMaximized, panelIlluminated, panelRef, forwardProps, maxHeight,
86     ...props}: MPVPanelContentProps) => {
87     useEffect(() => {
88         if (panelRef && panelRef.current) {
89             panelRef.current.scrollIntoView({behavior: 'smooth'});
90         }
91     }, [panelRef]);
92
93     const mh = panelMaximized
94         ? '100%'
95         : maxHeight;
96
97     return <Grid item style={{maxHeight: mh}} {...props}>
98         <span ref={panelRef} /> {/* Element to scroll to when the panel is selected */}
99         <Paper style={{height: '100%'}} elevation={panelIlluminated ? 8 : 0}>
100             { forwardProps
101                 ? React.cloneElement(props.children, { doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName, panelMaximized })
102                 : props.children }
103         </Paper>
104     </Grid>;
105 }
106
107 export interface MPVPanelState {
108     name: string;
109     visible?: boolean;
110 }
111 interface MPVContainerDataProps {
112     panelStates?: MPVPanelState[];
113 }
114 type MPVContainerProps = MPVContainerDataProps & GridProps;
115
116 // Grid container compatible component that also handles panel toggling.
117 const MPVContainerComponent = ({children, panelStates, classes, ...props}: MPVContainerProps & WithStyles<CssRules>) => {
118     if (children === undefined || children === null || children === {}) {
119         children = [];
120     } else if (!isArray(children)) {
121         children = [children];
122     }
123     const initialVisibility = (children as ReactNodeArray).map((_, idx) =>
124         !panelStates || // if panelStates wasn't passed, default to all visible panels
125             (panelStates[idx] &&
126                 (panelStates[idx].visible || panelStates[idx].visible === undefined)));
127     const [panelVisibility, setPanelVisibility] = useState<boolean[]>(initialVisibility);
128     const [previousPanelVisibility, setPreviousPanelVisibility] = useState<boolean[]>(initialVisibility);
129     const [highlightedPanel, setHighlightedPanel] = useState<number>(-1);
130     const [selectedPanel, setSelectedPanel] = useState<number>(-1);
131     const panelRef = useRef<any>(null);
132
133     let panels: JSX.Element[] = [];
134     let buttons: JSX.Element[] = [];
135
136     if (isArray(children)) {
137         for (let idx = 0; idx < children.length; idx++) {
138             const showFn = (idx: number) => () => {
139                 setPreviousPanelVisibility(initialVisibility);
140                 setPanelVisibility([
141                     ...panelVisibility.slice(0, idx),
142                     true,
143                     ...panelVisibility.slice(idx+1)
144                 ]);
145                 setSelectedPanel(idx);
146             };
147             const hideFn = (idx: number) => () => {
148                 setPreviousPanelVisibility(initialVisibility);
149                 setPanelVisibility([
150                     ...panelVisibility.slice(0, idx),
151                     false,
152                     ...panelVisibility.slice(idx+1)
153                 ])
154             };
155             const maximizeFn = (idx: number) => () => {
156                 setPreviousPanelVisibility(panelVisibility);
157                 // Maximize X == hide all but X
158                 setPanelVisibility([
159                     ...panelVisibility.slice(0, idx).map(() => false),
160                     true,
161                     ...panelVisibility.slice(idx+1).map(() => false),
162                 ]);
163             };
164             const unMaximizeFn = (idx: number) => () => {
165                 setPanelVisibility(previousPanelVisibility);
166                 setSelectedPanel(idx);
167             }
168             const panelName = panelStates === undefined
169                 ? `Panel ${idx+1}`
170                 : (panelStates[idx] && panelStates[idx].name) || `Panel ${idx+1}`;
171             const btnVariant = panelVisibility[idx]
172                 ? "contained"
173                 : "outlined";
174             const btnTooltip = panelVisibility[idx]
175                 ? ``
176                 :`Open ${panelName} panel`;
177             const panelIsMaximized = panelVisibility[idx] &&
178                 panelVisibility.filter(e => e).length === 1;
179
180             buttons = [
181                 ...buttons,
182                 <Tooltip title={btnTooltip} disableFocusListener>
183                     <Button variant={btnVariant} size="small" color="primary"
184                         className={classNames(classes.button)}
185                         onMouseEnter={() => {
186                             setHighlightedPanel(idx);
187                         }}
188                         onMouseLeave={() => {
189                             setHighlightedPanel(-1);
190                         }}
191                         onClick={showFn(idx)}>
192                             {panelName}
193                     </Button>
194                 </Tooltip>
195             ];
196
197             const aPanel =
198                 <MPVHideablePanel key={idx} visible={panelVisibility[idx]} name={panelName}
199                     panelRef={(idx === selectedPanel) ? panelRef : undefined}
200                     maximized={panelIsMaximized} illuminated={idx === highlightedPanel}
201                     doHidePanel={hideFn(idx)} doMaximizePanel={maximizeFn(idx)} doUnMaximizePanel={panelIsMaximized ? unMaximizeFn(idx) : () => null}>
202                     {children[idx]}
203                 </MPVHideablePanel>;
204             panels = [...panels, aPanel];
205         };
206     };
207
208     return <Grid container {...props}>
209         <Grid container item direction="row">
210             { buttons.map((tgl, idx) => <Grid item key={idx}>{tgl}</Grid>) }
211         </Grid>
212         <Grid container item {...props} xs className={classes.content}
213             onScroll={() => setSelectedPanel(-1)}>
214             { panelVisibility.includes(true)
215                 ? panels
216                 : <Grid container item alignItems='center' justify='center'>
217                     <DefaultView messages={["All panels are hidden.", "Click on the buttons above to show them."]} icon={InfoIcon} />
218                 </Grid> }
219         </Grid>
220     </Grid>;
221 };
222
223 export const MPVContainer = withStyles(styles)(MPVContainerComponent);