Skip to content

Commit

Permalink
chore: add with-i18n example
Browse files Browse the repository at this point in the history
  • Loading branch information
Daydreamer-riri committed Nov 29, 2024
1 parent f3e66a8 commit 196d55a
Show file tree
Hide file tree
Showing 24 changed files with 609 additions and 208 deletions.
11 changes: 11 additions & 0 deletions examples/with-i18n/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
23 changes: 23 additions & 0 deletions examples/with-i18n/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "with-i18n",
"type": "module",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite-react-ssg dev",
"build": "vite-react-ssg build",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"i18next": "^24.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^15.1.2"
},
"devDependencies": {
"vite": "catalog:",
"vite-plugin-pages": "^0.32.0",
"vite-react-ssg": "workspace:*"
}
}
1 change: 1 addition & 0 deletions examples/with-i18n/public/react.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/with-i18n/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions examples/with-i18n/src/@types/i18next.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import 'i18next'
import type { resources } from '../i18n'

declare module 'i18next' {
interface CustomTypeOptions {
defaultNS: 'translation'
resources: typeof resources['en']
}
}
42 changes: 42 additions & 0 deletions examples/with-i18n/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
32 changes: 32 additions & 0 deletions examples/with-i18n/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { RouteRecord } from 'vite-react-ssg'
import './App.css'
import Layout from './Layout'
import { resources } from './i18n'

export const routes: RouteRecord[] = [
{
path: '/:lng',
Component: Layout,
getStaticPaths: () => Object.keys(resources),
children: [
{
path: 'a',
lazy: () => import('./pages/a'),
},
{
index: true,
lazy: () => defaultToComponent(import('./pages/index')),
},
{
path: 'nest/:b',
lazy: () => defaultToComponent(import('./pages/nest/[b]')),
},
],
},
]

async function defaultToComponent(routePromise: Promise<RouteRecord & { default: any }>) {
const routeModule = await routePromise

return { ...routeModule, Component: routeModule.default }
}
42 changes: 42 additions & 0 deletions examples/with-i18n/src/Layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Suspense, useState } from 'react'
import { Outlet } from 'react-router-dom'
import { Head } from 'vite-react-ssg'
import './layout.css'
import { useTranslation } from 'react-i18next'
import { I18n, useI18n, useSyncLng } from './i18n'

export default function Layout() {
return (
<I18n>
<LayoutContent />
</I18n>
)
}

function LayoutContent() {
useSyncLng()
const [state, setState] = useState(false)
const { changeLng, getLng } = useI18n()
const { t } = useTranslation()

return (
<>
<Head>
<meta charSet="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/react.svg" />
<title>head test {state ? 'A' : 'B'}</title>
<body className={`body-class-in-head-${state ? 'a' : 'b'}`} />
</Head>
<main>
<h1 className="layout">{t('layout.head')}</h1>
<Suspense>
<Outlet />
</Suspense>
<div style={{ flexDirection: 'column', display: 'flex', gap: 8 }}>
<button type="button" onClick={() => setState(v => !v)}>{t('layout.change_title')}</button>
<button type="button" onClick={() => changeLng(getLng() === 'zh' ? 'en' : 'zh')}>{t('layout.change_lng')}</button>
</div>
</main>
</>
)
}
1 change: 1 addition & 0 deletions examples/with-i18n/src/assets/react.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions examples/with-i18n/src/components/a-count.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.a-count {
color: pink;
}
16 changes: 16 additions & 0 deletions examples/with-i18n/src/components/a-count.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useState } from 'react'
import './a-count.css'

export default function ACount() {
const [count, setCount] = useState(0)

return (
<button
type="button"
className="a-count"
onClick={() => setCount(prev => ++prev)}
>
{count}
</button>
)
}
5 changes: 5 additions & 0 deletions examples/with-i18n/src/components/load-comp-1.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default function LoadComp1() {
return (
<div>Load component 1</div>
)
}
106 changes: 106 additions & 0 deletions examples/with-i18n/src/i18n.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { I18nContext, I18nextProvider } from 'react-i18next'
import './@types/i18next.d.ts'
import { useLocation, useNavigate } from 'react-router-dom'
import type { ReactNode } from 'react'
import { useContext, useEffect, useRef } from 'react'
import type { i18n } from 'i18next'
import { createInstance } from 'i18next'

export const resources = {
en: {
translation: {
hello: 'Hello',
layout: {
head: 'Layout',
change_title: 'layout change title',
change_lng: 'change language',
},
to: 'TO',
edit: 'Edit',
hmr: 'and save to test HMR',
desc: 'Click on the Vite and React logos to learn more',
},
},
zh: {
translation: {
hello: '你好',
layout: {
head: '布局',
change_title: '更改标题',
change_lng: '更改语言',
},
to: '跳转至',
edit: '编辑',
hmr: '并保存以测试HMR',
desc: '点击 Vite 和 React 徽标了解更多信息',
},
},
} as const

export function I18n({ children }: { children: ReactNode }) {
const { pathname } = useLocation()
const currentLng = pathname.split('/')[1]
const i18nRef = useRef<null | i18n>(null)
if (!i18nRef.current) {
i18nRef.current = createInstance({ lng: currentLng, defaultNS: 'translation', ns: ['translation'], resources })
i18nRef.current.init()
}

return (
<I18nextProvider i18n={i18nRef.current}>
{children}
</I18nextProvider>
)
}

const lngs = Object.keys(resources)

export function useSyncLng() {
const { pathname } = useLocation()
const currentLng = pathname.split('/')[1]
const { i18n } = useContext(I18nContext)

const nav = useNavigate()
useEffect(() => {
if (!lngs.includes(currentLng)) {
nav('/en')
return
}
if (currentLng !== i18n.language) {
i18n.changeLanguage(currentLng)
}
}, [nav, currentLng, i18n])
}

export function useI18n() {
const nav = useNavigate()
const { pathname, search } = useLocation()

function withLngBase(path: string) {
if (!path.startsWith('/')) {
path = `/${path}`
}
if (path === '/') {
path = ''
}
return `/${getLng()}${path}`
}

function getLng() {
return pathname.split('/')[1]
}

const changeLng = (lng: keyof typeof resources) => {
const originLng = getLng()
nav({ pathname: pathname.replace(`/${originLng}`, `/${lng}`), search }, { replace: true })
}

const { i18n } = useContext(I18nContext)

return {
withLngBase,
getLng,
changeLng,
i18n,
}
}
69 changes: 69 additions & 0 deletions examples/with-i18n/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;

color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;

font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}

a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}

body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}

h1 {
font-size: 3.2em;
line-height: 1.1;
}

button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}

@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
3 changes: 3 additions & 0 deletions examples/with-i18n/src/layout.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.layout {
color: #333;
}
10 changes: 10 additions & 0 deletions examples/with-i18n/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { ViteReactSSG } from 'vite-react-ssg'
import { routes } from './App'
import './index.css'

export const createRoot = ViteReactSSG(
{
routes,
basename: import.meta.env.BASE_URL,
},
)
3 changes: 3 additions & 0 deletions examples/with-i18n/src/pages/a.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.a {
color: red;
}
Loading

0 comments on commit 196d55a

Please sign in to comment.