From b977e3f9ec6efce6d9559b7726e5c5b833d83759 Mon Sep 17 00:00:00 2001 From: developomp Date: Tue, 18 Jan 2022 12:12:23 +0900 Subject: [PATCH] update read progress on path change (close #33) --- source/src/components/Navbar.tsx | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/source/src/components/Navbar.tsx b/source/src/components/Navbar.tsx index 4c3b259..4d656f9 100644 --- a/source/src/components/Navbar.tsx +++ b/source/src/components/Navbar.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from "react" import styled from "styled-components" -import { Link } from "react-router-dom" +import { Link, useLocation } from "react-router-dom" import ReactTooltip from "react-tooltip" import { isMobile } from "react-device-detect" @@ -76,20 +76,21 @@ const StyledReadProgress = styled.div` })}; ` +const st = "scrollTop" +const sh = "scrollHeight" +const h = document.documentElement +const b = document.body + const ReadProgress = () => { const [scroll, setScroll] = useState(0) + const location = useLocation() + + // https://stackoverflow.com/a/8028584/12979111 + function scrollHandler() { + setScroll(((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100) + } useEffect(() => { - const st = "scrollTop" - const sh = "scrollHeight" - const scrollHandler = () => { - const h = document.documentElement - const b = document.body - - // https://stackoverflow.com/a/8028584/12979111 - setScroll(((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100) - } - window.addEventListener("scroll", scrollHandler) return () => { @@ -97,6 +98,15 @@ const ReadProgress = () => { } }, []) + // update on path change + useEffect(() => { + setTimeout(() => { + window.scrollTo({ top: 0, behavior: "smooth" }) + + scrollHandler() + }, 100) + }, [location]) + return }