/
section-nav.js
executable file
·97 lines (88 loc) · 2.39 KB
/
section-nav.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import PropTypes from 'prop-types'
import React, {useEffect, useState} from 'react'
import Slugger from 'github-slugger'
import striptags from 'striptags'
import styled from '@emotion/styled'
import useScroll from 'react-use/lib/useScroll'
import useWindowSize from 'react-use/lib/useWindowSize'
import {colors} from 'gatsby-theme-base'
import {trackEvent} from '../utils'
const StyledList = styled.ul({
marginLeft: 0,
marginBottom: 48,
overflow: 'auto'
})
const StyledListItem = styled.li(props => ({
listStyle: 'none',
fontSize: '1rem',
color: props.active && colors.primary,
a: {
color: 'inherit',
textDecoration: 'none',
':hover': {
opacity: colors.hoverOpacity
}
}
}))
function handleHeadingClick(event) {
trackEvent({
eventCategory: 'Section Nav',
eventAction: 'heading click',
eventLabel: event.target.innerText
})
}
export default function SectionNav(props) {
const {y} = useScroll(props.mainRef)
const {width, height} = useWindowSize()
const [offsets, setOffsets] = useState([])
const {contentRef, imagesLoaded} = props
useEffect(() => {
const headings = contentRef.current.querySelectorAll('h1, h2')
setOffsets(
Array.from(headings)
.map(heading => {
const anchor = heading.querySelector('a')
if (!anchor) {
return null
}
return {
id: heading.id,
offset: anchor.offsetTop
}
})
.filter(Boolean)
)
}, [width, height, contentRef, imagesLoaded])
let activeHeading = null
const windowOffset = height / 2
const scrollTop = y + windowOffset
for (let i = offsets.length - 1; i >= 0; i--) {
const {id, offset} = offsets[i]
if (scrollTop >= offset) {
activeHeading = id
break
}
}
const slugger = new Slugger()
return (
<StyledList>
{props.headings.map(({value}) => {
const text = striptags(value)
const slug = slugger.slug(text)
return (
<StyledListItem key={slug} active={slug === activeHeading}>
<a href={`#${slug}`} onClick={handleHeadingClick}>
{text}
</a>
</StyledListItem>
)
})}
</StyledList>
)
}
SectionNav.propTypes = {
headings: PropTypes.array.isRequired,
imagesLoaded: PropTypes.bool.isRequired,
mainRef: PropTypes.object.isRequired,
contentRef: PropTypes.object.isRequired
}