diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 94113d4..f6ed507 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -124,7 +124,10 @@ if [[ "$MODE" == "frontend" || "$MODE" == "dual" || "$MODE" == "standalone" ]]; TITLE_ESCAPED=$(sed_escape "$TITLE_HTML_ESCAPED") sed -i "s/LibreSpeed<\\/title>/<title>$TITLE_ESCAPED<\\/title>/g; s/<h1>LibreSpeed<\\/h1>/<h1>$TITLE_ESCAPED<\\/h1>/g" /var/www/html/index-classic.html sed -i "s/<title>LibreSpeed<\\/title>/<title>$TITLE_ESCAPED<\\/title>/g" /var/www/html/index.html - sed -i "s/<title data-i18n=\"page.title\">LibreSpeed - Free and Open Source Speedtest<\\/title>/<title>$TITLE_ESCAPED - Free and Open Source Speedtest<\\/title>/g; s/<h1 data-i18n=\"brand.title\">Free and Open Source Speedtest\\.<\\/h1>/<h1>$TITLE_ESCAPED<\\/h1>/g" /var/www/html/index-modern.html + # The modern page keeps its translated title and heading unless TITLE is something other than the default + if [ "$TITLE_ONE_LINE" != "LibreSpeed" ]; then + sed -i "s/<title data-i18n=\"page.title\">LibreSpeed - Free and Open Source Speedtest<\\/title>/<title>$TITLE_ESCAPED - Free and Open Source Speedtest<\\/title>/g; s/<h1 data-i18n=\"brand.title\">Free and Open Source Speedtest\\.<\\/h1>/<h1>$TITLE_ESCAPED<\\/h1>/g" /var/www/html/index-modern.html + fi fi # Replace modern page tagline if TAGLINE is set @@ -133,7 +136,10 @@ if [[ "$MODE" == "frontend" || "$MODE" == "dual" || "$MODE" == "standalone" ]]; TAGLINE_ONE_LINE=${TAGLINE_ONE_LINE//$'\n'/ } TAGLINE_HTML_ESCAPED=$(html_escape "$TAGLINE_ONE_LINE") TAGLINE_ESCAPED=$(sed_escape "$TAGLINE_HTML_ESCAPED") - sed -i "s/<p class=\"tagline\" data-i18n=\"brand.tagline\">No Flash, No Java, No Websockets, No Bullsh\\*t<\\/p>/<p class=\"tagline\">$TAGLINE_ESCAPED<\\/p>/g" /var/www/html/index-modern.html + # The modern page keeps its translated tagline unless TAGLINE is something other than the default + if [ "$TAGLINE_ONE_LINE" != "No Flash, No Java, No Websockets, No Bullsh*t" ]; then + sed -i "s/<p class=\"tagline\" data-i18n=\"brand.tagline\">No Flash, No Java, No Websockets, No Bullsh\\*t<\\/p>/<p class=\"tagline\">$TAGLINE_ESCAPED<\\/p>/g" /var/www/html/index-modern.html + fi fi # Support legacy EMAIL env var as fallback for GDPR_EMAIL diff --git a/frontend/README.md b/frontend/README.md index 3233d80..06f13dd 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -30,7 +30,7 @@ browser. - Texts written by `javascript/index.js` go through `LibreSpeedI18n.t(key, fallback, { name: value })`. - To add a language, copy `locales/en.json` to `locales/<id>.json`, translate it and add `{ id, name }` to `LANGUAGES` in `javascript/i18n.js`. `tests/e2e/i18n.spec.js` checks that every catalog has the same keys as the English one. -- Setting `TITLE` or `TAGLINE` in the Docker image replaces the translated title, heading and tagline with that text. +- In the Docker image, a `TITLE` or `TAGLINE` other than the default replaces the translated title, heading and tagline with that text; the defaults keep them translated. ## Notes diff --git a/frontend/javascript/i18n.js b/frontend/javascript/i18n.js index ff9cf66..585a614 100644 --- a/frontend/javascript/i18n.js +++ b/frontend/javascript/i18n.js @@ -20,9 +20,15 @@ { id: "es", name: "Español" } ]; const STORAGE_KEY = "librespeed-language"; + // How long the page stays hidden while the first catalog loads; a late catalog is still applied + const PENDING_MS = 3000; const localesURL = new URL("../locales/", document.currentScript.src); let language = DEFAULT_LANGUAGE; let messages = {}; + // The latest change of language wins, whatever the order in which the catalogs arrive + let request = 0; + // The English text and attributes of the page, kept before the first translation as the fallback of missing keys + const originals = new WeakMap(); const supported = id => LANGUAGES.some(item => item.id === id); const normalize = value => @@ -47,29 +53,42 @@ ); } - function translateDocument() { - document.querySelectorAll("[data-i18n]").forEach(element => { - element.textContent = translate(element.dataset.i18n, element.textContent.trim()); - }); - document.querySelectorAll("[data-i18n-attr]").forEach(element => { - element.dataset.i18nAttr.split(",").forEach(binding => { - const [attribute, key] = binding.split(":"); - element.setAttribute(attribute, translate(key, element.getAttribute(attribute))); - }); - }); + function original(element, name, current) { + const saved = originals.get(element) || {}; + if (!(name in saved)) saved[name] = current; + originals.set(element, saved); + return saved[name]; + } + + function showLanguage() { document.querySelectorAll("[data-language-select]").forEach(select => { select.value = language; }); } + function translateDocument() { + document.querySelectorAll("[data-i18n]").forEach(element => { + element.textContent = translate(element.dataset.i18n, original(element, "", element.textContent.trim())); + }); + document.querySelectorAll("[data-i18n-attr]").forEach(element => { + element.dataset.i18nAttr.split(",").forEach(binding => { + const [attribute, key] = binding.split(":"); + element.setAttribute(attribute, translate(key, original(element, attribute, element.getAttribute(attribute)))); + }); + }); + showLanguage(); + } + function set(id, save) { if (!supported(id)) return Promise.resolve(); + const mine = ++request; return fetch(new URL(`${id}.json`, localesURL)) .then(response => { if (!response.ok) throw new Error(`Unable to load the ${id} translations`); return response.json(); }) .then(catalog => { + if (mine !== request) return; language = id; messages = catalog; if (save) { @@ -83,13 +102,20 @@ translateDocument(); window.dispatchEvent(new Event("i18nchange")); }) - .catch(error => console.warn("LibreSpeed localization unavailable:", error)) + .catch(error => { + console.warn("LibreSpeed localization unavailable:", error); + // The page stays in the language it shows, and so does the selector + if (mine === request) showLanguage(); + }) .finally(() => document.documentElement.removeAttribute("data-i18n-pending")); } const initial = initialLanguage(); // The page waits for a catalog other than English, so it does not flash in English first - if (initial !== DEFAULT_LANGUAGE) document.documentElement.setAttribute("data-i18n-pending", ""); + if (initial !== DEFAULT_LANGUAGE) { + document.documentElement.setAttribute("data-i18n-pending", ""); + setTimeout(() => document.documentElement.removeAttribute("data-i18n-pending"), PENDING_MS); + } document.addEventListener("DOMContentLoaded", () => { document.querySelectorAll("[data-language-select]").forEach(select => { diff --git a/tests/e2e/i18n.spec.js b/tests/e2e/i18n.spec.js index 7d17541..90213df 100644 --- a/tests/e2e/i18n.spec.js +++ b/tests/e2e/i18n.spec.js @@ -1,6 +1,7 @@ const fs = require("node:fs"); const path = require("node:path"); const { test, expect } = require("@playwright/test"); +const { baseUrls } = require("./helpers/env"); const staticRepositoryUrl = "http://127.0.0.1:18184"; const pageUrl = `${staticRepositoryUrl}/index-modern.html`; @@ -86,6 +87,56 @@ test.describe("Localization of the modern page", () => { }); }); + test.describe("English browser, catalogs that misbehave", () => { + test.use({ locale: "en-US" }); + + test("the latest choice wins when the catalogs arrive out of order", async ({ page }) => { + await page.route("**/frontend/locales/sv.json", async route => { + await new Promise(resolve => setTimeout(resolve, 1000)); + await route.continue(); + }); + await openPage(page); + const select = page.locator("[data-language-select]"); + const swedishArrived = page.waitForResponse("**/frontend/locales/sv.json"); + await select.selectOption("sv"); + await select.selectOption("pt"); + await expect(page.locator("main > h1")).toHaveText("Teste de velocidade livre e de código aberto."); + await swedishArrived; + await page.waitForTimeout(200); + await expect(page.locator("main > h1")).toHaveText("Teste de velocidade livre e de código aberto."); + await expect(select).toHaveValue("pt"); + expect(await page.evaluate(() => localStorage.getItem("librespeed-language"))).toBe("pt"); + }); + + test("the selector goes back to the language shown when a change fails", async ({ page }) => { + await openPage(page); + const select = page.locator("[data-language-select]"); + await select.selectOption("pt"); + await expect(page.locator("main > h1")).toHaveText("Teste de velocidade livre e de código aberto."); + + await page.route("**/frontend/locales/en.json", route => route.abort()); + await select.selectOption("en"); + await expect(select).toHaveValue("pt"); + await expect(page.locator("main > h1")).toHaveText("Teste de velocidade livre e de código aberto."); + }); + + test("a key missing from a catalog falls back to the English text, not to the previous language", async ({ + page + }) => { + await page.route("**/frontend/locales/sv.json", route => + route.fulfill({ json: { "brand.title": "Svensk rubrik" } }) + ); + await openPage(page); + const select = page.locator("[data-language-select]"); + await select.selectOption("pt"); + await expect(page.locator("main > p.tagline")).toContainText("Sem Flash"); + await select.selectOption("sv"); + await expect(page.locator("main > h1")).toHaveText("Svensk rubrik"); + await expect(page.locator("main > p.tagline")).toHaveText("No Flash, No Java, No Websockets, No Bullsh*t"); + await expect(page.locator("#start-button")).toHaveText("Let's start"); + }); + }); + test.describe("Swedish browser", () => { test.use({ locale: "sv-SE" }); @@ -98,6 +149,19 @@ test.describe("Localization of the modern page", () => { await expect(page.locator("[data-language-select]")).toHaveValue("sv"); }); + test("shows the page in English when the catalog stalls, and translates it when the catalog arrives", async ({ + page + }) => { + await page.route("**/frontend/locales/sv.json", async route => { + await new Promise(resolve => setTimeout(resolve, 4500)); + await route.continue(); + }); + await openPage(page); + await expect(page.locator("main > h1")).toBeVisible(); + await expect(page.locator("main > h1")).toHaveText("Free and Open Source Speedtest."); + await expect(page.locator("main > h1")).toHaveText("Gratis hastighetstest med öppen källkod."); + }); + test("translates the alert when no server can be reached", async ({ page }) => { const dialogs = []; page.on("dialog", dialog => { @@ -130,6 +194,17 @@ test.describe("Localization of the modern page", () => { }); }); + test.describe("Docker image with the default TITLE and TAGLINE", () => { + test.use({ locale: "pt-BR" }); + + test("translates the title, the heading and the tagline", async ({ page }) => { + await page.goto(`${baseUrls.standalone}/index-modern.html`); + await expect(page.locator("main > h1")).toHaveText("Teste de velocidade livre e de código aberto."); + await expect(page.locator("main > p.tagline")).toHaveText("Sem Flash, sem Java, sem Websockets, sem enrolação"); + await expect(page).toHaveTitle(/código aberto/); + }); + }); + test("every catalog has the keys of the English one, and the pages only use keys that exist", () => { const catalog = id => JSON.parse(fs.readFileSync(path.join(root, `frontend/locales/${id}.json`), "utf8")); const english = Object.keys(catalog("en"));