feat: translate funcs

This commit is contained in:
TrèsAbhi committed 2024-03-03 22:13:22 -06:00
1 parent fa9b6c6d97
commit cba93b3d55
3 files changed
+59 -32

No files matched your search

-32
View File
@@ -1,32 +0,0 @@
name: CI Version
on: push
jobs:
host:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Use node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'npm'
- name: Install Yarn
run: npm install --location=global yarn
- name: Use node_modules cache
uses: actions/cache@v3
with:
path: '**/node_modules'
key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }}
- name: Install dependencies
run: yarn
- name: Generate leaderboard
run: yarn lint:version
+17
View File
@@ -0,0 +1,17 @@
const LANGUAGES = ['en-US', 'es-ES', 'ja-JP'] as const;
export type Language = (typeof LANGUAGES)[number];
export type TranslationFragmentTree = {
[key: string]: TranslationFragment;
} & {
$?: string;
};
export type TranslationFragment = string | TranslationFragmentTree;
export const translations = LANGUAGES.reduce(
(table, language) => ({
...table,
[language]: import(`../../lang/${language}.json`),
}),
{},
) as Record<Language, Promise<TranslationFragment>>;
+42
View File
@@ -0,0 +1,42 @@
import { Language, translations } from './strings';
export async function translator(language: Language) {
const strings = await translations[language];
function translate(key: string) {
const path = key.split('.');
let fragment = strings;
for (const pathItem in path) {
if (typeof fragment === 'string') {
throw new SyntaxError(
`Attempted to access sub-string ("${pathItem}" in "${path}") from a string instead of a tree`,
);
} else {
fragment = fragment[pathItem];
if (typeof fragment === 'undefined') {
throw new Error(
`Undefined translation for key "${key}" (in "${path}") in language "${language}"`,
);
}
}
}
if (typeof fragment === 'string') {
return fragment;
} else if (fragment.$) {
return fragment.$!;
} else {
throw new Error(
`Unresolved tree ending for path "${path}" in language "${language}"`,
);
}
}
function t(strings: TemplateStringsArray) {
return translate(strings[0]);
}
return { translate, t };
}