moved read progress to separate component
This commit is contained in:
parent
3bb45c3b10
commit
825d23d5ea
2 changed files with 65 additions and 58 deletions
63
source/src/components/ReadProgress.tsx
Normal file
63
source/src/components/ReadProgress.tsx
Normal file
|
@ -0,0 +1,63 @@
|
|||
import { useCallback, useEffect, useState } from "react"
|
||||
import { useLocation } from "react-router-dom"
|
||||
import styled from "styled-components"
|
||||
|
||||
import theming from "../styles/theming"
|
||||
|
||||
const StyledReadProgressBackground = styled.div`
|
||||
height: 2px;
|
||||
background-color: darkslategray;
|
||||
`
|
||||
|
||||
const StyledReadProgress = styled.div`
|
||||
height: 100%;
|
||||
background-color: ${(props) =>
|
||||
theming.theme(props.theme.currentTheme, {
|
||||
light: theming.light.color1,
|
||||
dark: theming.dark.color1,
|
||||
})};
|
||||
`
|
||||
|
||||
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
|
||||
const scrollHandler = useCallback(() => {
|
||||
setScroll(((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
scrollHandler()
|
||||
})
|
||||
|
||||
resizeObserver.observe(document.body)
|
||||
window.addEventListener("scroll", scrollHandler)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
window.removeEventListener("scroll", scrollHandler)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// update on path change
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
scrollHandler()
|
||||
}, 100)
|
||||
}, [location])
|
||||
|
||||
return (
|
||||
<StyledReadProgressBackground>
|
||||
<StyledReadProgress style={{ width: `${scroll}%` }} />
|
||||
</StyledReadProgressBackground>
|
||||
)
|
||||
}
|
||||
|
||||
export default ReadProgress
|
Loading…
Add table
Add a link
Reference in a new issue