Skip to content

feat(interface): add lang selector in settings page #525

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions i18n/english.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ const cli = {
}
};

const languages = {
fr: "french",
en: "english"
};

const ui = {
stats: {
title: "Global Stats",
Expand All @@ -105,9 +110,7 @@ const ui = {
dependencies: "scripts & dependencies",
warnings: "threats in source code",
vulnerabilities: "vulnerabilities (CVE)",
licenses: "licenses conformance (SPDX)",
dark: "dark",
light: "light"
licenses: "licenses conformance (SPDX)"
},
title: {
maintainers: "maintainers",
Expand Down Expand Up @@ -188,8 +191,12 @@ const ui = {
general: {
title: "General",
save: "save",
defaultPannel: "Default Package Menu",
themePannel: "Interface theme",
dark: "dark",
light: "light",
languages,
defaultPanel: "Default Package Menu",
themePanel: "Interface theme",
langPanel: "Interface language",
warnings: "SAST Warnings to ignore",
flags: "Flags (emojis) to ignore",
network: "Network",
Expand Down
17 changes: 12 additions & 5 deletions i18n/french.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ const cli = {
}
};

const languages = {
fr: "français",
en: "anglais"
};

const ui = {
stats: {
title: "Stats Globales",
Expand All @@ -105,9 +110,7 @@ const ui = {
dependencies: "scripts & dépendances",
warnings: "menaces dans le code",
vulnerabilities: "vulnérabilités",
licenses: "conformité des licences (SPDX)",
dark: "sombre",
light: "clair"
licenses: "conformité des licences (SPDX)"
},
title: {
maintainers: "mainteneurs",
Expand Down Expand Up @@ -188,8 +191,12 @@ const ui = {
general: {
title: "Général",
save: "sauvegarder",
defaultPannel: "Panneau par défaut",
themePannel: "Thème de l'interface",
dark: "sombre",
light: "clair",
languages,
defaultPanel: "Panneau par défaut",
themePanel: "Thème de l'interface",
langPanel: "Langue de l'interface",
warnings: "Avertissements à ignorer",
flags: "Drapeau (emojis) à ignorer",
network: "Réseau",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
"dependencies": {
"@nodesecure/documentation-ui": "^1.3.0",
"@nodesecure/flags": "^3.0.3",
"@nodesecure/i18n": "^4.0.1",
"@nodesecure/i18n": "^4.0.3",
"@nodesecure/js-x-ray": "^9.2.0",
"@nodesecure/licenses-conformance": "^2.1.0",
"@nodesecure/npm-registry-sdk": "^3.0.0",
Expand Down
15 changes: 12 additions & 3 deletions public/components/views/settings/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export class Settings {
/** @type {HTMLInputElement} */
showFriendlyDependenciesCheckbox: document.querySelector("#show-friendly"),
themeSelector: document.querySelector("#theme_selector"),
langSelector: document.querySelector("#lang_selector"),
disableExternalRequestsCheckbox: document.querySelector("#disable-external")
};

Expand All @@ -52,6 +53,7 @@ export class Settings {
...this.dom.flagsCheckbox,
this.dom.showFriendlyDependenciesCheckbox,
this.dom.themeSelector,
this.dom.langSelector,
this.dom.disableExternalRequestsCheckbox
];
for (const formField of formFields) {
Expand Down Expand Up @@ -203,7 +205,8 @@ export class Settings {
ignore: { flags: new Set(), warnings: new Set() },
showFriendlyDependencies: this.dom.showFriendlyDependenciesCheckbox.checked,
theme: this.dom.themeSelector.value,
disableExternalRequests: this.dom.disableExternalRequestsCheckbox.checked
disableExternalRequests: this.dom.disableExternalRequestsCheckbox.checked,
lang: this.dom.langSelector.value
};

for (const checkbox of this.dom.warningsCheckbox) {
Expand All @@ -228,15 +231,21 @@ export class Settings {
"content-type": "application/json"
}
});
this.config = newConfig;
this.config = { ...newConfig, lang: this.config.lang };
this.saveButton.classList.add("disabled");

window.dispatchEvent(new CustomEvent("settings-saved", { detail: this.config }));
window.dispatchEvent(new CustomEvent("settings-saved", {
detail: {
...this.config,
lang: newConfig.lang
}
}));
}

updateSettings() {
this.dom.defaultPackageMenu.value = this.config.defaultPackageMenu;
this.dom.themeSelector.value = this.config.theme;
this.dom.langSelector.value = this.config.lang;

const warnings = new Set(this.config.ignore.warnings);
const flags = new Set(this.config.ignore.flags);
Expand Down
14 changes: 14 additions & 0 deletions public/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ document.addEventListener("DOMContentLoaded", async() => {
window.navigation = new ViewNavigation();
window.wiki = new Wiki();

const languages = window.i18n.package_info.navigation.languages;
const langSelector = document.getElementById("lang_selector");
if (langSelector && languages) {
langSelector.innerHTML = Object.entries(languages)
.map(([key, label]) => `<option value="${key}">${label}</option>`)
.join("");
}

await init();
onSettingsSaved(window.settings.config);

Expand Down Expand Up @@ -211,15 +219,21 @@ async function updateShowInfoMenu(params) {
function onSettingsSaved(defaultConfig = null) {
async function updateSettings(config) {
console.log("[INFO] Settings saved:", config);
if (window.settings.config.lang !== config.lang) {
window.location.reload();
}

const warningsToIgnore = new Set(config.ignore.warnings);
const flagsToIgnore = new Set(config.ignore.flags);
const theme = config.theme;
const lang = config.lang;
secureDataSet.warningsToIgnore = warningsToIgnore;
secureDataSet.flagsToIgnore = flagsToIgnore;
secureDataSet.theme = theme;
window.settings.config.ignore.warnings = warningsToIgnore;
window.settings.config.ignore.flags = flagsToIgnore;
window.settings.config.theme = theme;
window.settings.config.lang = lang;
window.settings.config.disableExternalRequests = config.disableExternalRequests;

if (theme === "dark") {
Expand Down
15 changes: 15 additions & 0 deletions src/commands/lang.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Import Third-party Dependencies
import * as i18n from "@nodesecure/i18n";
import { appCache } from "@nodesecure/cache";
import { select } from "@topcli/prompts";
import kleur from "kleur";

Expand All @@ -15,6 +16,20 @@ export async function set() {
await i18n.setLocalLang(selectedLang);
await i18n.getLocalLang();

try {
const config = await appCache.getConfig();

if (config) {
await appCache.updateConfig({
...config,
lang: selectedLang
});
}
}
catch {
// Config does not exist, do nothing
}

console.log(
kleur.white().bold(`\n ${i18n.getTokenSync("cli.commands.lang.new_selection", kleur.yellow().bold(selectedLang))}`)
);
Expand Down
9 changes: 7 additions & 2 deletions views/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,13 @@ <h1><i class="icon-cog"></i>[[=z.token('settings.general.title')]]</h1>
</select>
<label for="theme_selector" class="mt-10">[[=z.token('settings.general.themePannel')]]:</label>
<select name="themeSelector" id="theme_selector">
<option value="dark">[[=z.token('package_info.navigation.dark')]]</option>
<option value="light">[[=z.token('package_info.navigation.light')]]</option>
<option value="dark">[[=z.token('settings.dark')]]</option>
<option value="light">[[=z.token('settings.light')]]</option>
Comment on lines +121 to +122
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<option value="dark">[[=z.token('settings.dark')]]</option>
<option value="light">[[=z.token('settings.light')]]</option>
<option value="dark">[[=z.token('settings.general.dark')]]</option>
<option value="light">[[=z.token('settings.general.light')]]</option>

</select>
<label for="lang_selector" class="mt-10">[[=z.token('settings.general.langPannel')]]:</label>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<label for="lang_selector" class="mt-10">[[=z.token('settings.general.langPannel')]]:</label>
<label for="lang_selector" class="mt-10">[[=z.token('settings.general.langPanel')]]:</label>

<select name="langSelector" id="lang_selector">
<option value="french">[[=z.token('settings.languages.fr')]]</option>
<option value="english">[[=z.token('settings.languages.en')]]</option>
Comment on lines +126 to +127
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
<option value="french">[[=z.token('settings.languages.fr')]]</option>
<option value="english">[[=z.token('settings.languages.en')]]</option>
<option value="french">[[=z.token('settings.general.languages.fr')]]</option>
<option value="english">[[=z.token('settings.general.languages.en')]]</option>

</select>
<p class="settings-line-title">[[=z.token('settings.general.network')]]:</p>
<div>
Expand Down
2 changes: 2 additions & 0 deletions workspaces/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import fs from "node:fs";

// Import Third-party Dependencies
import cacache from "cacache";
import * as i18n from "@nodesecure/i18n";

// Import Internal Dependencies
import { logger } from "@nodesecure/server";
Expand All @@ -30,6 +31,7 @@ export interface AppConfig {
};
theme?: "light" | "dark";
disableExternalRequests: boolean;
lang?: i18n.Languages;
}

export interface PayloadsList {
Expand Down
17 changes: 14 additions & 3 deletions workspaces/server/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Import Third-party Dependencies
import { warnings, type WarningName } from "@nodesecure/js-x-ray";
import { appCache, type AppConfig } from "@nodesecure/cache";
import * as i18n from "@nodesecure/i18n";

// Import Internal Dependencies
import { logger } from "./logger.js";
Expand All @@ -16,6 +17,7 @@ const kDefaultConfig = {
};

export async function get(): Promise<AppConfig> {
const localLang = await i18n.getLocalLang();
try {
const config = await appCache.getConfig();

Expand All @@ -26,7 +28,8 @@ export async function get(): Promise<AppConfig> {
warnings = []
} = {},
theme,
disableExternalRequests = false
disableExternalRequests = false,
lang = localLang
} = config;
logger.info(
// eslint-disable-next-line @stylistic/max-len
Expand All @@ -40,7 +43,8 @@ export async function get(): Promise<AppConfig> {
warnings
},
theme,
disableExternalRequests
disableExternalRequests,
lang
};
}
catch (err: any) {
Expand All @@ -50,7 +54,7 @@ export async function get(): Promise<AppConfig> {

logger.info(`[config|get](fallback to default: ${JSON.stringify(kDefaultConfig)})`);

return kDefaultConfig;
return { ...kDefaultConfig, lang: localLang };
}
}

Expand All @@ -66,4 +70,11 @@ export async function set(newValue: AppConfig) {

throw err;
}

const i18nLocalLang = await i18n.getLocalLang();
if (i18nLocalLang !== newValue.lang) {
logger.info(`[config|set](updating i18n lang to: ${newValue.lang})`);
await i18n.setLocalLang(newValue.lang!);
await i18n.getLanguages();
}
}
7 changes: 6 additions & 1 deletion workspaces/server/test/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import assert from "node:assert";
import cacache from "cacache";
import { warnings } from "@nodesecure/js-x-ray";
import { AppConfig, CACHE_PATH } from "@nodesecure/cache";
import * as i18n from "@nodesecure/i18n";

// Import Internal Dependencies
import { get, set } from "../src/config.js";
Expand All @@ -17,6 +18,7 @@ describe("config", () => {
let actualConfig: AppConfig;

before(async() => {
await i18n.getLanguages();
actualConfig = await get();
});

Expand All @@ -33,7 +35,8 @@ describe("config", () => {
ignore: { flags: [], warnings: Object.entries(warnings)
.filter(([_, { experimental }]) => experimental)
.map(([warning]) => warning) },
disableExternalRequests: false
disableExternalRequests: false,
lang: await i18n.getLocalLang()
});
});

Expand All @@ -44,6 +47,7 @@ describe("config", () => {
flags: ["foo"],
warnings: ["bar"]
},
lang: "english",
theme: "galaxy",
disableExternalRequests: true
};
Expand All @@ -60,6 +64,7 @@ describe("config", () => {
flags: ["foz"],
warnings: ["baz"]
},
lang: "english",
theme: "galactic",
disableExternalRequests: true
};
Expand Down
8 changes: 5 additions & 3 deletions workspaces/server/test/httpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ describe("httpServer", { concurrency: 1 }, () => {
const result = await get(kHttpURL);

assert.equal(result.statusCode, 200);
assert.equal(result.headers["content-type"], "text/html");
assert.ok(result.headers["content-type"]!.startsWith("text/html"));
});

test("'/' should fail", async(ctx) => {
Expand Down Expand Up @@ -233,6 +233,7 @@ describe("httpServer", { concurrency: 1 }, () => {
flags: ["foo"],
warnings: ["bar"]
},
lang: "english",
theme: "galaxy",
disableExternalRequests: true
};
Expand All @@ -250,19 +251,20 @@ describe("httpServer", { concurrency: 1 }, () => {
});

test("PUT '/config' should update the config", async() => {
const lang = await i18n.getLocalLang();
const { data: actualConfig } = await get(new URL("/config", kHttpURL));
// FIXME: use @mynusift/httpie instead of fetch. Atm it throws with put().
// https://github.com/nodejs/undici/issues/583
const { status } = await fetch(new URL("/config", kHttpURL), {
method: "PUT",
body: JSON.stringify({ fooz: "baz" }),
body: JSON.stringify({ fooz: "baz", lang }),
headers: { "Content-Type": "application/json" }
});

assert.equal(status, 204);

const inCache = await cacache.get(CACHE_PATH, kConfigKey);
assert.deepEqual(JSON.parse(inCache.data.toString()), { fooz: "baz" });
assert.deepEqual(JSON.parse(inCache.data.toString()), { fooz: "baz", lang });

await fetch(new URL("/config", kHttpURL), {
method: "PUT",
Expand Down
Loading