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>; 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> = [{ const listOfElements: Array<NavElement> = [{
id: "home", id: "home",
title: lang["Link_home"], title: lang["navbar"]["Link_home"],
type: "simple", type: "simple",
url: "/", url: "/",
show: "always", show: "always",
position: "top" position: "top"
}, { }, {
id: "about", id: "about",
title: lang["Link_about"], title: lang["navbar"]["Link_about"],
type: "simple", type: "simple",
url: "#", url: "#",
show: "always", show: "always",
position: "top" position: "top"
}, { }, {
id: "api", id: "api",
title: lang["Link_api"], title: lang["navbar"]["Link_api"],
type: "simple", type: "simple",
url: "#", url: "#",
show: "always", show: "always",
position: "top" position: "top"
}, { }, {
id: "login", id: "login",
title: lang["Link_login"], title: lang["navbar"]["Link_login"],
type: "simple", type: "simple",
url: "/login", url: "/login",
show: "notLoggedInOnly", show: "notLoggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "register", id: "register",
title: lang["Link_register"], title: lang["navbar"]["Link_register"],
type: "simple", type: "simple",
url: "/register", url: "/register",
show: "notLoggedInOnly", show: "notLoggedInOnly",
position: "bottom" position: "bottom"
},{ },{
id: "overview", id: "overview",
title: lang["Link_overview"], title: lang["navbar"]["Link_overview"],
type: "simple", type: "simple",
url: "/game", url: "/game",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "buildings", id: "buildings",
title: lang["Link_buildings"], title: lang["navbar"]["Link_buildings"],
type: "simple", type: "simple",
url: "/game/buildings", url: "/game/buildings",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "research", id: "research",
title: lang["Link_research"], title: lang["navbar"]["Link_research"],
type: "simple", type: "simple",
url: "/game/research", url: "/game/research",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "ships", id: "ships",
title: lang["Link_ships"], title: lang["navbar"]["Link_ships"],
type: "simple", type: "simple",
url: "/game/ships", url: "/game/ships",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "fleet", id: "fleet",
title: lang["Link_fleet"], title: lang["navbar"]["Link_fleet"],
type: "simple", type: "simple",
url: "/game/fleet", url: "/game/fleet",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "galaxyView", id: "galaxyView",
title: lang["Link_galaxyView"], title: lang["navbar"]["Link_galaxyView"],
type: "simple", type: "simple",
url: "/game/galaxyView", url: "/game/galaxyView",
show: "loggedInOnly", show: "loggedInOnly",
position: "bottom" position: "bottom"
}, { }, {
id: "profile", id: "profile",
title: lang["Link_profile"], title: lang["navbar"]["Link_profile"],
type: "simple", type: "simple",
url: "/game/profile", url: "/game/profile",
show: "loggedInOnly", show: "loggedInOnly",

View File

@ -5,8 +5,7 @@ import { getHighestWeightedLanguage, getLocales } from '../lib/utils/langDriver'
import resourceTypes from '../lib/data/resources.json'; import resourceTypes from '../lib/data/resources.json';
const resourceLang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), 'resources'); const lang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), ['resourcebar', 'resources']);
const resBarLang = await getLocales(await getHighestWeightedLanguage(Astro.request.headers.get('accept-language')), 'resourcebar');
const resources = await calculateCurrentAvailableResources(new ObjectId(Astro.cookies.get('planetid')?.value ?? '')); 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} /> <img src={resourceTypes.find(x => x.name === res.name)?.icon ?? "#"} alt={res.name} />
</div> </div>
<div class="resourcebar-item-text-wrapper" data-resname={res.name}> <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 class="resourcebar-item-amount">[fetching]</div>
</div> </div>
<div class="resourcebar-item-tooltip"> <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">{lang["resourcebar"]['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">{lang["resourcebar"]['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_capacity']} - <span class="resourcebar-item-tooltip-capacity">{'21372137'}</span></div>
</div> </div>
</div> </div>
)} )}

View File

