UNPKG

vcc-ui

Version:

A React library for building user interfaces at Volvo Cars

111 lines (110 loc) 2.73 kB
import { createKeyboardNavigation } from '@volvo-cars/react-aria'; import PropTypes from 'prop-types'; import React, { forwardRef, useEffect, useState } from 'react'; import { useTheme } from '../../styling/use-theme'; import { Block } from '../block'; export const { useKeyboardNavigation, KeyboardNavigationProvider } = createKeyboardNavigation(); const hideOnScrollOffsetTop = 80; const navStyle = _ref => { let { theme, sticky, hideOnScroll, isVisible } = _ref; return { position: 'relative', zIndex: 10, width: '100%', background: theme.color.background.primary, boxSizing: 'border-box', ':before': { content: "''", display: 'block', background: theme.color.ornament.divider, height: 1, outline: 'none', position: 'absolute', left: 0, right: 0, zIndex: -1, bottom: 0 }, extend: [{ condition: sticky, style: { position: 'fixed', top: 0, left: 0 } }, { condition: hideOnScroll, style: { transition: 'transform 200ms ease-out' } }, { condition: !isVisible, style: { transform: 'translateY(-100%)' } }] }; }; // using an external variable for performance reasons let previousScrollY = 0; /** * @deprecated Use `<nav>` element instead. */ export const Nav = /*#__PURE__*/forwardRef((_ref2, ref) => { let { hideOnScroll = false, sticky = false, children } = _ref2; const [isVisible, setVisible] = useState(true); const theme = useTheme(); useEffect(() => { const toggleVisibility = () => { if (window.scrollY > previousScrollY) { if (isVisible && window.scrollY > hideOnScrollOffsetTop) { setVisible(false); } } else { if (!isVisible) { setVisible(true); } } previousScrollY = window.scrollY; }; if (hideOnScroll) { window.addEventListener('scroll', toggleVisibility); } return () => { window.removeEventListener('scroll', toggleVisibility); }; }, [hideOnScroll, isVisible]); const styleProps = { sticky, hideOnScroll, isVisible, theme }; return /*#__PURE__*/React.createElement(Block, { as: "nav", ref: ref, extend: navStyle(styleProps) }, /*#__PURE__*/React.createElement(KeyboardNavigationProvider, null, children)); }); Nav.displayName = 'Nav'; Nav.propTypes = { /** Automatically hide the sticky navigation if the user starts scrolling */ hideOnScroll: PropTypes.bool, /** Make the navigation stick to the top of the viewport */ sticky: PropTypes.bool, /** A JSX node */ // @ts-ignore children: PropTypes.node };