Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ZO: Translation system #2647

Merged
merged 2 commits into from
Jan 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions apps/zzz-frontend/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,5 @@
"cache": false
}
},
"implicitDependencies": [
"common-localization",
"sr-localization",
"sr-dm-localization"
]
"implicitDependencies": ["common-localization", "zzz-localization"]
}
4 changes: 2 additions & 2 deletions apps/zzz-frontend/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ScrollTop } from '@genshin-optimizer/common/ui'
import '@genshin-optimizer/sr/i18n' // import to load translations
import { theme } from '@genshin-optimizer/sr/theme'
import { DatabaseProvider } from '@genshin-optimizer/zzz/db-ui'
import '@genshin-optimizer/zzz/i18n' // import to load translations
import { theme } from '@genshin-optimizer/zzz/theme'
import {
Box,
Container,
Expand Down
4 changes: 2 additions & 2 deletions apps/zzz-frontend/vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ export default defineConfig({
},
{
src: normalizePath(
resolve('../../libs/sr/localization/assets/locales')
resolve('../../libs/zzz/localization/assets/locales')
),
dest: 'assets',
},
{
src: normalizePath(
resolve('../../libs/sr/dm-localization/assets/locales')
resolve('../../libs/zzz/dm-localization/assets/locales')
),
dest: 'assets',
},
Expand Down
12 changes: 10 additions & 2 deletions libs/common/localization/src/executors/gen-locale/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import type { GenLocaleExecutorSchema } from './schema'
* common: /libs/common/localization
* gi: /libs/gi/localization
* sr: /libs/sr/localization
* zzz: /libs/zzz/localization
*/
type ProjNames = 'common' | 'gi' | 'sr'
type ProjNames = 'common' | 'gi' | 'sr' | 'zzz'
export const projRootPath = (cat: ProjNames) =>
`${process.env['NX_WORKSPACE_ROOT']}/libs/${cat}/localization/`

Expand All @@ -25,7 +26,12 @@ export default async function runExecutor(_options: GenLocaleExecutorSchema) {
const json = JSON.parse(raw)
await Promise.all(
Object.entries(json).map(async ([ns, entry]) => {
if (ns.startsWith('sr_')) {
if (ns.startsWith('zzz_')) {
await dumpPrettyFile(
`${localeDir('zzz')}${lang}/${ns.slice(3)}.json`,
entry
)
} else if (ns.startsWith('sr_')) {
await dumpPrettyFile(
`${localeDir('sr')}${lang}/${ns.slice(3)}.json`,
entry
Expand All @@ -52,6 +58,7 @@ export default async function runExecutor(_options: GenLocaleExecutorSchema) {
* common: XXX -> common_XXX
* gi XXX -> XXX (no change due to legacy)
* sr XXX -> sr_XXX
* zzz XXX -> zzz_XXX
*/
const main = {} as { [key: string]: object }

Expand All @@ -70,6 +77,7 @@ export default async function runExecutor(_options: GenLocaleExecutorSchema) {
enToMain(`${localeDir('common')}en/`, 'common_')
enToMain(`${localeDir('gi')}en/`) // do not add prefix to gi files
enToMain(`${localeDir('sr')}en/`, 'sr_')
enToMain(`${localeDir('zzz')}en/`, 'zzz_')
// dump main file to common lib
dumpFile(`${projRootPath('common')}/main_gen.json`, main)

Expand Down
21 changes: 21 additions & 0 deletions libs/zzz/i18n-node/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"parserOptions": {
"project": "libs/zzz/i18n-node/tsconfig.eslint.json"
},
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
3 changes: 3 additions & 0 deletions libs/zzz/i18n-node/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# zzz-i18n-node

This library was generated with [Nx](https://nx.dev).
9 changes: 9 additions & 0 deletions libs/zzz/i18n-node/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "zzz-i18n-node",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/zzz/i18n-node/src",
"projectType": "library",
"tags": [],
"// targets": "to see all targets run: nx show project zzz-i18n-node --web",
"targets": {}
}
58 changes: 58 additions & 0 deletions libs/zzz/i18n-node/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import Backend from 'i18next-fs-backend'
import { initReactI18next } from 'react-i18next'

/**
* @see: https://www.i18next.com/translation-function/essentials
* @see: https://react.i18next.com/latest/using-with-hooks
*/
const i18nInstance = i18n
.createInstance()
// load translation using http ->
// see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// Configure localization.

i18nInstance.init({
// debug: process.env.NODE_ENV === "development",
// Use English strings by default, if the current language does not include
// the specified string.
fallbackLng: 'en',
// fallbackLng: 'dev', // Switch to this to force the fallback value on missing strings.

// List all translation namespaces.
ns: ['charNames_gen', 'relicNames_gen', 'lightConeNames_gen'],
// Specify the default namespace.
defaultNS: 'ui',

// Only use the language code, skipping the region code.
// For example, en-US becomes simply en.
load: 'languageOnly',

returnNull: false,

backend: {
// Path to load localization data from.
loadPath: `${__dirname}/assets/zzz/locales/{{lng}}/{{ns}}.json`,
},
interpolation: {
escapeValue: false, //react does interlopation already
},
})

// https://www.i18next.com/translation-function/formatting#adding-custom-format-function
i18nInstance.services.formatter?.add('percent', (value, _lng, options) => {
return (value * 100).toFixed(options.fixed)
})
i18nInstance.services.formatter?.add('fixed', (value, _lng, options) => {
return value.toFixed(options.fixed)
})

export { i18nInstance }
1 change: 1 addition & 0 deletions libs/zzz/i18n-node/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './i18n'
8 changes: 8 additions & 0 deletions libs/zzz/i18n-node/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": ["node"]
},
"include": ["**/*.ts", "**/*.tsx"]
}
19 changes: 19 additions & 0 deletions libs/zzz/i18n-node/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"module": "commonjs",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
}
]
}
10 changes: 10 additions & 0 deletions libs/zzz/i18n-node/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"declaration": true,
"types": ["node"]
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
}
13 changes: 13 additions & 0 deletions libs/zzz/i18n/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"presets": [
[
"@nx/react/babel",
{
"runtime": "automatic",
"useBuiltIns": "usage",
"importSource": "@emotion/react"
}
]
],
"plugins": ["@emotion/babel-plugin"]
}
21 changes: 21 additions & 0 deletions libs/zzz/i18n/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"extends": ["plugin:@nx/react", "../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"parserOptions": {
"project": "libs/zzz/i18n/tsconfig.eslint.json"
},
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
3 changes: 3 additions & 0 deletions libs/zzz/i18n/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# zzz-i18n

This library was generated with [Nx](https://nx.dev).
8 changes: 8 additions & 0 deletions libs/zzz/i18n/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "zzz-i18n",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/zzz/i18n/src",
"projectType": "library",
"tags": [],
"targets": {}
}
46 changes: 46 additions & 0 deletions libs/zzz/i18n/src/Translate.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
'use client'
import { ColorText, SqBadge, TranslateBase } from '@genshin-optimizer/common/ui'
import '@genshin-optimizer/zzz/theme' // import to validate typing for color variants
import type { ReactNode } from 'react'

const textComponents = {
fire: <ColorText color="fire" />,
ice: <ColorText color="ice" />,
electric: <ColorText color="electric" />,
frost: <ColorText color="frost" />,
physical: <ColorText color="physical" />,
ether: <ColorText color="ether" />,
}

const badgeComponents = {
fire: <SqBadge color="fire" />,
ice: <SqBadge color="ice" />,
electric: <SqBadge color="electric" />,
frost: <SqBadge color="frost" />,
physical: <SqBadge color="physical" />,
ether: <SqBadge color="ether" />,
}

export function Translate({
ns,
key18,
values,
children,
useBadge,
}: {
ns: string
key18: string
values?: Record<string, string | number>
children?: ReactNode
useBadge?: boolean
}) {
return (
<TranslateBase
ns={ns}
key18={key18}
values={values}
children={children}
components={useBadge ? badgeComponents : textComponents}
/>
)
}
75 changes: 75 additions & 0 deletions libs/zzz/i18n/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import Backend from 'i18next-http-backend'
import { initReactI18next } from 'react-i18next'

// Probably a way to auto-populate this.
export const languageCodeList = [
'chs',
'cht',
'de',
'en',
'es',
'fr',
'id',
'it',
'ja',
'ko',
'pt',
'ru',
'th',
'tr',
'vi',
]

/**
* @see: https://www.i18next.com/translation-function/essentials
* @see: https://react.i18next.com/latest/using-with-hooks
*/
i18n
// load translation using http ->
// see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// Configure localization.
.init({
// debug: process.env.NODE_ENV === "development",
// Use English strings by default, if the current language does not include
// the specified string.
fallbackLng: 'en',
// fallbackLng: 'dev', // Switch to this to force the fallback value on missing strings.

// List all translation namespaces.
ns: ['languages', 'ui'],
// Specify the default namespace.
defaultNS: 'ui',

// Only use the language code, skipping the region code.
// For example, en-US becomes simply en.
load: 'languageOnly',

returnNull: false,

backend: {
// Path to load localization data from.
loadPath: './assets/locales/{{lng}}/{{ns}}.json',
},
interpolation: {
escapeValue: false, //react does interlopation already
},
})

// https://www.i18next.com/translation-function/formatting#adding-custom-format-function
i18n.services.formatter?.add('percent', (value, _lng, options) => {
return (value * 100).toFixed(options.fixed)
})
i18n.services.formatter?.add('fixed', (value, _lng, options) => {
return value.toFixed(options.fixed)
})

export { i18n }
3 changes: 3 additions & 0 deletions libs/zzz/i18n/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import './i18n'
export * from './i18n'
export * from './Translate'
8 changes: 8 additions & 0 deletions libs/zzz/i18n/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"types": ["node"]
},
"include": ["**/*.ts", "**/*.tsx"]
}
Loading