21317: overflow now toggles on and off at the same pixel Arvados-DCO-1.1-Signed-off...
[arvados.git] / services / workbench2 / src / components / multiselect-toolbar / ms-toolbar-overflow-wrapper.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React, { useState, useRef, useEffect } from 'react';
6 import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core';
7 import classnames from 'classnames';
8 import { ArvadosTheme } from 'common/custom-theme';
9 import { OverflowMenu, OverflowChild } from './ms-toolbar-overflow-menu';
10
11 type CssRules = 'visible' | 'inVisible' | 'toolbarWrapper' | 'overflowStyle';
12
13 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
14     visible: {
15         order: 0,
16         visibility: 'visible',
17         opacity: 1,
18     },
19     inVisible: {
20         order: 100,
21         visibility: 'hidden',
22         pointerEvents: 'none',
23     },
24     toolbarWrapper: {
25         display: 'flex',
26         overflow: 'hidden',
27         padding: '0 0px 0 20px',
28         width: '100%',
29     },
30     overflowStyle: {
31         order: 99,
32         position: 'sticky',
33         right: '-2rem',
34         width: 0,
35     },
36 });
37
38 type WrapperProps = {
39     children: OverflowChild[];
40     menuLength: number;
41 };
42
43 export const IntersectionObserverWrapper = withStyles(styles)((props: WrapperProps & WithStyles<CssRules>) => {
44     const { classes, children, menuLength } = props;
45     const lastEntryId = (children[menuLength - 1] as any).props['data-targetid'];
46     const navRef = useRef<any>(null);
47     const [visibilityMap, setVisibilityMap] = useState<Record<string, boolean>>({});
48     const [numHidden, setNumHidden] = useState(() => findNumHidden(visibilityMap));
49
50     const prevNumHidden = useRef(numHidden);
51
52     const handleIntersection = (entries) => {
53         const updatedEntries: Record<string, boolean> = {};
54         entries.forEach((entry) => {
55             const targetid = entry.target.dataset.targetid as string;
56             if (entry.isIntersecting) {
57                 updatedEntries[targetid] = true;
58             } else {
59                 updatedEntries[targetid] = false;
60             }
61         });
62
63         setVisibilityMap((prev) => ({
64             ...prev,
65             ...updatedEntries,
66             [lastEntryId]: Object.keys(updatedEntries)[0] === lastEntryId,
67         }));
68     };
69
70     useEffect(() => {
71         if (prevNumHidden.current === 2 && numHidden === 1) {
72             setVisibilityMap((prev) => ({
73                 ...prev,
74                 [lastEntryId]: true,
75             }));
76         }
77         prevNumHidden.current = numHidden;
78     }, [numHidden, lastEntryId]);
79
80     useEffect(() => {
81         setNumHidden(findNumHidden(visibilityMap));
82     }, [visibilityMap]);
83
84     useEffect((): any => {
85         setVisibilityMap({});
86         const observer = new IntersectionObserver(handleIntersection, {
87             root: navRef.current,
88             rootMargin: '0px -30px 0px 0px',
89             threshold: 1,
90         });
91         // We are adding observers to child elements of the container div
92         // with ref as navRef. Notice that we are adding observers
93         // only if we have the data attribute targetid on the child element
94         if (navRef.current)
95             Array.from(navRef.current.children).forEach((item: any) => {
96                 if (item.dataset.targetid) {
97                     observer.observe(item);
98                 }
99             });
100         return () => {
101             observer.disconnect();
102         };
103         // eslint-disable-next-line
104     }, [menuLength]);
105
106     function findNumHidden(visMap: {}) {
107         return Object.values(visMap).filter((x) => x === false).length;
108     }
109
110     return (
111         <div
112             className={classes.toolbarWrapper}
113             ref={navRef}
114         >
115             {React.Children.map(children, (child) => {
116                 return React.cloneElement(child, {
117                     className: classnames(child.props.className, {
118                         [classes.visible]: !!visibilityMap[child.props['data-targetid']],
119                         [classes.inVisible]: !visibilityMap[child.props['data-targetid']],
120                     }),
121                 });
122             })}
123             {numHidden >= 2 && (
124                 <OverflowMenu
125                     visibilityMap={visibilityMap}
126                     className={classes.overflowStyle}
127                 >
128                     {children}
129                 </OverflowMenu>
130             )}
131         </div>
132     );
133 });