import React, { FC, ReactType, ReactNode, useState, useEffect } from 'react'; import LogoRawSVG from '../../assets/icons/logo-raw.svg'; import DefaultLink, { LinkProps } from '../../blocks/Link'; import css from './index.module.css'; import classnames from 'classnames'; import { MilaGridColumn } from '../../index'; import GridContainer from '../../grid/GridContainer'; import { useSpring, animated } from 'react-spring'; import usePrevious from '../../hooks/usePrevious'; import { throttle } from 'lodash'; export interface HeaderProps { variant?: string; claim?: string; Navigation: ReactType; Link?: ReactType; LinkProps?: LinkProps; children?: ReactNode; } const getScrollPosition = (): { x: number; y: number } => { const target = document.body; const position = target.getBoundingClientRect(); return { x: position.left, y: position.top }; }; const Header: FC = ({ claim, Link = DefaultLink, LinkProps, Navigation, variant, }) => { const [sticky, setSticky] = useState(false); const [minScroll, setMinScroll] = useState(false); const prevScroll = usePrevious(minScroll); const [clientHeight, setClientHeight] = useState(0); const [currPos, setCurrPos] = useState(null); const prevPos = usePrevious(currPos); const [isMobileNavOpen, setIsMobileNavOpen] = useState(false); const contentProps = useSpring({ transform: sticky || !minScroll ? 'translateY(0%)' : 'translateY(-110%)', position: minScroll ? 'fixed' : 'absolute', config: { duration: !prevScroll ? 0 : 300 }, }); const handleScroll = (e): void => { const currentHeight = e.target.body.clientHeight; setClientHeight(currentHeight); if (!prevPos || clientHeight === currentHeight) { const pos = getScrollPosition(); setCurrPos(pos); // @ts-ignore const isShow = pos.y > (prevPos ? prevPos.y : 0) && Math.abs(pos.y) > 400; setMinScroll(Math.abs(pos.y) > 400); if (isShow !== sticky) { setSticky(isShow); } } setClientHeight(currentHeight); }; useEffect(() => { const throttledCount = throttle(handleScroll, 300); window.addEventListener('scroll', throttledCount); return (): void => window.removeEventListener('scroll', throttledCount); }); return (
{claim ? ( <>
) : ( )}
{Navigation && ( { document.body.style.overflow = open ? 'hidden' : ''; setIsMobileNavOpen(open); }} /> )}
); }; export default Header;