Modify language driver to accept array of multiple types

This commit is contained in:
Aelita4 2024-07-07 10:55:43 +02:00
parent 4f10a18d33
commit 5f305c8983
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
7 changed files with 61 additions and 63 deletions

View File

@ -19,88 +19,88 @@ interface NavElement {
dropdowns?: Array<NavElement>;
}
const lang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), 'navbar');
const lang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), ['navbar']);
const listOfElements: Array<NavElement> = [{
id: "home",
title: lang["Link_home"],
title: lang["navbar"]["Link_home"],
type: "simple",
url: "/",
show: "always",
position: "top"
}, {
id: "about",
title: lang["Link_about"],
title: lang["navbar"]["Link_about"],
type: "simple",
url: "#",
show: "always",
position: "top"
}, {
id: "api",
title: lang["Link_api"],
title: lang["navbar"]["Link_api"],
type: "simple",
url: "#",
show: "always",
position: "top"
}, {
id: "login",
title: lang["Link_login"],
title: lang["navbar"]["Link_login"],
type: "simple",
url: "/login",
show: "notLoggedInOnly",
position: "bottom"
}, {
id: "register",
title: lang["Link_register"],
title: lang["navbar"]["Link_register"],
type: "simple",
url: "/register",
show: "notLoggedInOnly",
position: "bottom"
},{
id: "overview",
title: lang["Link_overview"],
title: lang["navbar"]["Link_overview"],
type: "simple",
url: "/game",
show: "loggedInOnly",
position: "bottom"
}, {
id: "buildings",
title: lang["Link_buildings"],
title: lang["navbar"]["Link_buildings"],
type: "simple",
url: "/game/buildings",
show: "loggedInOnly",
position: "bottom"
}, {
id: "research",
title: lang["Link_research"],
title: lang["navbar"]["Link_research"],
type: "simple",
url: "/game/research",
show: "loggedInOnly",
position: "bottom"
}, {
id: "ships",
title: lang["Link_ships"],
title: lang["navbar"]["Link_ships"],
type: "simple",
url: "/game/ships",
show: "loggedInOnly",
position: "bottom"
}, {
id: "fleet",
title: lang["Link_fleet"],
title: lang["navbar"]["Link_fleet"],
type: "simple",
url: "/game/fleet",
show: "loggedInOnly",
position: "bottom"
}, {
id: "galaxyView",
title: lang["Link_galaxyView"],
title: lang["navbar"]["Link_galaxyView"],
type: "simple",
url: "/game/galaxyView",
show: "loggedInOnly",
position: "bottom"
}, {
id: "profile",
title: lang["Link_profile"],
title: lang["navbar"]["Link_profile"],
type: "simple",
url: "/game/profile",
show: "loggedInOnly",

View File

@ -5,8 +5,7 @@ import { getHighestWeightedLanguage, getLocales } from '../lib/utils/langDriver'
import resourceTypes from '../lib/data/resources.json';
const resourceLang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), 'resources');
const resBarLang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), 'resourcebar');
const lang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), ['resourcebar', 'resources']);
const resources = await calculateCurrentAvailableResources(new ObjectId(Astro.cookies.get('planetid')?.value ?? ''));
@ -31,13 +30,13 @@ for(const key in resources) {
<img src={resourceTypes.find(x => x.name === res.name)?.icon ?? "#"} alt={res.name} />
</div>
<div class="resourcebar-item-text-wrapper" data-resname={res.name}>
<div class="resourcebar-item-text">{resourceLang[`Label_${res.name}`]}</div>
<div class="resourcebar-item-text">{lang["resources"][`Label_${res.name}`]}</div>
<div class="resourcebar-item-amount">[fetching]</div>
</div>
<div class="resourcebar-item-tooltip">
<div class="resourcebar-item-tooltip-name">{resBarLang['Label_avaliable']} - <span class="resourcebar-item-tooltip-avaliable">{Math.floor(res.amount).toString()}</span></div>
<div class="resourcebar-item-tooltip-name">{resBarLang['Label_production']} - <span class="resourcebar-item-tooltip-production">{res.perHourMiningRate.toString()}</span></div>
<div class="resourcebar-item-tooltip-name">{resBarLang['Label_capacity']} - <span class="resourcebar-item-tooltip-capacity">{'21372137'}</span></div>
<div class="resourcebar-item-tooltip-name">{lang["resourcebar"]['Label_avaliable']} - <span class="resourcebar-item-tooltip-avaliable">{Math.floor(res.amount).toString()}</span></div>
<div class="resourcebar-item-tooltip-name">{lang["resourcebar"]['Label_production']} - <span class="resourcebar-item-tooltip-production">{res.perHourMiningRate.toString()}</span></div>
<div class="resourcebar-item-tooltip-name">{lang["resourcebar"]['Label_capacity']} - <span class="resourcebar-item-tooltip-capacity">{'21372137'}</span></div>
</div>
</div>
)}

