Skip to content

Commit

Permalink
fix: navigation closes when window size shrinks, add overlay fade
Browse files Browse the repository at this point in the history
  • Loading branch information
vpicone committed May 21, 2019
1 parent 7e27122 commit 36bd5fe
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions packages/gatsby-theme-carbon/src/components/Container.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext } from 'react';
import React, { useContext, useEffect, useRef, useCallback } from 'react';
import styled from '@emotion/styled';
import NavContext from '../util/context/NavContext';
import useWindowSize from '../util/hooks/useWindowSize';
Expand All @@ -10,27 +10,45 @@ const Overlay = styled.div`
position: fixed;
background: rgba(0, 0, 0, 0.25);
transition: all 0.15s ease;
pointer-events: ${({ visible }) => (visible ? 'auto' : 'none')};
opacity: ${({ visible }) => (visible ? 1 : 0)};
transition: opacity 150ms ease;
`;

const Container = ({ children, homepage }) => {
const { leftNavIsOpen, switcherIsOpen, toggleNavState } = useContext(
NavContext
);
const windowSize = useWindowSize();
const closeNavs = () => {
const lastWindowSize = useRef(windowSize);

const closeNavs = useCallback(() => {
toggleNavState('leftNavIsOpen', 'close');
toggleNavState('switcherIsOpen', 'close');
};
}, [toggleNavState]);

useEffect(() => {
const windowShrinking =
lastWindowSize.current &&
lastWindowSize.current.innerWidth > windowSize.innerWidth;
if (windowShrinking && windowSize.innerWidth < 1056) {
closeNavs();
}
lastWindowSize.current = windowSize;
}, [closeNavs, windowSize, windowSize.innerWidth]);

const shouldShowOverlay = () => {
const overlayVisible = (() => {
const navOpen = leftNavIsOpen || switcherIsOpen;
return navOpen && windowSize.innerWidth && windowSize.innerWidth < 1056;
};
})();

return (
<>
{shouldShowOverlay() ? <Overlay onClick={closeNavs} /> : null}
<div className={`${homepage ? 'container--homepage' : 'container'}`}>
<Overlay visible={overlayVisible} onClick={closeNavs} />
<div
aria-hidden={overlayVisible}
className={`${homepage ? 'container--homepage' : 'container'}`}
>
{children}
</div>
</>
Expand Down

0 comments on commit 36bd5fe

Please sign in to comment.