/
link.js
71 lines (60 loc) · 1.7 KB
/
link.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
import React from "react"
import PropTypes from "prop-types"
import { Link as GatsbyLink, navigate as gatsbyNavigate } from "gatsby"
import { IntlContextConsumer } from "./intl-context"
const Link = ({ to, language, children, onClick, ...rest }) => (
<IntlContextConsumer>
{intl => {
const languageLink = language || intl.language
const link = intl.routed || language ? `/${languageLink}${to}` : `${to}`
const handleClick = e => {
if (language) {
localStorage.setItem("gatsby-intl-language", language)
}
if (onClick) {
onClick(e)
}
}
return (
<GatsbyLink {...rest} to={link} onClick={handleClick}>
{children}
</GatsbyLink>
)
}}
</IntlContextConsumer>
)
Link.propTypes = {
children: PropTypes.node.isRequired,
to: PropTypes.string,
language: PropTypes.string,
}
Link.defaultProps = {
to: "",
}
export default Link
export const navigate = (to, options) => {
if (typeof window === "undefined") {
return
}
const { language, routed } = window.___gatsbyIntl
const link = routed ? `/${language}${to}` : `${to}`
gatsbyNavigate(link, options)
}
export const changeLocale = (language, to) => {
if (typeof window === "undefined") {
return
}
const { routed } = window.___gatsbyIntl
const removeLocalePart = pathname => {
if (!routed) {
return pathname
}
const i = pathname.indexOf(`/`, 1)
return pathname.substring(i)
}
const pathname = to || removeLocalePart(window.location.pathname)
// TODO: check slash
const link = `/${language}${pathname}${window.location.search}`
localStorage.setItem("gatsby-intl-language", language)
gatsbyNavigate(link)
}