View File

@ -32,18 +32,21 @@ export async function getHighestWeightedLanguage(header: string | null): Promise
return highestWeightedLang;
}
export async function getLocales(language: string, type: string) {
export async function getLocales(language: string, types: string[]) {
if(!(await getSupportedLanguages()).includes(language)) {
console.log(await getSupportedLanguages(), language)
return null;
}
const lang = await (await fetch(`http://localhost:4321/lang/${language}/${type}.json`)).json();
const out: any = {};
for(const type of types) {
const lang = await (await fetch(`http://localhost:4321/lang/${language}/${type}.json`)).json();
out[type] = {};
for(const category in lang) {
for(const element in lang[category]) {
out[`${category}_${element}`] = lang[category][element];
out[type][`${category}_${element}`] = lang[category][element];
}
}
}

View File

@ -16,10 +16,7 @@ if(checkUser === null || checkUser.username !== username) return Astro.redirect(
const locale = await getHighestWeightedLanguage(Astro.request.headers.get('accept-language'));
const langResources = await getLocales(locale, 'resources');
const langGame = await getLocales(locale, 'game');
const langBuildings = await getLocales(locale, 'buildings');
const langResearch = await getLocales(locale, 'research');
const lang = await getLocales(locale, ['resources', 'game', 'buildings', 'research']);
---
<Layout title="Buildings">
@ -28,19 +25,19 @@ const langResearch = await getLocales(locale, 'research');
{buildingsList.map(cat => (
<div class="building-card">
<h3>{langBuildings[`Label_${cat.category}`]}</h3>
<h3>{lang["buildings"][`Label_${cat.category}`]}</h3>
{cat.buildings.map(building => ( <>
<h4>{langBuildings[`Label_${building.id}`]}</h4>
<h4>{lang["buildings"][`Label_${building.id}`]}</h4>
{building.requirements.resources.map(res => (
<div>{langResources[`Label_${res.name}`]}: {res.amount}</div>
<div>{lang["resources"][`Label_${res.name}`]}: {res.amount}</div>
))}
{building.requirements.buildings.map(b => (
<div>{langBuildings[`Label_${b.id}`]}: {b.level}</div>
<div>{lang["buildings"][`Label_${b.id}`]}: {b.level}</div>
))}
{building.requirements.research.map(t => (
<div>{langResearch[`Label_${t.id}`].name}: {t.level}</div>
<div>{lang["research"][`Label_${t.id}`].name}: {t.level}</div>
))}
<a id={`build_${building.id}`} href="#" class="a-button">{langGame['Link_build']}</a>
<a id={`build_${building.id}`} href="#" class="a-button">{lang["game"]['Link_build']}</a>
</>))}
</div>
))}

View File

@ -17,7 +17,7 @@ const locale = await getHighestWeightedLanguage(Astro.request.headers.get('accep
const user = await getUserByNickOrEmail(username);
const langGame = await getLocales(locale, 'game');
const lang = await getLocales(locale, ['game']);
---
<Layout title="Profile">
@ -25,24 +25,24 @@ const langGame = await getLocales(locale, 'game');
<ResourceBar loggedIn="true" />
<div class="wrapper">
<h3>{format(langGame['Label_userCreationDate'], user?.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ").toString() ?? "")}</h3>
<a href="/logout" class="a-button">{langGame['Link_logout']}</a>
<h3>{format(lang["game"]['Label_userCreationDate'], user?.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ").toString() ?? "")}</h3>
<a href="/logout" class="a-button">{lang["game"]['Link_logout']}</a>
</div>
<form id="changeUsernameForm" class="data-form">
<input class="data-form-input" type="text" name="username" placeholder={langGame['Label_newUsernamePlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={langGame['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changeUsername']} />
<input class="data-form-input" type="text" name="username" placeholder={lang["game"]['Label_newUsernamePlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={lang["game"]['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={lang["game"]['Link_changeUsername']} />
</form>
<form id="changeEmailForm" class="data-form">
<input class="data-form-input" type="email" name="email" placeholder={langGame['Label_newEmailPlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={langGame['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changeEmail']} />
<input class="data-form-input" type="email" name="email" placeholder={lang["game"]['Label_newEmailPlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={lang["game"]['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={lang["game"]['Link_changeEmail']} />
</form>
<form id="changePasswordForm" class="data-form">
<input class="data-form-input" type="password" name="oldPassword" placeholder={langGame['Label_oldPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password1" placeholder={langGame['Label_newPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password2" placeholder={langGame['Label_newPasswordVerifyPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changePassword']} />
<input class="data-form-input" type="password" name="oldPassword" placeholder={lang["game"]['Label_oldPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password1" placeholder={lang["game"]['Label_newPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password2" placeholder={lang["game"]['Label_newPasswordVerifyPlaceholder']} />
<input class="data-form-button" type="button" value={lang["game"]['Link_changePassword']} />
</form>
</Layout>

View File

@ -20,10 +20,7 @@ if(checkUser === null || checkUser.username !== username) return Astro.redirect(
const locale = await getHighestWeightedLanguage(Astro.request.headers.get('accept-language'));
const langResources = await getLocales(locale, 'resources');
const langGame = await getLocales(locale, 'game');
const langBuildings = await getLocales(locale, 'buildings');
const langResearch = await getLocales(locale, 'research');
const lang = await getLocales(locale, ['game', 'resources', 'buildings', 'research']);
const researchDetails: ResearchDetail[] = []; //TODO: Add union type for cost keys
researchList.forEach(element => {
@ -48,21 +45,21 @@ researchList.forEach(element => {
{researchDetails.map(research => (
<div class="research-card">
<h2>{langResearch[`Label_${research.id}`].name}</h2>
<h2>{lang["research"][`Label_${research.id}`].name}</h2>
<div class="research-card-wrapper">
<div class="research-image"></div>
{langResearch[`Label_${research.id}`].description}<br />
{lang["research"][`Label_${research.id}`].description}<br />
<a id={`research_${research.id}`} href="#" class="a-button">{langGame['Link_research']}</a>
<a id={`research_${research.id}`} href="#" class="a-button">{lang["game"]['Link_research']}</a>
<div class="research-req-icon">
<Icon class="research-req-icon-proper" name="mdi:help" />
<div class="research-req-tooltip">
<div>{langResearch['Label_required']}:</div>
<div>{lang["research"]['Label_required']}:</div>
{research.requiredResearch.length !== 0 ? research.requiredResearch.map(req => (
<div>
{langResearch[`Label_${req.id}`].name} - {req.level}
{lang["research"][`Label_${req.id}`].name} - {req.level}
</div>
)) : langResearch['Label_none']}
)) : lang["research"]['Label_none']}
</div>
</div>
</div>
@ -71,7 +68,7 @@ researchList.forEach(element => {
</div>
<div class="research-cost-wrapper">
{Object.entries(research.cost).map(([key, value]) => <div>
{langResources[`Label_${key}`]}: {value} ||
{lang["resources"][`Label_${key}`]}: {value} ||
</div>)}
</div>
</div>

View File

@ -6,6 +6,8 @@ import { getHighestWeightedLanguage, getLocales } from '../../lib/utils/langDriv
import ResourceBar from '../../components/ResourceBar.astro';
import ships from '../../lib/data/ships.json';
import { getPlanetById } from '../../lib/db/planets';
import { ObjectId } from 'mongodb';
const loggedToken = Astro.cookies.get('sessionToken')?.value ?? null;
const username = Astro.cookies.get('username')?.value ?? "";
@ -14,11 +16,11 @@ if(loggedToken === null || username === "") return Astro.redirect('/logout');
const checkUser = await getUserByAccessToken(loggedToken);
if(checkUser === null || checkUser.username !== username) return Astro.redirect('/logout');
const locale = await getHighestWeightedLanguage(Astro.request.headers.get('accept-language'));
const langShips = await getLocales(locale, 'ships');
const planet = await getPlanetById(new ObjectId(Astro.cookies.get('planetid')?.value));
const playerShips = checkUser.ships;
console.log(playerShips)
if(!planet) return;
const lang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), ['ships']);
---
<Layout title="Ships">
@ -28,7 +30,7 @@ console.log(playerShips)
{ships.map(ship => (
<div class="ship-card">
<div class="ship-title">
<b>({playerShips.find((s => s.id === ship.id))?.amount ?? 0})</b> <i>{ship.id}</i>
<b>({planet.ships.find((s => s.id === ship.id))?.amount ?? 0})</b> <i>{ship.id}</i>
</div>
</div>
))}