diff --git a/src/components/common/Nav.tsx b/src/components/common/Nav.tsx index 0198795..c907f54 100644 --- a/src/components/common/Nav.tsx +++ b/src/components/common/Nav.tsx @@ -1,13 +1,25 @@ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import tw, { styled, theme } from 'twin.macro'; import { Icon } from '~/components/ui/icons/Icon'; import { Link } from 'gatsby'; import { Groups } from '~/components/ui/groups/Groups'; import cn from 'classnames'; +import { useStateRef } from '~/utils/hooks/basic'; +import { offsetToDocument } from '~/utils/dom/offset'; -const Root = styled.nav` +const Root = styled.nav<{ sticky: boolean }>` ${tw`bg-blue-600 flex flex-col sm:flex-row sm:items-center justify-between text-white relative`} min-height: 2rem; + ${({ sticky }) => + sticky && + ` + position: fixed!important; + min-width: 100%; + top: 0; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .1); + transition: all .25s ease-in; + z-index: 1; + `} `; const NavLink = styled(Link)` @@ -38,7 +50,7 @@ const HamburgerButton = styled.button<{ open: boolean }>` open && ` transform: rotate(45deg) - translateY(0px); + translateY(0px); `} } @@ -49,7 +61,7 @@ const HamburgerButton = styled.button<{ open: boolean }>` open && ` transform: rotate(-45deg) - translateY(0px); + translateY(0px); `} } @@ -60,8 +72,29 @@ const HamburgerButton = styled.button<{ open: boolean }>` export function Nav({ profile: { github, linkedin, facebook } }) { const [open, setOpen] = useState(false); + const [stickyGetter, setSticky] = useStateRef(false); + + useEffect(() => { + const content = document.getElementById('content'); + const { top: bodyTop } = offsetToDocument(content); + function listener() { + if (window.scrollY >= bodyTop) { + if (!stickyGetter()) { + setSticky(true); + } + } else { + if (stickyGetter()) { + setSticky(false); + } + } + } + window.addEventListener('scroll', listener); + return () => { + window.removeEventListener('scroll', listener); + }; + }, []); return ( - +
- + Home + + Projects +
); diff --git a/src/components/home/HomeMain.tsx b/src/components/home/HomeMain.tsx index cf33ea6..c26da45 100644 --- a/src/components/home/HomeMain.tsx +++ b/src/components/home/HomeMain.tsx @@ -18,7 +18,7 @@ const Root = tw.div` `; export default function HomeMain({ profile }: { profile: typeof userProfile }) { return ( - + diff --git a/src/utils/dom/offset.ts b/src/utils/dom/offset.ts new file mode 100644 index 0000000..06d1f04 --- /dev/null +++ b/src/utils/dom/offset.ts @@ -0,0 +1,9 @@ +export function offsetToDocument(el) { + if (!el) { + return { top: 0, left: 0 }; + } + const rect = el.getBoundingClientRect(), + scrollLeft = window.pageXOffset || document.documentElement.scrollLeft, + scrollTop = window.pageYOffset || document.documentElement.scrollTop; + return { top: rect.top + scrollTop, left: rect.left + scrollLeft }; +}