Repository navigation
Description
Context
Currently, all 4 translation JSON files (2,053 keys each, over 500 KB total uncompressed source) are bundled into every application page because frontend/src/lib/i18n/languages.ts statically imports them.
This issue implements asynchronous, code-split lazy loading with shared caching and atomic UI/direction transitions so that only the active locale bundle is loaded at startup, and language switching is smooth, resilient, and race-free.
What to do
1. Shared Locale Message Loader & Cache
Create frontend/src/lib/i18n/loader.ts (or integrate in languages.ts) providing a shared loader for both React and non-React consumers:
import { LANGUAGES, type Language } from './languages';
type Messages = Record<string, unknown>;
const messageCache = new Map<Language, Messages>();
const inFlightPromises = new Map<Language, Promise<Messages>>();
export async function loadLocaleMessages(lang: Language): Promise<Messages> {
const cached = messageCache.get(lang);
if (cached) return cached;
const inFlight = inFlightPromises.get(lang);
if (inFlight) return inFlight;
const config = LANGUAGES[lang] ?? LANGUAGES.en;
const promise = (config.load ? config.load() : import('./messages/en.json'))
.then((mod) => {
const messages = (mod.default ?? mod) as Messages;
messageCache.set(lang, messages);
inFlightPromises.delete(lang);
return messages;
})
.catch((err) => {
inFlightPromises.delete(lang);
throw err;
});
inFlightPromises.set(lang, promise);
return promise;
}2. Async Loading, Race Protection & Atomic Transition in I18nProvider
Update frontend/src/components/providers/I18nProvider.tsx:
- Deterministic initial-language precedence:
- Persisted store preference (
usePosSettingsStore.getState().languageif valid and supported) - BCP-47 browser language match against selectable registered languages
- Fallback to
'en'
- Persisted store preference (
- Packaged English startup fallback: If the requested locale fails to load during cold boot, fall back to packaged English so the application always renders.
- Stale load / Race protection: Use a generation counter or cancellation flag so rapid language switching (e.g. EN → ES → PT) ignores stale resolved promises and applies only the latest requested language.
- Failed-switch behavior: If loading a newly selected language fails:
- Keep the currently rendered language and messages active (no unmounting, blank screen, or key flashing).
- Revert the requested language in the store.
- Display a non-disruptive error toast / log a warning.
- Atomic UI & Direction Transition: Keep the current UI rendered while the new locale bundle loads. When the new bundle is ready, update active messages, active locale,
<html lang>, and<html dir>atomically in the same React commit.
3. Static Export Packaging & Offline-First Invariant
Ensure Next.js static export emits each locale's message bundle as an independent static chunk packaged with the Electron desktop application.
- Zero external translation network calls/dependencies: Chunks are served locally by FloCafe's embedded localhost server.
- The application must operate with full fidelity when external network access is disabled.
4. Measurable Bundle Verification & Offline Test
Inspect build output before and after to verify that locale chunks are code-split. Add an explicit test verifying that packaged builds load locale chunks locally without external network access.
What NOT to do
- Do NOT migrate components from
useI18ntouseTranslations(reserved for refactor(i18n): component migration 5A — shared, layout, auth, setup #376–refactor(i18n): component migration 5E — settings, admin, remaining #380). - Do NOT remove the compatibility adapter (reserved for refactor(i18n): remove legacy custom i18n implementation #381).
- Do NOT introduce full-page blanking or jarring loading skeletons on language switch.
- Do NOT allow document direction (
<html dir>) to flip before messages have loaded. - Do NOT make runtime external network calls for translations.
- Do NOT guess bundle savings; measure and record actual chunk outputs in the PR description.
Acceptance Criteria
- Only the active locale bundle is loaded during initial application startup.
- Shared loader (
loader.ts) caches loaded messages and deduplicates in-flight promises for React and non-React consumers. - Race conditions from rapid language switches are prevented via stale-load protection.
- Language switching transitions atomically: messages, active locale,
<html lang>, and<html dir>update in sync without key flash or UI flicker. - Failed language switch reverts gracefully without crashing or unmounting the application.
- Cold boot falls back to packaged English if the active locale chunk fails to load.
- Static export chunks load offline with external network access disabled.
- Actual before-and-after chunk sizes measured and documented.
Verification
npm run build:frontend # inspect emitted chunk assets
npm run lint
npm test
npm run test:translationsManual testing:
- Launch app with English: verify network/chunk inspection loads English bundle only.
- Rapidly switch EN → ES → PT: verify only Portuguese applies without race conditions.
- Verify
<html dir>and UI text transition atomically when switching to/from RTL. - Disable external internet: verify app boots and switches languages entirely from local packaged assets.
Activity
khaira777 commentedon Aug 19, 2026
Status: implemented — pipeline running
What was built
frontend/src/lib/i18n/loader.ts:loadLocaleMessages(lang)with a message cache (English primed synchronously as the packaged cold-boot fallback) and in-flight promise deduplication, shared by React and non-React consumers.languages.tsnow only declares dynamic chunk loaders; the four message JSON files are no longer statically imported into the main graph.I18nProviderasync + atomic — deterministic initial-language resolution (persisted store preference → browser match against selectable languages → English); stale-load protection so rapid EN→ES→PT applies only the latest request; failed switches keep the current language rendered and revert the store request; messages swap atomically with the active locale.t()bridge reads the shared cache — fallback chain (target → English → raw key) unchanged; English renders until the active chunk arrives, so no raw-key flashing is possible.<html lang>/<html dir>—HtmlLangSync/KdsHtmlLangapply lang/dir only after the locale's messages have loaded (direction never flips ahead of messages), and now usegetLanguageLocale()instead of hard-coded tags.tests/locale-chunk-splitting.test.ts(wired intonpm test): es/pt/fa must ship as independent lazy chunks, not eagerly referenced by any page, with no external network references (offline invariant).Measured bundle impact (before → after, static export)
Verification (all green locally)
npm test✅ full suite (incl.test:translations,test:locale-chunks, all RTL suites)npm run lint✅ 0 errors ·npm run build✅ ·npm run build:frontend✅issue-241-localized-errorsall 4 languages,browser-receipts37/37)Also removed the orphaned
tests/issue-374-nested-messages-verification.test.ts(no-mistakes evidence file merged with #396, not wired into any script).perf(i18n): lazy load active locale bundle with shared cache & atomic…
khaira777 commentedon Aug 19, 2026
✅ Done — merged as
8df666avia PR #398All acceptance criteria met and verified:
frontend/src/lib/i18n/loader.tscaches loaded messages and deduplicates in-flight promises for React and non-React consumers.<html lang>, and<html dir>update together; lang/dir are applied only after the locale's messages have loaded, so direction never flips ahead of messages (no key flash or layout jump).tests/locale-chunk-splitting.test.ts(wired intonpm test) asserts es/pt/fa are independent lazy chunks not eagerly referenced by any page, with no external network references.Verification: full
npm test✅ · lint 0 errors ✅ ·build+build:frontend✅ · all 12 CI checks on PR #398 ✅ (incl. e2e-playwright, linux-tests shards, windows-uninstaller).Also removed the orphaned
tests/issue-374-nested-messages-verification.test.ts(no-mistakes evidence file merged with #396, not wired into any script) in the same PR.Closing.