-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
index.js
119 lines (105 loc) · 2.98 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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*global __PREFIX_PATHS__, __PATH_PREFIX__ */
import React from "react"
import { Link, NavLink } from "react-router-dom"
import PropTypes from "prop-types"
let pathPrefix = `/`
if (typeof __PREFIX_PATHS__ !== `undefined` && __PREFIX_PATHS__) {
pathPrefix = __PATH_PREFIX__
}
function normalizePath(path) {
return path.replace(/^\/\//g, `/`)
}
const NavLinkPropTypes = {
activeClassName: PropTypes.string,
activeStyle: PropTypes.object,
exact: PropTypes.bool,
strict: PropTypes.bool,
isActive: PropTypes.func,
location: PropTypes.object,
}
class GatsbyLink extends React.Component {
constructor(props) {
super()
this.state = {
to: normalizePath(pathPrefix + props.to),
}
}
componentWillReceiveProps(nextProps) {
if (this.props.to !== nextProps.to) {
this.setState({
to: normalizePath(pathPrefix + nextProps.to),
})
___loader.enqueue(this.state.to)
}
}
componentDidMount() {
___loader.enqueue(this.state.to)
}
render() {
const { onClick, ...rest } = this.props
let El
if (Object.keys(NavLinkPropTypes).some(propName => this.props[propName])) {
El = NavLink
} else {
El = Link
}
return (
<El
onClick={e => {
// eslint-disable-line
onClick && onClick(e)
if (
e.button === 0 && // ignore right clicks
!this.props.target && // let browser handle "target=_blank"
!e.defaultPrevented && // onClick prevented default
!e.metaKey && // ignore clicks with modifier keys...
!e.altKey &&
!e.ctrlKey &&
!e.shiftKey
) {
// Is this link pointing to a hash on the same page? If so,
// just scroll there.
let pathname = this.state.to
if (pathname.split(`#`).length > 1) {
pathname = pathname
.split(`#`)
.slice(0, -1)
.join(``)
}
if (pathname === window.location.pathname) {
const hashFragment = this.state.to
.split(`#`)
.slice(1)
.join(`#`)
const element = document.getElementById(hashFragment)
if (element !== null) {
element.scrollIntoView()
return true
}
}
// In production, make sure the necessary scripts are
// loaded before continuing.
if (process.env.NODE_ENV === `production`) {
e.preventDefault()
window.___navigateTo(this.state.to)
}
}
}}
{...rest}
to={this.state.to}
/>
)
}
}
GatsbyLink.propTypes = {
...NavLinkPropTypes,
to: PropTypes.string.isRequired,
onClick: PropTypes.func,
}
GatsbyLink.contextTypes = {
router: PropTypes.object,
}
export default GatsbyLink
export const navigateTo = pathname => {
window.___navigateTo(normalizePath(pathPrefix + pathname))
}