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