-
Notifications
You must be signed in to change notification settings - Fork 0
/
useLocales.ts
58 lines (52 loc) · 1.67 KB
/
useLocales.ts
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
import { useStaticQuery, graphql } from "gatsby"
import { useLocation } from "@reach/router"
import type { AllLocalesQuery } from "../../graphql-types"
type I18n = NonNullable<AllLocalesQuery["allFile"]["nodes"][number]["childI18NJson"]>
export type Locale = {
id: string
} & {
[K in keyof I18n]: NonNullable<I18n[K]>
}
/**
* Gatsby really wants to push everything, even simple stuff like JSON files in
* a project folder, through a complicated GraphQL pipeline. This hook hides the
* details of looking up the locale files in the `i18n` folder and makes them
* easily accessible to any component that needs them.
*
* @returns the list of all `locales`, as well as the current `locale` given by the URL
*/
export default function useLocales(): { locales: Locale[]; locale?: Locale } {
const { allFile }: AllLocalesQuery = useStaticQuery(
graphql`
query AllLocales {
allFile(filter: { sourceInstanceName: { eq: "i18n" }, extension: {eq: "json"}}) {
nodes {
name
childI18NJson {
viewIn
langPicker
title
description
calendarEvent
connectWallet
signOut
myNFTs
nextNFT
prevNFT
close
zoomIn
zoomOut
}
}
}
}
`
)
const { pathname } = useLocation()
const locales = allFile.nodes.map(node => ({
id: node.name,
...node.childI18NJson!,
}) as Locale) // type coercion removes the `| null` that GraphQL includes
const locale = locales.find(l => new RegExp(`/${l.id}`).test(pathname))
return { locales, locale }
}