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