Skip to content

Commit

Permalink
use official gatsby i18n theme
Browse files Browse the repository at this point in the history
  • Loading branch information
pettinarip committed Jul 12, 2022
1 parent c121309 commit be58015
Show file tree
Hide file tree
Showing 72 changed files with 739 additions and 218 deletions.
2 changes: 1 addition & 1 deletion docs/best-practices.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Markdown will be translated as whole pages of content, so no specific action is
- **Method two: `translateMessageId()`**

```tsx
import { useIntl } from "gatsby-plugin-intl"
import { useIntl } from "react-intl"
import { translateMessageId } from "src/utils/translations"
// Utilize anywhere in JS using
Expand Down
49 changes: 45 additions & 4 deletions gatsby-browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
*/

import React from "react"
import Layout from "./src/components/Layout"
import browserLang from "browser-lang"
import { withPrefix, GatsbyBrowser } from "gatsby"

import Prism from "prism-react-renderer/prism"
;(typeof global !== "undefined" ? global : window).Prism = Prism
Expand All @@ -15,12 +16,52 @@ import "@formatjs/intl-locale/polyfill"
import "@formatjs/intl-numberformat/polyfill"
import "@formatjs/intl-numberformat/locale-data/en"

import Layout from "./src/components/Layout"
import {
Lang,
supportedLanguages,
defaultLanguage,
} from "./src/utils/languages"
import { Context } from "./src/types"

// Default languages included:
// https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js
require("prismjs/components/prism-solidity")

// Prevents <Layout/> from unmounting on page transitions
// https://www.gatsbyjs.com/docs/layout-components/#how-to-prevent-layout-components-from-unmounting
export const wrapPageElement = ({ element, props }) => (
<Layout {...props}>{element}</Layout>
)
export const wrapPageElement: GatsbyBrowser<
any,
Context
>["wrapPageElement"] = ({ element, props }) => {
const { location, pageContext } = props
const { pathname, search } = location
const { originalPath } = pageContext

const [, pathLocale] = pathname.split("/")

// client side redirect on paths that don't have a locale in them. Most useful
// on dev env where we don't have server redirects
if (!supportedLanguages.includes(pathLocale as Lang)) {
let detected =
window.localStorage.getItem("eth-org-language") ||
browserLang({
languages: supportedLanguages,
fallback: defaultLanguage,
})

if (!supportedLanguages.includes(detected as Lang)) {
detected = defaultLanguage
}

const queryParams = search || ""
const newUrl = withPrefix(`/${detected}${originalPath}${queryParams}`)
window.localStorage.setItem("eth-org-language", detected)
window.location.replace(newUrl)

// can't return null here, must return an element
return <div />
}

return <Layout {...props}>{element}</Layout>
}
22 changes: 12 additions & 10 deletions gatsby-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from "path"
import type { GatsbyConfig } from "gatsby"

import {
buildLangs,
supportedLanguages,
defaultLanguage,
ignoreLanguages,
Expand Down Expand Up @@ -37,17 +38,18 @@ const config: GatsbyConfig = {
plugins: [
// i18n support
{
resolve: `gatsby-plugin-intl`,
resolve: `gatsby-theme-i18n`,
options: {
// language JSON resource path
path: path.resolve(`src/intl`),
// supported language
languages: supportedLanguages,
// language file path
defaultLanguage,
// redirect to `/${lang}/` when connecting to `/`
// based on user's browser language preference
redirect: true,
defaultLang: defaultLanguage,
prefixDefault: true,
locales: buildLangs.length ? buildLangs.join(" ") : null,
configPath: path.resolve(`./i18n/config.json`),
},
},
{
resolve: `gatsby-theme-i18n-react-intl`,
options: {
defaultLocale: `./src/intl/en.json`,
},
},
// Web app manifest
Expand Down
81 changes: 38 additions & 43 deletions gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
defaultLanguage,
Lang,
} from "./src/utils/languages"
import getMessages from "./src/utils/getMessages"
import redirects from "./redirects.json"

const exec = util.promisify(child_process.exec)
Expand Down Expand Up @@ -153,9 +152,6 @@ export const onCreateNode: GatsbyNode<{

if (slug.includes("/translations/")) {
slug = slug.replace("/translations", "")
const split = slug.split("/")
split.splice(1, 1)

isOutdated = await checkIsMdxOutdated(node.fileAbsolutePath)
} else {
slug = `/${defaultLanguage}${slug}`
Expand Down Expand Up @@ -193,6 +189,7 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
}) => {
const { createPage, createRedirect } = actions

// server side redirects
redirects.forEach((redirect) => {
createRedirect({
...redirect,
Expand Down Expand Up @@ -271,27 +268,22 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
const splitSlug = slug.split("/")
splitSlug.splice(1, 1, lang)
const langSlug = splitSlug.join("/")
createPage({
createPage<Context>({
path: langSlug,
component: path.resolve(`src/templates/${template}.tsx`),
context: {
language: lang,
slug: langSlug,
ignoreTranslationBanner: isLegal,
isLegal: isLegal,
isOutdated: false,
isContentEnglish: true,
relativePath: relativePath, // Use English path for template MDX query
// Create `intl` object so `gatsby-plugin-intl` will skip
// generating language variations for this page
intl: {
language: lang,
defaultLanguage,
languages: supportedLanguages,
messages: getMessages("./src/intl/", lang),
routed: true,
originalPath: slug.substr(3),
redirect: false,
},
relativePath, // Use English path for template MDX query
// gatsby i18n theme context
locale: lang,
hrefLang: lang,
originalPath: langSlug.slice(3),
dateFormat: "MM/DD/YYYY",
},
})
}
Expand All @@ -305,18 +297,13 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
language,
slug,
isOutdated: !!node.fields.isOutdated,
relativePath: relativePath,
// Create `intl` object so `gatsby-plugin-intl` will skip
// generating language variations for this page
intl: {
language,
defaultLanguage,
languages: supportedLanguages,
messages: getMessages("./src/intl/", language),
routed: true,
originalPath: slug.substr(3),
redirect: false,
},
isDefaultLang: language === defaultLanguage,
relativePath,
// gatsby i18n theme context
locale: language,
hrefLang: language,
originalPath: slug.slice(3),
dateFormat: "MM/DD/YYYY",
},
})
})
Expand All @@ -338,22 +325,22 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
page,
lang
)
createPage({
path: `/${lang}/${page}/`,
const originalPath = `/${page}/`
const slug = `/${lang}${originalPath}`

createPage<Context>({
path: slug,
component: path.resolve(`src/pages-conditional/${page}.tsx`),
context: {
slug: `/${lang}/${page}/`,
intl: {
language: lang,
languages: supportedLanguages,
defaultLanguage,
messages: getMessages("./src/intl/", lang),
routed: true,
originalPath: `/${page}/`,
redirect: false,
},
language: lang,
slug,
isContentEnglish,
isOutdated,
// gatsby i18n theme context
locale: lang,
hrefLang: lang,
originalPath,
dateFormat: "MM/DD/YYYY",
},
})
}
Expand All @@ -370,12 +357,20 @@ export const onCreatePage: GatsbyNode<any, Context>["onCreatePage"] = async ({
}) => {
const { createPage, deletePage } = actions

const isTranslated = page.context.language !== defaultLanguage
// create routes without the lang prefix e.g. `/{path}` as our i18n plugin
// only creates `/{lang}/{path}` routes. This is useful on dev env to avoid
// getting a 404 since we don't have server side redirects
if (page.path.startsWith(`/${defaultLanguage}`)) {
const path = page.path.slice(3)
createPage({ ...page, path })
}

const isTranslated = page.context.locale !== defaultLanguage
const hasNoContext = page.context.isOutdated === undefined

if (isTranslated && hasNoContext) {
const { isOutdated, isContentEnglish } = await checkIsPageOutdated(
page.context.intl.originalPath,
page.path,
page.context.language
)
deletePage(page)
Expand Down
4 changes: 3 additions & 1 deletion gatsby-ssr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import type { GatsbySSR } from "gatsby"

import Layout from "./src/components/Layout"

import { Context } from "./src/types"

// Prevents <Layout/> from unmounting on page transitions
// https://www.gatsbyjs.com/docs/layout-components/#how-to-prevent-layout-components-from-unmounting
export const wrapPageElement: GatsbySSR["wrapPageElement"] = ({
export const wrapPageElement: GatsbySSR<any, Context>["wrapPageElement"] = ({
element,
props,
}) => {
Expand Down
Loading

0 comments on commit be58015

Please sign in to comment.