mirror of
https://github.com/blitzkit/blitzkit.git
synced 2026-10-23 11:39:50 +02:00
feat: translate funcs
This commit is contained in:
1 parent
fa9b6c6d97
commit
cba93b3d55
3 files changed
+59
-32
No files matched your search
@@ -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>>;
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user