@ -32,18 +32,21 @@ export async function getHighestWeightedLanguage(header: string | null): Promise
return highestWeightedLang; return highestWeightedLang;
} }
export async function getLocales(language: string, type: string) { export async function getLocales(language: string, types: string[]) {
if(!(await getSupportedLanguages()).includes(language)) { if(!(await getSupportedLanguages()).includes(language)) {
console.log(await getSupportedLanguages(), language) console.log(await getSupportedLanguages(), language)
return null; return null;
} }
const lang = await (await fetch(`http://localhost:4321/lang/${language}/${type}.json`)).json();
const out: any = {}; 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 category in lang) {
for(const element in lang[category]) { 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 locale = await getHighestWeightedLanguage(Astro.request.headers.get('accept-language'));
const langResources = await getLocales(locale, 'resources'); const lang = await getLocales(locale, ['resources', 'game', 'buildings', 'research']);
const langGame = await getLocales(locale, 'game');
const langBuildings = await getLocales(locale, 'buildings');
const langResearch = await getLocales(locale, 'research');
--- ---
<Layout title="Buildings"> <Layout title="Buildings">
@ -28,19 +25,19 @@ const langResearch = await getLocales(locale, 'research');
{buildingsList.map(cat => ( {buildingsList.map(cat => (
<div class="building-card"> <div class="building-card">
<h3>{langBuildings[`Label_${cat.category}`]}</h3> <h3>{lang["buildings"][`Label_${cat.category}`]}</h3>
{cat.buildings.map(building => ( <> {cat.buildings.map(building => ( <>
<h4>{langBuildings[`Label_${building.id}`]}</h4> <h4>{lang["buildings"][`Label_${building.id}`]}</h4>
{building.requirements.resources.map(res => ( {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 => ( {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 => ( {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> </div>
))} ))}

View File

@ -17,7 +17,7 @@ const locale = await getHighestWeightedLanguage(Astro.request.headers.get('accep
const user = await getUserByNickOrEmail(username); const user = await getUserByNickOrEmail(username);
const langGame = await getLocales(locale, 'game'); const lang = await getLocales(locale, ['game']);
--- ---
<Layout title="Profile"> <Layout title="Profile">
@ -25,24 +25,24 @@ const langGame = await getLocales(locale, 'game');
<ResourceBar loggedIn="true" /> <ResourceBar loggedIn="true" />
<div class="wrapper"> <div class="wrapper">
<h3>{format(langGame['Label_userCreationDate'], user?.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ").toString() ?? "")}</h3> <h3>{format(lang["game"]['Label_userCreationDate'], user?.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ").toString() ?? "")}</h3>
<a href="/logout" class="a-button">{langGame['Link_logout']}</a> <a href="/logout" class="a-button">{lang["game"]['Link_logout']}</a>
</div> </div>
<form id="changeUsernameForm" class="data-form"> <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="text" name="username" placeholder={lang["game"]['Label_newUsernamePlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={langGame['Label_passwordPlaceholder']} /> <input class="data-form-input" type="password" name="password" placeholder={lang["game"]['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changeUsername']} /> <input class="data-form-button" type="button" value={lang["game"]['Link_changeUsername']} />
</form> </form>
<form id="changeEmailForm" class="data-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="email" name="email" placeholder={lang["game"]['Label_newEmailPlaceholder']} />
<input class="data-form-input" type="password" name="password" placeholder={langGame['Label_passwordPlaceholder']} /> <input class="data-form-input" type="password" name="password" placeholder={lang["game"]['Label_passwordPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changeEmail']} /> <input class="data-form-button" type="button" value={lang["game"]['Link_changeEmail']} />
</form> </form>
<form id="changePasswordForm" class="data-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="oldPassword" placeholder={lang["game"]['Label_oldPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password1" placeholder={langGame['Label_newPasswordPlaceholder']} /> <input class="data-form-input" type="password" name="password1" placeholder={lang["game"]['Label_newPasswordPlaceholder']} />
<input class="data-form-input" type="password" name="password2" placeholder={langGame['Label_newPasswordVerifyPlaceholder']} /> <input class="data-form-input" type="password" name="password2" placeholder={lang["game"]['Label_newPasswordVerifyPlaceholder']} />
<input class="data-form-button" type="button" value={langGame['Link_changePassword']} /> <input class="data-form-button" type="button" value={lang["game"]['Link_changePassword']} />
</form> </form>
</Layout> </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 locale = await getHighestWeightedLanguage(Astro.request.headers.get('accept-language'));
const langResources = await getLocales(locale, 'resources'); const lang = await getLocales(locale, ['game', 'resources', 'buildings', 'research']);
const langGame = await getLocales(locale, 'game');
const langBuildings = await getLocales(locale, 'buildings');
const langResearch = await getLocales(locale, 'research');
const researchDetails: ResearchDetail[] = []; //TODO: Add union type for cost keys const researchDetails: ResearchDetail[] = []; //TODO: Add union type for cost keys
researchList.forEach(element => { researchList.forEach(element => {
@ -48,21 +45,21 @@ researchList.forEach(element => {
{researchDetails.map(research => ( {researchDetails.map(research => (
<div class="research-card"> <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-card-wrapper">
<div class="research-image"></div> <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"> <div class="research-req-icon">
<Icon class="research-req-icon-proper" name="mdi:help" /> <Icon class="research-req-icon-proper" name="mdi:help" />
<div class="research-req-tooltip"> <div class="research-req-tooltip">
<div>{langResearch['Label_required']}:</div> <div>{lang["research"]['Label_required']}:</div>
{research.requiredResearch.length !== 0 ? research.requiredResearch.map(req => ( {research.requiredResearch.length !== 0 ? research.requiredResearch.map(req => (
<div> <div>
{langResearch[`Label_${req.id}`].name} - {req.level} {lang["research"][`Label_${req.id}`].name} - {req.level}
</div> </div>
)) : langResearch['Label_none']} )) : lang["research"]['Label_none']}
</div> </div>
</div> </div>
</div> </div>
@ -71,7 +68,7 @@ researchList.forEach(element => {
</div> </div>
<div class="research-cost-wrapper"> <div class="research-cost-wrapper">
{Object.entries(research.cost).map(([key, value]) => <div> {Object.entries(research.cost).map(([key, value]) => <div>
{langResources[`Label_${key}`]}: {value} || {lang["resources"][`Label_${key}`]}: {value} ||
</div>)} </div>)}
</div> </div>
</div> </div>

View File

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