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',
38 children: OverflowChild[];
42 export const IntersectionObserverWrapper = withStyles(styles)((props: WrapperProps & WithStyles<CssRules>) => {
43 const { classes, children, menuLength } = props;
44 const lastEntryId = (children[menuLength - 1] as any).props['data-targetid'];
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) => ({
62 [lastEntryId]: Object.keys(updatedEntries)[0] === lastEntryId,
67 useEffect((): any => {
69 const observer = new IntersectionObserver(handleIntersection, {
71 rootMargin: '0px -30px 0px 0px',
74 // We are adding observers to child elements of the container div
75 // with ref as navRef. Notice that we are adding observers
76 // only if we have the data attribute targetid on the child element
78 Array.from(navRef.current.children).forEach((item: any) => {
79 if (item.dataset.targetid) {
80 observer.observe(item);
84 observer.disconnect();
86 // eslint-disable-next-line
89 const numHidden = (visMap: {}) => {
90 return Object.values(visMap).filter((x) => x === false).length;
95 className={classes.toolbarWrapper}
98 {React.Children.map(children, (child) => {
99 return React.cloneElement(child, {
100 className: classnames(child.props.className, {
101 [classes.visible]: !!visibilityMap[child.props['data-targetid']],
102 [classes.inVisible]: !visibilityMap[child.props['data-targetid']],
106 {numHidden(visibilityMap) >= 2 && (
108 visibilityMap={visibilityMap}
109 className={classes.overflowStyle}