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