Skip to content

perf(i18n): lazy load active locale translation bundle #375

Closed

Description

@khaira777

Refs: #372
Depends on: #382

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:
    1. Persisted store preference (usePosSettingsStore.getState().language if valid and supported)
    2. BCP-47 browser language match against selectable registered languages
    3. Fallback to 'en'
  • 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

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:translations

Manual testing:

  1. Launch app with English: verify network/chunk inspection loads English bundle only.
  2. Rapidly switch EN → ES → PT: verify only Portuguese applies without race conditions.
  3. Verify <html dir> and UI text transition atomically when switching to/from RTL.
  4. Disable external internet: verify app boots and switches languages entirely from local packaged assets.

Activity

  1. added
    enhancement
    area:frontend
    on Aug 17, 2026
  2. khaira777 commented on Aug 19, 2026

    @khaira777
    ContributorAuthor

    Status: implemented — pipeline running

    What was built

    1. Shared loader/cache — 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.
    2. Registry no longer bundles messages — languages.ts now only declares dynamic chunk loaders; the four message JSON files are no longer statically imported into the main graph.
    3. I18nProvider async + 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.
    4. Legacy 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.
    5. Atomic <html lang>/<html dir> — HtmlLangSync/KdsHtmlLang apply lang/dir only after the locale's messages have loaded (direction never flips ahead of messages), and now use getLanguageLocale() instead of hard-coded tags.
    6. Setup flow renders once its locale bundle is ready (browser-language first-run preserved).
    7. Build-output test — tests/locale-chunk-splitting.test.ts (wired into npm 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)

    • Before: every one of the 24 pages eagerly loaded all 4 locale chunks (en 95 KB + es 108 KB + pt 107 KB + fa 143 KB = 453 KB).
    • After: only packaged English (95 KB) is eager; es/pt/fa (~357 KB) are fetched only when their locale activates — a ~79% reduction in per-page startup translation payload.

    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 ✅
    • Manual evidence suites ✅ (issue-241-localized-errors all 4 languages, browser-receipts 37/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).

  3. khaira777 commented on Aug 19, 2026

    @khaira777
    ContributorAuthor

    ✅ Done — merged as 8df666a via PR #398

    All acceptance criteria met and verified:

    • Only the active locale bundle is loaded at startup — every one of the 24 static-export pages now eagerly loads only packaged English (95 KB); es/pt/fa chunks (~357 KB total) are fetched only when their locale activates (~79% reduction in per-page startup translation payload).
    • Shared loader/cache — frontend/src/lib/i18n/loader.ts caches loaded messages and deduplicates in-flight promises for React and non-React consumers.
    • Race protection — rapid language switches ignore stale loads (latest request wins); the shared in-flight map dedupes concurrent loads.
    • Atomic transition — messages, active locale, <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).
    • Failed switch reverts gracefully — keeps the current language rendered and reverts the store request with a logged warning.
    • Cold-boot English fallback — packaged English is primed synchronously, so the app always renders even if a locale chunk fails.
    • Static export chunks load offline — tests/locale-chunk-splitting.test.ts (wired into npm test) asserts es/pt/fa are independent lazy chunks not eagerly referenced by any page, with no external network references.
    • Before/after chunk sizes measured and documented — see comment above.

    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.

  4. self-assigned this
    on Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:frontendenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions