1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React, { useState, useRef, useEffect , ReactElement, JSXElementConstructor} 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';
11 type CssRules = 'visible' | 'inVisible' | 'toolbarWrapper' | 'overflowStyle';
13 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
16 visibility: 'visible',
22 pointerEvents: 'none',
34 backgroundColor: 'white',
39 children: OverflowChild[]
42 export const IntersectionObserverWrapper = withStyles(styles)((props: WrapperProps & WithStyles<CssRules>) => {
43 const { classes, children} = props
45 const navRef = useRef<any>(null);
46 const [visibilityMap, setVisibilityMap] = useState({});
48 const handleIntersection = (entries) => {
49 const updatedEntries = {};
50 entries.forEach((entry) => {
51 const targetid = entry.target.dataset.targetid;
52 if (entry.isIntersecting) {
53 updatedEntries[targetid] = true;
55 updatedEntries[targetid] = false;
59 setVisibilityMap((prev) => ({
64 useEffect((): any => {
65 const observer = new IntersectionObserver(handleIntersection, {
67 rootMargin: '0px -20px 0px 0px',
70 // We are adding observers to child elements of the container div
71 // with ref as navRef. Notice that we are adding observers
72 // only if we have the data attribute targetid on the child element
74 Array.from(navRef.current.children).forEach((item: any) => {
75 if (item.dataset.targetid) {
76 observer.observe(item);
80 observer.disconnect();
85 <div className={classes.toolbarWrapper} ref={navRef}>
86 {React.Children.map(children, (child) => {
87 return React.cloneElement(child, {
88 className: classnames(child.props.className, {
89 [classes.visible]: !!visibilityMap[child.props["data-targetid"]],
90 [classes.inVisible]: !visibilityMap[child.props["data-targetid"]]
95 visibilityMap={visibilityMap}
96 className={classes.overflowStyle}