Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add loading screen translations inline in web app (#2413)

Leendert de Borst98c132d8396d
diff --git a/apps/web/index.html b/apps/web/index.html
index ca6563951..a0f551463 100644
--- a/apps/web/index.html
+++ b/apps/web/index.html
@@ -24,10 +24,6 @@ https://github.com/aliasvault/aliasvault | AGPLv3
<link rel="prefetch" href="/wasm/aliasvault_core_bg.wasm" as="fetch" type="application/wasm" crossorigin="anonymous" />
<link rel="prefetch" href="/wasm/sql-wasm-browser.wasm" as="fetch" type="application/wasm" crossorigin="anonymous" />
<script>
- /*
- * Apply the saved theme before the first paint so the loading screen does not flash. Same rule and the same
- * localStorage key ('color-theme') as the Blazor client, so an existing preference carries over.
- */
(function () {
var theme = localStorage.getItem('color-theme');
if (theme === 'dark' || (!theme && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
@@ -81,26 +77,17 @@ https://github.com/aliasvault/aliasvault | AGPLv3
</div>
<div id="app"></div>
<script>
- var translations = {};
- function getCurrentLanguage() { return localStorage.getItem('AppLanguage') || 'en'; }
- async function fetchTranslations(lang) {
- var response = await fetch('/locales/' + lang + '.json');
- if (!response.ok) { throw new Error('No loading screen translations for ' + lang); }
- return response.json();
- }
- async function loadTranslations() {
- var lang = getCurrentLanguage();
+ var translations = (function () {
+ var all = {};
try {
- translations = await fetchTranslations(lang);
+ all = JSON.parse(document.getElementById('loading-screen-translations').textContent);
} catch (error) {
- try {
- translations = lang === 'en' ? {} : await fetchTranslations('en');
- } catch (fallbackError) {
- console.warn('Failed to load localization files, using fallback strings:', fallbackError);
- translations = {};
- }
+ console.warn('Failed to read the loading screen translations, using fallback strings:', error);
}
- }
+ var stored = localStorage.getItem('AppLanguage');
+ var browserLang = (navigator.language || '').split('-')[0];
+ return all[stored] || all[browserLang] || all.en || {};
+ })();
function getTranslation(path) {
var keys = path.split('.');
var value = translations;
@@ -167,7 +154,7 @@ https://github.com/aliasvault/aliasvault | AGPLv3
showError(getTranslation('errors.webAssemblyError'));
}
});
- loadTranslations().then(localizeContent);
+ localizeContent();
window.addEventListener('load', manageLoadingScreen);
</script>
<script type="module" src="/src/main.tsx"></script>
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index 673c21e54..796e482fd 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -1,4 +1,4 @@
-import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import react from '@vitejs/plugin-react';
@@ -10,41 +10,24 @@ const LOCALES_DIR = path.resolve(import.meta.dirname, 'src/i18n/locales');
const APP_VERSION = (JSON.parse(readFileSync(path.resolve(import.meta.dirname, 'package.json'), 'utf8')) as { version: string }).version;
/**
- * Serve the loadingScreen strings of every src/i18n/locales/<lang>.json as /locales/<lang>.json, which the loading
- * screen script in index.html fetches before the app bundle has loaded.
+ * Inline the loadingScreen strings of every src/i18n/locales/<lang>.json into index.html, so the loading screen
+ * script shows the right language on the first load without needing a separate request.
*/
function loadingScreenLocales(): Plugin {
- /**
- * The loading screen JSON of one language, or null when the language has no locale file.
- */
- const read = (lang: string): string | null => {
- const file = path.join(LOCALES_DIR, `${lang}.json`);
- if (!existsSync(file)) {
- return null;
- }
- const locale = JSON.parse(readFileSync(file, 'utf8')) as { loadingScreen?: unknown };
- return JSON.stringify(locale.loadingScreen ?? {});
- };
-
return {
name: 'loading-screen-locales',
- configureServer(server) {
- server.middlewares.use((req, res, next) => {
- const match = /^\/locales\/([a-z]{2})\.json(?:\?.*)?$/.exec(req.url ?? '');
- if (!match) {
- next();
- return;
- }
- const body = read(match[1]);
- res.statusCode = body ? 200 : 404;
- res.setHeader('Content-Type', 'application/json');
- res.end(body ?? '{}');
- });
- },
- generateBundle() {
+ transformIndexHtml() {
+ const translations: Record<string, unknown> = {};
for (const file of readdirSync(LOCALES_DIR).filter((name) => name.endsWith('.json'))) {
- this.emitFile({ type: 'asset', fileName: `locales/${file}`, source: read(path.basename(file, '.json')) ?? '{}' });
+ const locale = JSON.parse(readFileSync(path.join(LOCALES_DIR, file), 'utf8')) as { loadingScreen?: unknown };
+ if (locale.loadingScreen) {
+ translations[path.basename(file, '.json')] = locale.loadingScreen;
+ }
}
+
+ // Escape "<" so no string can close the script element.
+ const json = JSON.stringify(translations).replace(/</g, '\\u003c');
+ return [{ tag: 'script', attrs: { type: 'application/json', id: 'loading-screen-translations' }, children: json, injectTo: 'body-prepend' }];
},
};
}