-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
index.js
53 lines (49 loc) · 1.42 KB
/
index.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
/** @jsx jsx */
import React from 'react'
import { jsx } from 'theme-ui'
import { Link } from 'gatsby'
import { useDocs, useCurrentDoc } from 'docz'
import { get } from 'lodash/fp'
import * as styles from './styles'
const getHeadings = (route, docs) => {
const doc = docs.find(doc => doc.route === route)
const headings = get('headings', doc)
return headings ? headings.filter(heading => heading.depth === 2) : []
}
const getCurrentHash = () => {
if (typeof window === 'undefined') {
return ''
}
return window.location ? decodeURI(window.location.hash) : ''
}
export const NavLink = React.forwardRef(({ item, ...props }, ref) => {
const docs = useDocs()
const to = item.route
const headings = docs && getHeadings(to, docs)
const current = useCurrentDoc()
const isCurrent = item.route === current.route
const showHeadings = isCurrent && headings && headings.length > 0
const currentHash = getCurrentHash()
return (
<React.Fragment>
<Link
{...props}
to={to}
sx={styles.link}
activeClassName="active"
ref={ref}
/>
{showHeadings &&
headings.map(heading => (
<Link
key={heading.slug}
to={`${to}#${heading.slug}`}
sx={styles.smallLink}
className={currentHash === `#${heading.slug}` ? 'active' : ''}
>
{heading.value}
</Link>
))}
</React.Fragment>
)
})