Skip to content

feat(i18n): source translations and the language set from SahajCloud #198

Description

@Ardnived

Blocked by sydevs/SahajCloud#705 and sydevs/SahajCloud#706. Do not start until both are merged to main and production is seeded and published — pnpm types:cms reads from main, so running it earlier silently pulls the old shape.

Closes #28 and #167. Supersedes PR #168 (its measured boot order, preferredLanguage, the one-writer finding and the sync-script production-key rule are reused; its shipped ∩ enabled split is moot once nothing is shipped). Part of sydevs/SahajCloud#702.

Summary

  • Every UI string comes from sy-atlas-translations, one i18next namespace with nested keys (event.display.chip_full), fetched per locale in parallel with clients/me. public/locales/**, i18next-http-backend, pnpm i18n:add and the /locales/* CORS rule go.
  • A committed English snapshot (src/config/translations.en.json, written by pnpm sync:translations, never hand-edited) initialises i18next synchronously, types every t() key, feeds tests and Ladle, and is the last-resort fallback. The CMS still refreshes en at runtime, so an English edit ships without a deploy.
  • The languages the widget offers are sy-atlas-config.availableLocales — an operator's set, each locale published in the CMS. The picker lists exactly that set; a locale naming anything else is corrected to English.
  • Hosts observe one change: connect-src https://sahajatlas.com is no longer needed (nothing connects to it — script-src/font-src still do), and cloud.sydevelopers.com, already required, now also serves the strings.

Background

src/config/i18n.ts loads ${VITE_HOST}/locales/<lng>/<ns>.json over HTTP; supportedLanguages in i18n-options.ts is pinned to the directory listing; nine files read public/locales from disk; ERROR_POLICY carries English fallbackText because a bundle may never arrive. #28 asked for the CMS to own the strings, #167 for it to own the set, and PR #168 built the set half against the old languages field. SahajCloud has since (child 1 + child 2) rewritten the global by widget view, seeded ten locales, added per-locale publish status, availableLocales with a "published or refuse" validator, and a client-read English merge — so a non-English read is already complete and fallbackLng only matters when the read fails. The key contract is sydevs/SahajCloud#706 Appendix A; this issue renames every call site through it.

Proposed changes

1. Two reads, warmed with clients/me

src/config/api/fetch.ts + index.ts:

  • atlasConfigQuery() — ['atlas-config'], sdk.findGlobal({ slug: 'sy-atlas-config', depth: 0, select: { availableLocales: true } }), zod AtlasConfigSchema (availableLocales: string[] | nullish), staleTime: ATLAS_CONFIG_STALE_TIME (= REGIONS_STALE_TIME), gcTime: WHOLESALE_GC_TIME, retryOnMount: false. Locale-agnostic; the interceptor's ?locale= is harmless.
  • translationsQuery(locale) — ['translations', locale], sdk.findGlobal({ slug: 'sy-atlas-translations', locale, depth: 0, select: <every widget tab; never emails or event.title> }), parsed through a light TranslationBundleSchema, same windows.
  • applyRequestContext (src/config/api/client.ts line 34) sets locale only when absent, so the SDK's explicit ?locale= for the translations read wins; every other request keeps the resolved language. fetch.test.ts gains the pin.
  • api.warmConfig() and api.warmTranslations(i18n.language) fire from App's mount effect (ungated by compact — the card is localized) and from PathBoot in Widget.tsx, which reads clients/me above App (feat(i18n): take the language set from SahajCloud, not from supportedLanguages #168 measured: warmed in parallel the config settled 1 ms after clients/me; serialized, the language flipped in front of the viewer). Both pass the factory verbatim to prefetchQuery.

2. i18next: snapshot at init, CMS bundles on demand, one writer

  • src/config/i18n.ts: no backend; resources: { en: { translation: snapshot } }; initImmediate: false (init is synchronous, so nothing suspends on i18n any more — remove the useSuspense: false options and the "cold boot can suspend" comments in Widget.tsx, views/shared.tsx, views/fallbacks.tsx); react: { bindI18nStore: 'added' }; detector unchanged (querystring → hostHtmlLang → navigator, caches: [], cimode guard).
  • src/config/i18n-options.ts: defaultNS: 'translation', ns: ['translation'], %{} interpolation kept, supportedLngs and supportedLanguages removed. Plurals: event.display.sessions_count with count resolves _one/_few/_many/_other natively.
  • New src/config/language.ts — applyLanguage(requested): preferred = preferredLanguage(requested, availableLocales) (feat(i18n): take the language set from SahajCloud, not from supportedLanguages #168's helper: case-fold → base tag → regional variant → en); if the bundle is cached, addResourceBundle(preferred, 'translation', bundle, true, true) + changeLanguage(preferred) synchronously; else ensureQueryData(translationsQuery(preferred)) then the same; on failure changeLanguage('en') + reportInternalError. Exactly two callers: AppShell's language effect (a useLayoutEffect replacing App.tsx lines 320-323; defaultLocale consumed once via a ref; pageLocaleOverride(search, availableLocales) keeps its precedence) and useLocale().setLocale. en is applied through the same path, so a CMS edit to English lands at runtime.
  • Accepted: if a ?locale=fr page's bundle lands after clients/me, one English frame paints first (the case feat(i18n): take the language set from SahajCloud, not from supportedLanguages #168 measured as overlapped in both routing modes); locale-keyed caches then refetch once.

3. The language set

  • New src/hooks/use-languages.ts → availableLocales, or ['en'] when the read fails, is empty, or lacks the field (never offer a language whose publication cannot be proven; a CMS that cannot answer this cannot answer clients/me either).
  • SettingsMenu.tsx line 122: rows from useLanguages(), CMS order, nativeLanguageLabel endonyms. Standalone <html lang>/dir via Helmet and the widget root's lang/dir unchanged (i18n.dir('fa') is rtl).
  • hostHtmlLangDetector unchanged. The supportedLngs narrowing caveat from feat(i18n): take the language set from SahajCloud, not from supportedLanguages #168 disappears with the option.

4. Snapshot, sync script, gates, typing

  • scripts/sync-translations.mjs (pnpm sync:translations [--write]), modelled on scripts/sync-atlas-contract.mjs and feat(i18n): take the language set from SahajCloud, not from supportedLanguages #168's sync-atlas-languages.mjs: reads production only; key from ATLAS_API_KEY (shell or .env.local via Vite's loadEnv), falling back to VITE_SAHAJCLOUD_API_KEY only when VITE_SAHAJCLOUD_URL is the production origin — a local key must never reach production's logs; strips metadata, emails, event.title; sorts keys; refuses a missing tab or any blank value; exit 1 on drift without --write. Writes src/config/translations.en.json.
  • src/config/translations.test.ts replaces the parity gate: every literal t() key in src/** resolves in the snapshot; the dynamic families resolve from their constants (filters.format/cadence/time options, sort orders, REGISTRATION_QUESTION_NAMES, WEEK_NUMBER_KEYS, ERROR_POLICY[*].messageKey, both REFUSAL_MESSAGE_KEYS, STATE_MESSAGE_KEYS); sessions_count_one/_other present; no blank value; and every snapshot key is referenced (no dead copy in the CMS).
  • src/types/i18next.d.ts: CustomTypeOptions.resources = { translation: typeof snapshot } (typed t()); TranslationKey derived from Required<Pick<SyAtlasTranslation, …widget tabs>> after pnpm types:cms, with snapshot satisfies WidgetTranslations so the snapshot cannot drift from the CMS types. FallbackPolicy.messageKey and StripTranslate take TranslationKey.

5. Call sites, deletions, tests, docs

  • Rename every t() key through Appendix A of feat(translations): rewrite the Sahaj Atlas schema by widget view, seed all ten locales, and gate availableLocales on them SahajCloud#706 (33 files, listed under Files affected); collapse every useTranslation('common'|'events') and tEvents/tCommon pair to useTranslation(); ERROR_POLICY.messageKey renamed, fallbackText stays hardcoded (tracker decision 6).

  • Delete public/locales/**, scripts/add-locale-key.mjs + i18n:add, i18next-http-backend, the /locales/* rule in public/_headers, src/config/i18n-budgets.test.ts, VITE_HOST (its only reader was loadPath: .env, vite.config.ts CF_PAGES_URL fallback, serve-embed-review.mjs port derivation, docs).

  • Disk-reading tests: i18n-options.test.ts (drop bundle parity, UNTRANSLATED_EVENT_KEYS, supportedLngs round-trip; add preferredLanguage cases); i18n-budgets.test.ts (deleted — budgets are maxLength+strict in the CMS); src/types/event.test.ts lines 191-211 (deleted — CMS-side spec + the dynamic-family gate); src/lib/brand.test.ts, Fallbacks.test.tsx, CompactEmbedView.test.tsx, .ladle/i18n.ts (read the snapshot); src/styles/fonts.ts + test (subsets named against the CMS locale set: latin, latin-ext, cyrillic cover the ten; el/hy/fa/bg would need a subset and degrade to the system sans until added). The 18 component tests that mock react-i18next to echo keys get renamed expectations.

  • Smoke: boot-origins.smoke.test.ts drops the locale JSON (VITE_HOST) pattern and the three /locales/* tests, keeps the VITE_SAHAJCLOUD_URL private-origin check; robots.smoke.test.ts pins CORS-plus-noindex on /embed.js instead.

  • Size: en bundles are 3.3 KiB gzipped; bundled ≈ +3.5 KiB, minus ≈ 2 KiB for the backend; net ≈ +1.5 KiB against BUDGET_KIB = 308 on a ~300–303 KiB embed. Budget holds. If a build lands within 2.1 KiB of 308, raise to 310 in the same commit with the measurement.

  • Docs: docs/embedding.md — locale row (an unenabled language falls back to English; the set is SahajCloud's), "follows your page's language" section, CSP block (drop https://sahajatlas.com from connect-src; delete the "keep it regardless — the locale JSON" note and table row; say cloud.sydevelopers.com also serves the strings), "Where to load it from" (delete the compiled-in locale host and curl recipe), troubleshooting row "Every label reads like events.title" → "labels are English on a non-English page: connect-src cloud.sydevelopers.com missing, or the language is not enabled in SahajCloud". CHANGELOG.md Unreleased/Changed entry. AGENTS.md (i18n row, file layout, conventions bullet, _headers bullet, VITE_HOST bullet, Accent-history paragraph). docs/rules/i18n-and-state.md (+ .claude/rules symlink): i18next section rewritten around the snapshot, the single writer, count, and this workflow note from refactor(i18n): source translations from SahajCloud CMS #28:

    Translations are CMS-owned. All Sahaj Atlas UI copy lives in SahajCloud's sy-atlas-translations global — do not hand-edit strings in this app; src/config/translations.en.json is generated. To add, rename or remove a key, open an issue on sydevs/SahajCloud — search the open ones first and update the outstanding request rather than duplicating it. Once the CMS ships the key, run pnpm sync:translations --write and wire the t() here.

    Also docs/environment.md (VITE_HOST → ATLAS_API_KEY), docs/testing.md boot-origins story, docs/rules/mapbox.md port note, STORYBOOK.md.

Acceptance criteria

  • pnpm types:cms run after both SahajCloud children are on main; SyAtlasTranslation/SyAtlasConfig show the new shape (availableLocales, common.chrome, …).
  • No public/locales, i18next-http-backend, VITE_HOST, or /locales/* reference remains in source, config, _headers, tests or docs.
  • src/config/translations.en.json exists, is produced by pnpm sync:translations --write, and pnpm sync:translations reports no drift.
  • Every t() call site uses a key from Appendix A; pnpm typecheck rejects a misspelled key; translations.test.ts passes in both directions.
  • pnpm review:embed in a browser: locale=de renders German from the CMS; the picker lists exactly availableLocales; locale=it (not enabled) renders English with no error; no request to /locales/*; a compact card fetches only clients/me, the config and the translations; the standalone <html lang>/dir follow the active locale.
  • With the translations read failing (blocked in devtools), the widget renders English, never raw keys, and ERROR_POLICY.fallbackText still shows for a boot failure.
  • Copy budgets are no longer asserted here; i18n-budgets.test.ts and the event.test.ts questions check are gone with a pointer to the CMS specs.
  • pnpm size passes; the measured embed and any budget change are recorded in the PR.
  • docs/embedding.md, CHANGELOG.md, AGENTS.md, docs/rules/i18n-and-state.md updated as above.

Files affected

  • src/config/i18n.ts, src/config/i18n-options.ts (+test), new src/config/language.ts, src/config/translations.en.json, src/config/translations.test.ts, src/config/query-client.ts
  • src/config/api/client.ts, fetch.ts, index.ts (+fetch.test.ts); new src/types/atlas-config.ts, src/types/translations.ts, src/types/i18next.d.ts; src/types/index.ts
  • src/App.tsx, src/Widget.tsx, src/hooks/use-locale.ts, new src/hooks/use-languages.ts
  • t() call sites: src/hooks/use-event-display.ts; src/views/{CountriesView,SearchView,FilterView,RegionView,OnlineView,EventView,CalendarView,RegistrationView,ShareView,CompactEmbedView,DrawerStack (+strip-label.ts),FullInterface,fallbacks,shared}.tsx; src/components/atoms/Dropdown; src/components/molecules/{ActiveFilterPills,AddToCalendar,EventActions,EventChips,EventListItem,EventMetadata,Fallbacks,GeolocationPrompt,ImageCarousel,SearchFilters,SettingsMenu (+story),ShareContent (+platform-buttons),SortMenu}; src/components/organisms/{EventDetails/EventDetails,EventDetails/EventRegister,EventsList/LoadMore,Mapbox/Map,Mapbox/MapSearch,RegistrationForm,ReportIssueForm/ReportIssueForm,ReportIssueForm/ReportIssueModal}; the 18 component tests that echo keys
  • Tests: src/config/i18n-budgets.test.ts (delete), src/types/event.test.ts, src/lib/brand.test.ts, src/components/molecules/Fallbacks/Fallbacks.test.tsx, src/views/CompactEmbedView/CompactEmbedView.test.tsx, src/styles/fonts.ts + fonts.test.ts, tests/smoke/boot-origins.smoke.test.ts, tests/smoke/robots.smoke.test.ts
  • .ladle/i18n.ts; scripts/sync-translations.mjs (new), scripts/add-locale-key.mjs (delete), scripts/serve-embed-review.mjs; public/locales/** (delete), public/_headers; package.json, pnpm-lock.yaml, .env, vite.config.ts
  • Docs: docs/embedding.md, CHANGELOG.md, AGENTS.md, docs/rules/i18n-and-state.md, docs/environment.md, docs/testing.md, docs/rules/mapbox.md, STORYBOOK.md

Verification checklist

  • pnpm lint && pnpm typecheck && pnpm test:run && pnpm build && pnpm size && pnpm ladle:build
  • pnpm sync:translations (no drift) and pnpm sync:translations --write against production with ATLAS_API_KEY; confirm the script refuses a local VITE_SAHAJCLOUD_API_KEY.
  • Every new assertion reintroduced-as-a-defect and watched fail (docs/testing.md): the referenced-key gate both ways, the explicit-locale interceptor pin, preferredLanguage, the ['en'] fallback.
  • Browser (pnpm review:embed + Playwright): locale=de, locale=de-DE, locale=it, ?locale=fr on the page, picker switch, path routing (data-sahaj-atlas-ready reports {"routing":"path"}), compact card request list, standalone <html lang>.
  • Security review (trigger: src/config/api/, App.tsx, Widget.tsx, package.json, .env, vite.config.ts).
  • Smoke lane green against the Cloudflare preview with the trimmed boot-origins and robots specs.

References

Activity

  1. added theissue type on Sep 5, 2026
  2. sydevs-bot commented on Sep 12, 2026

    @sydevs-bot
    Contributor

    @Ardnived unblocked: every blocker is closed. Say @sydevs-bot implement to start.

    🤖 sydevs dispatcher

  3. Ardnived commented on Sep 12, 2026

    @Ardnived
    ContributorAuthor

    @sydevs-bot implement

  4. added
    bot:working
    and removed on Sep 12, 2026
  5. sydevs-bot commented on Sep 12, 2026

    @sydevs-bot
    Contributor

    🤖 no session running

    recent dispatches
    • 16:26Z implement · attempt 1 · session · done
    • 16:26Z implement · attempt 1 · session

    Written by the sydevs dispatcher. Sessions never edit this comment.

  6. removed
    bot:working
    on Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Fields

    Priority

    Medium

    Hold Until

    None yet

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions