Add basic language support

This commit is contained in:
Aelita4 2023-11-11 23:28:14 +01:00
parent 210c457e72
commit eb5283882b
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
4 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,9 @@
{
"Header": {
"user": "user {}"
},
"Link": {
"logout": "Log out",
"build": "Build {}"
}
}

View File

@ -0,0 +1,8 @@
{
"Link": {
"home": "home",
"login": "login",
"register": "register",
"dropdown": "dropdown"
}
}

View File

@ -0,0 +1,7 @@
{
"Label": {
"coal": "Coal",
"iron": "Iron",
"gold": "Gold"
}
}

View File

@ -0,0 +1,50 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
export function getSupportedLanguages() {
const supportedLanguages = fs.readdirSync(path.dirname(fileURLToPath(import.meta.url))).filter((file: string) => {
return fs.statSync(path.join(path.dirname(fileURLToPath(import.meta.url)), file)).isDirectory();
});
return supportedLanguages;
}
export function getHighestWeightedLanguage(header: string | null): any {
if(header === null) return 'en';
const supportedLanguages = getSupportedLanguages();
const langs = header.split(',');
let highestWeight = 0;
let highestWeightedLang = 'en';
for(const lang of langs) {
const subArray = lang.split(";");
const langName = subArray[0];
const langWeight = subArray.filter((sub: string) => sub.includes("q=")).length > 0 ? parseFloat(subArray.filter((sub: string) => sub.includes("q="))[0].split("=")[1]) : 1;
if(langWeight > highestWeight && supportedLanguages.includes(langName)) {
highestWeight = langWeight;
highestWeightedLang = langName;
}
}
return highestWeightedLang;
}
export async function getLocales(language: string, type: string) {
if(!getSupportedLanguages().includes(language)) {
return null;
}
const lang = (await import(`./${language}/${type}.json`)).default;
const out: any = {};
for(const category in lang) {
for(const element in lang[category]) {
out[`${category}_${element}`] = lang[category][element];
}
}
return out;
}