feat: started implementation of translations

This commit is contained in:
TrèsAbhi committed 2024-03-04 10:33:02 -06:00
1 parent 2ba9f0f4c8
commit ac60a436f1
6 files changed
+75 -118

No files matched your search

+18 -9
View File
@@ -1,6 +1,7 @@
const LANGUAGES = ['en-US', 'es-ES', 'ja-JP'] as const;
import { Locale } from 'discord.js';
const LOCALES: Locale[number][] = ['en-US', 'es-ES'];
export type Language = (typeof LANGUAGES)[number];
export type TranslationFragmentTree = {
[key: string]: TranslationFragment;
} & {
@@ -8,10 +9,18 @@ export type TranslationFragmentTree = {
};
export type TranslationFragment = string | TranslationFragmentTree;
export const translations = LANGUAGES.reduce(
(table, language) => ({
...table,
[language]: import(`../../lang/${language}.json`),
}),
{},
) as Record<Language, Promise<TranslationFragment>>;
export const translations = Promise.all(
LOCALES.map(async (locale) => ({
locale,
translations: await import(`../../lang/${locale}.json`),
})),
).then(
(translations) =>
translations.reduce(
(table, { locale, translations }) => ({
...table,
[locale]: translations,
}),
{},
) as Record<Locale[number], TranslationFragment>,
);
+17 -10
View File
@@ -1,13 +1,14 @@
import { Language, translations } from './strings';
import { Locale } from 'discord.js';
import { translations } from './strings';
export async function translator(language: Language) {
const strings = await translations[language];
export async function translator(locale: Locale) {
const strings = (await translations)[locale];
function translate(key: string) {
const path = key.split('.');
function translate(path: string) {
const pathArray = path.split('.');
let fragment = strings;
for (const pathItem in path) {
for (const pathItem of pathArray) {
if (typeof fragment === 'string') {
throw new SyntaxError(
`Attempted to access sub-string ("${pathItem}" in "${path}") from a string instead of a tree`,
@@ -17,7 +18,7 @@ export async function translator(language: Language) {
if (typeof fragment === 'undefined') {
throw new Error(
`Undefined translation for key "${key}" (in "${path}") in language "${language}"`,
`Undefined translation for key "${path}" (in "${path}") in language "${locale}"`,
);
}
}
@@ -29,13 +30,19 @@ export async function translator(language: Language) {
return fragment.$!;
} else {
throw new Error(
`Unresolved tree ending for path "${path}" in language "${language}"`,
`Unresolved tree ending for "${path}" in language "${locale}"`,
);
}
}
function t(strings: TemplateStringsArray) {
return translate(strings[0]);
function t(paths: TemplateStringsArray, ...embeds: string[]) {
return paths
.map((path, index) =>
path.length === 0
? ''
: `${translate(path)}${index === embeds.length ? '' : embeds[index]}`,
)
.join('');
}
return { translate, t };