1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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';
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[];
43 export const IntersectionObserverWrapper = withStyles(styles)((props: WrapperProps & WithStyles<CssRules>) => {
44 const { classes, children, length } = props;
46 const navRef = useRef<any>(null);
47 const [visibilityMap, setVisibilityMap] = useState({});
49 const handleIntersection = (entries) => {
50 const updatedEntries = {};
51 entries.forEach((entry) => {
52 const targetid = entry.target.dataset.targetid;
53 if (entry.isIntersecting) {
54 updatedEntries[targetid] = true;
56 updatedEntries[targetid] = false;
60 setVisibilityMap((prev) => ({
66 useEffect((): any => {
68 const observer = new IntersectionObserver(handleIntersection, {
70 rootMargin: '0px -20px 0px 0px',
73 // We are adding observers to child elements of the container div
74 // with ref as navRef. Notice that we are adding observers
75 // only if we have the data attribute targetid on the child element
77 Array.from(navRef.current.children).forEach((item: any) => {
78 if (item.dataset.targetid) {
79 observer.observe(item);
83 observer.disconnect();
89 className={classes.toolbarWrapper}
92 {React.Children.map(children, (child) => {
93 return React.cloneElement(child, {
94 className: classnames(child.props.className, {
95 [classes.visible]: !!visibilityMap[child.props['data-targetid']],
96 [classes.inVisible]: !visibilityMap[child.props['data-targetid']],
101 visibilityMap={visibilityMap}
102 className={classes.overflowStyle}