19687: Fixes log panel scrolling behavior in Safari.
[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     minHeight?: string;
71 }
72
73 interface MPVPanelActionProps {
74     doHidePanel?: () => void;
75     doMaximizePanel?: () => void;
76     doUnMaximizePanel?: () => void;
77 }
78
79 // Props received by panel implementors
80 export type MPVPanelProps = MPVPanelDataProps & MPVPanelActionProps;
81
82 type MPVPanelContentProps = {children: ReactElement} & MPVPanelProps & GridProps;
83
84 // Grid item compatible component for layout and MPV props passing
85 export const MPVPanelContent = ({doHidePanel, doMaximizePanel, doUnMaximizePanel, panelName,
86     panelMaximized, panelIlluminated, panelRef, forwardProps, maxHeight, minHeight,
87     ...props}: MPVPanelContentProps) => {
88     useEffect(() => {
89         if (panelRef && panelRef.current) {
90             panelRef.current.scrollIntoView({alignToTop: true});
91         }
92     }, [panelRef]);
93
94     const maxH = panelMaximized
95         ? '100%'
96         : maxHeight;
97
98     return <Grid item style={{maxHeight: maxH, minHeight}} {...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, doUnMaximizePanel, 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 initialVisibility = (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[]>(initialVisibility);
129     const [previousPanelVisibility, setPreviousPanelVisibility] = useState<boolean[]>(initialVisibility);
130     const [highlightedPanel, setHighlightedPanel] = useState<number>(-1);
131     const [selectedPanel, setSelectedPanel] = useState<number>(-1);
132     const panelRef = useRef<any>(null);
133
134     let panels: JSX.Element[] = [];
135     let buttons: JSX.Element[] = [];
136
137     if (isArray(children)) {
138         for (let idx = 0; idx < children.length; idx++) {
139             const showFn = (idx: number) => () => {
140                 setPreviousPanelVisibility(initialVisibility);
141                 setPanelVisibility([
142                     ...panelVisibility.slice(0, idx),
143                     true,
144                     ...panelVisibility.slice(idx+1)
145                 ]);
146                 setSelectedPanel(idx);
147             };
148             const hideFn = (idx: number) => () => {
149                 setPreviousPanelVisibility(initialVisibility);
150                 setPanelVisibility([
151                     ...panelVisibility.slice(0, idx),
152                     false,
153                     ...panelVisibility.slice(idx+1)
154                 ])
155             };
156             const maximizeFn = (idx: number) => () => {
157                 setPreviousPanelVisibility(panelVisibility);
158                 // Maximize X == hide all but X
159                 setPanelVisibility([
160                     ...panelVisibility.slice(0, idx).map(() => false),
161                     true,
162                     ...panelVisibility.slice(idx+1).map(() => false),
163                 ]);
164             };
165             const unMaximizeFn = (idx: number) => () => {
166                 setPanelVisibility(previousPanelVisibility);
167                 setSelectedPanel(idx);
168             }
169             const panelName = panelStates === undefined
170                 ? `Panel ${idx+1}`
171                 : (panelStates[idx] && panelStates[idx].name) || `Panel ${idx+1}`;
172             const btnVariant = panelVisibility[idx]
173                 ? "contained"
174                 : "outlined";
175             const btnTooltip = panelVisibility[idx]
176                 ? ``
177                 :`Open ${panelName} panel`;
178             const panelIsMaximized = panelVisibility[idx] &&
179                 panelVisibility.filter(e => e).length === 1;
180
181             buttons = [
182                 ...buttons,
183                 <Tooltip title={btnTooltip} disableFocusListener>
184                     <Button variant={btnVariant} size="small" color="primary"
185                         className={classNames(classes.button)}
186                         onMouseEnter={() => {
187                             setHighlightedPanel(idx);
188                         }}
189                         onMouseLeave={() => {
190                             setHighlightedPanel(-1);
191                         }}
192                         onClick={showFn(idx)}>
193                             {panelName}
194                     </Button>
195                 </Tooltip>
196             ];
197
198             const aPanel =
199                 <MPVHideablePanel key={idx} visible={panelVisibility[idx]} name={panelName}
200                     panelRef={(idx === selectedPanel) ? panelRef : undefined}
201                     maximized={panelIsMaximized} illuminated={idx === highlightedPanel}
202                     doHidePanel={hideFn(idx)} doMaximizePanel={maximizeFn(idx)} doUnMaximizePanel={panelIsMaximized ? unMaximizeFn(idx) : () => null}>
203                     {children[idx]}
204                 </MPVHideablePanel>;
205             panels = [...panels, aPanel];
206         };
207     };
208
209     return <Grid container {...props}>
210         <Grid container item direction="row">
211             { buttons.map((tgl, idx) => <Grid item key={idx}>{tgl}</Grid>) }
212         </Grid>
213         <Grid container item {...props} xs className={classes.content}
214             onScroll={() => setSelectedPanel(-1)}>
215             { panelVisibility.includes(true)
216                 ? panels
217                 : <Grid container item alignItems='center' justify='center'>
218                     <DefaultView messages={["All panels are hidden.", "Click on the buttons above to show them."]} icon={InfoIcon} />
219                 </Grid> }
220         </Grid>
221     </Grid>;
222 };
223
224 export const MPVContainer = withStyles(styles)(MPVContainerComponent);