Skip to content

Commit a058413

Browse files
fix(i18n): the Console language menu offers the platform locale table's languages (#31793)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbQ445c6fbGTJdveorKb6FDj)_ Fixes #30514 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — the published `objectstack-i18n` skill never says the Console menu offers a locale outside the platform table, and every `supportedLocales` example in it is a table language ## 维护者速读 - **改了什么**:Console 右上角语言菜单只提供平台语言表(11 种)里的语言,并与应用声明的语言取交集。`zh-CN` 这类旧写法显示成表里的名字(简体中文),同一语言只出现一次,`th` 这类表外语言不再出现。 - **为什么改**:裁决 F 规定平台只有一张语言表、不分档。此前菜单把应用列表原样照搬:所有自带应用都显示「中文(中国)」,还会提供没有任何界面翻译的 `th`。 - **风险与回滚**:这是一次收窄,受影响的自带应用为 0 个(examples 三个应用和 HotCRM 只声明表内语言)。已存储 `th` 的用户会先以 `th` 启动,应用列表到达后自动回到默认语言。回滚只需 revert 本 PR,无数据迁移。 - **先看**:`ui/packages/i18n/src/provider.tsx`(`offeredTableTags` 与自愈判断),`ui/packages/app-shell/src/layout/LocaleSwitcher.tsx`(勾选),`ui/apps/console/src/pages/system/ProfilePage.tsx`(存储值读法)。 - **两分钟验证**:`cd ui && pnpm exec vitest run packages/app-shell/src/layout/__tests__/LocaleSwitcher.appLocales.test.tsx`,预期全部通过,其中 app-crm、app-todo、HotCRM 三种声明都显示表内名称。 - **需要你做的**:无,席位落地(落地前席位需完成契约复审档复核)。 ## What changes `offerableLanguages` (the list the globe menu and the profile page's language card render) is now the platform locale table ∩ the app's locale list: - each code the app lists (`GET /api/v1/i18n/locales`) is read through `resolveBuiltInLanguage`, which applies the table's read aliases and then shorter prefixes, the same resolution that picks the pack the code renders in; - only codes that land on a table tag are kept, as that tag, de-duplicated, in the app's declared order; - an app answer with no table language, or no `loadLocales` wiring, offers the table's 11 tags. An out-of-table key of `config.resources` no longer adds an entry to that fallback. Around it: - **Self-heal.** The `provisional` self-heal (a stored language accepted on the loader's credit) is judged against the offered set, not the raw app list. A stored `th` still boots, then reverts and is cleared once the list lands, even when the app lists `th`. The loader's credit and `BootstrapLocaleOptions.hasLoader` are unchanged (seat amendment 2, option C). - **Checkmark.** `LocaleSwitcher` compares the session language through `resolveBuiltInLanguage`, so a session in `zh-CN` ticks 简体中文. - **Profile page.** `ProfilePage` reads a stored `sys_user.locale` spelling as its table tag (`zh-CN` → `zh-Hans`). Without that, the exact-match check prepended a stray 中文(中国) option beside 简体中文. A tag the table does not name stays as stored. ### What the menu offered before, measured Probe on `origin/main` c2bb879: the real `I18nProvider` with a mocked `loadLocales`. Step-1 report: #30514 comment 6731426750. | Case | `loadLocales()` answer | Before | After | |:--|:--|:--|:--| | 1 · no loader (control) | none | 11 table tags | unchanged | | 2a · table tags | `en, zh-Hans` | English, 简体中文 | unchanged | | 2b · app-crm, app-showcase | `en, zh-CN` | English, 中文(中国) | English, 简体中文 | | 2c · app-todo | `en, zh-CN, ja-JP` | …, 日本語 (日本) | …, 日本語 | | 2d · HotCRM sales | `en, zh-CN, ja-JP, es-ES` | …, Español de España | …, Español | | 3 · out-of-table | `en, zh-CN, th` | …, ไทย (no pack) | English, 简体中文 | | 4a · alias beside its tag | `en, zh-CN, zh-Hans` | two entries for one pack | one 简体中文 | | 4b · region variants | `de-AT, pt-PT, zh-TW, en-GB` | CLDR names (Português europeu served by `pt-BR`) | `de`, `pt-BR`, `zh-Hant`, `en` with table labels | | 5 · app declares nothing | the loaded bundle set | 11 entries, mixed spellings | the 11 table tags | ### Narrowing census: 0 first-party apps affected - `supportedLocales` declarations: examples/app-crm `['en', 'zh-CN']`, examples/app-showcase `['en', 'zh-CN']`, examples/app-todo `['en', 'zh-CN', 'ja-JP']`, HotCRM `src/sales/index.ts` `['en', 'zh-CN', 'ja-JP', 'es-ES']`. objectstack-ai/gallery declares none. - None names a language outside the table, and no example or HotCRM translations file is keyed outside it. - 0 in-repo producers pass `config.resources` to `I18nProvider` (`git grep` over `ui/apps`, `ui/packages`, `ui/examples`). ### Downstream readers of the offered tag A pick now writes the table tag (`zh-Hans`). `zh-Hans` was already an offered value before this PR, in cases 1, 2a and 5. Each reader accepts it, measured: - **The html lang attribute.** The provider writes `document.documentElement.lang = lng`, and the end-to-end pin's DOM shows `lang="zh-Hans"`. - **The locale header the adapter sends.** `createAuthenticatedFetch` copies the html lang attribute into `Accept-Language`. Both i18n providers resolve a request locale with `resolveLocaleAmong`, and `resolveLocaleAmong('zh-Hans', [en, zh-CN, ja-JP, es-ES, …])` = `zh-CN`, `ja` → `ja-JP`, `es` → `es-ES`. - **What gets stored back to `sys_user.locale`.** The column's `locale_bcp47_shape` rule (`SYS_USER_LOCALE_TAG_PATTERN`) accepts `zh-Hans`, `zh-Hant` and `pt-BR`. The messaging reader uses the same shape, and its bundle ladder is the same `resolveLocaleAmong`. ## Why Ruling F (#29428, of #29349): the platform supports one list of languages, each complete on every surface, with no tiers. Phases 2 and 3 completed the Console packs and the server bundles for the table's 11 languages. This phase makes the menu offer exactly those languages. ## Tests On `ui/` as of `bbc447f4`, from `ui/`, under `scripts/pm/os-verify-lock.sh`: - `packages/i18n/src/__tests__/`, `packages/app-shell/src/layout/__tests__/LocaleSwitcher*`, `apps/console/src/pages/system/__tests__/ProfilePage*`: Test Files 107/107, Tests 1873 passed, 13 skipped. - Consumers of the offered list (`app-shell/src/hooks/__tests__/userLocale*`, `AppHeader*`, `studio-locale.i18n`, console `i18nAfterSignIn-12034`, `loadLocales*`, `FirstRunChecklist`, `HomeLayout.searchOpensPalette-12601`, `sharedInboxFeed.twoSurfaces`, plugin-form `affordanceGrantMap-12082`): 46 files. 45 were green; `userLocale-10059` went red as expected and is the edited pin below, and that file now passes 24/24. New and rewritten pins: - `LocaleSwitcher.appLocales.test.tsx` - `th` is not offered, whether it comes from the app list or from `config.resources`; - the app-crm / app-todo / HotCRM declarations show table labels, once each; - `zh-CN` beside `zh-Hans` is one entry; - a session stored as `zh-CN` ticks 简体中文. - `provider-app-locale-restore.test.tsx` - a stored `th` boots, then reverts and is purged once the list lands; - a stored `zh-CN` stays and is offered as `zh-Hans`; - table ∩ app list as tags in app order; region variants; - the table fallback for an app listing no table language; - CONTROL: no loader offers the 11 table tags. - `ProfilePage.language.test.tsx` (new top-level describe) - a stored `zh-CN` is one option with nothing to save; - a stored `th` is still shown. Edited pin, approved by the seat: `userLocale-10059.test.tsx` "renders the offered variant for a bare column, end to end". A `zh` column with `loadLocales` `['en','zh-CN']` now shows `zh-Hans` (before: `zh-CN`). The offered entry is now the table tag; the pack is the same. Ablation of the canonicalizing step (`offeredTableTags` pushes the raw code instead of its table tag), through `scripts/ablation-replace.mjs`: - the anchor went x1 → x0, and the blob went `c7299ca5` → `2551b42e`; - 11 tests failed across `provider-app-locale-restore` and `LocaleSwitcher.appLocales` (Tests 11 failed, 22 passed); - the restore left the blob equal to HEAD with `git diff HEAD` empty. ## Acceptance notes - **Ruling F gaps outside this card**, carried on #29428 by the seat: - (a) the Studio namespace ships 2 of 11 languages, and `zh-Hant` resolves to the Simplified catalogue; - (b) the built-in emails ship 4 of 11 locales; - (c) `TranslationConfigSchema` accepts an out-of-table `supportedLocales` entry. This PR adds no language anywhere. It only removes entries. - `localeLabel`'s `Intl.DisplayNames` branch is now reached only for a code outside the table, which the menu no longer offers. It is left in place: it is exported and still named by its own tests. ## Verification - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 36 commands. All 36 were run and exited 0, and `--ran` reconciles 36 derived / 36 run / 0 NOT-MEASURED. The PR-body gates (`check-changeset-no-major`, `check-adr-0087-registration`, `check-closing-keyword-parity`, `check-partof-closing-keyword`) ran against this body and exited 0. - `pnpm --filter @object-ui/i18n run type-check` exited 0. The app-shell and console type-checks are left to CI's Type Check UI (they need the whole `ui/` closure built). - Head `96d210d4` merges `origin/main`. The incoming commits touch no file in this diff, and `ui/` is unchanged since `bbc447f4`, where the suites above ran. - The full dogfood battery is owed for the `(narrowing)` arm. It is running on `96d210d4`, and its reading goes in the os-dev-report on #30514. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` untouched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (`eslint` over the seven touched `ui/` files: 0 errors; the repo-wide run is CI's) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jRuaxwwjABz1AXpCeM)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 34a30e8 commit a058413

8 files changed

Lines changed: 267 additions & 84 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
'@object-ui/i18n': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/console': patch
5+
---
6+
7+
fix(i18n): the Console language menu offers the platform locale table's languages, intersected with the app's locale list
8+
9+
Clause-②: no (narrowing)
10+
Metadata-protocol: none
11+
12+
<!-- adr-0087: not-required (no-migration-prescription) no metadata an author writes changes: `i18n.supportedLocales` accepts the same values, `GET /api/v1/i18n/locales` reports the same list and no stored shape is rewritten; what narrows is the Console menu's reading of that list, and a language outside the platform locale table has no replacement spelling to migrate to -->
13+
14+
**BREAKING** for an app whose locale list names a language outside the platform locale table (for example `th`): the Console language menu no longer offers it. No first-party app does — examples/app-crm, app-showcase, app-todo and HotCRM declare only table languages, through read-alias spellings that now show as their table entries.
15+
16+
The Console language menu now offers the platform locale table's languages,
17+
intersected with the app's locale list (ruling F). `offerableLanguages` reads
18+
each code the app lists through the table's read aliases and offers table tags
19+
only, de-duplicated, in the app's order:
20+
21+
- a stored spelling is its table entry with the table's own label: an app
22+
declaring `zh-CN`, `ja-JP` or `es-ES` shows 简体中文, 日本語 and Español instead
23+
of 中文(中国), 日本語 (日本) and Español de España, and a pick writes the
24+
table tag (`zh-Hans`) to `sys_user.locale`;
25+
- two spellings of one language (`zh-CN` beside `zh-Hans`) are one entry;
26+
- a code the table does not name (for example `th`) is no longer offered, and
27+
neither is an out-of-table key of `config.resources` in the offline fallback.
28+
A stored choice of such a code still boots, then reverts and is cleared once
29+
the app's list arrives.
30+
31+
The menu's checkmark and the profile page's language card compare a stored
32+
spelling through the same resolution, so an account storing `zh-CN` sees one
33+
简体中文 entry, ticked.
34+
35+
Migration: none for a metadata author — `i18n.supportedLocales` accepts the
36+
same values and `GET /api/v1/i18n/locales` reports the same list. An app that
37+
relied on the menu offering a language outside the platform locale table has
38+
no replacement; that language is not complete on the platform's own surfaces.

‎ui/apps/console/src/pages/system/ProfilePage.tsx‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import {
3737
} from '@object-ui/components';
3838
import { useUpload } from '@object-ui/fields';
3939
import { ConsolePageHeader } from '@object-ui/app-shell';
40-
import { useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
40+
import { resolveBuiltInLanguage, useDisplayLocale, useObjectTranslation, type TranslateFn } from '@object-ui/i18n';
4141
import { useAdapter, extractFieldErrors, extractWriteErrorMessage } from '@object-ui/react';
4242
import { usePermissions } from '@object-ui/permissions';
4343
import { resolveFieldAffordance } from '@object-ui/core';
@@ -581,8 +581,8 @@ interface LanguageCardProps {
581581
* ## What is offered, and what happens when the write route is not there
582582
*
583583
* The option list is `offerableLanguages` — the i18n provider's own answer
584-
* (the deployment's published locales ∩ what this renderer can resolve), which
585-
* is what `LocaleSwitcher` renders too. ⛔ No second list is introduced here.
584+
* (the platform locale table ∩ the deployment's published locales, as table
585+
* tags), which is what `LocaleSwitcher` renders too. ⛔ No second list is introduced here.
586586
* A stored tag that is not in that set is prepended so the control shows the
587587
* truth rather than rendering blank.
588588
*
@@ -618,7 +618,15 @@ function LanguageCard({ userId }: LanguageCardProps) {
618618
.then((row) => {
619619
if (cancelled) return;
620620
const raw = (row as { locale?: unknown } | null)?.locale;
621-
const value = typeof raw === 'string' && raw.length > 0 ? raw : USE_DEPLOYMENT_DEFAULT;
621+
// A stored spelling of a platform locale table language (`zh-CN`) is
622+
// read as its table tag (`zh-Hans`), the value the offered list carries
623+
// (objectstack#30514). Read as-is, it matched no option and was
624+
// prepended beside the table entry: two options for one language.
625+
// A tag the table does not name stays as stored.
626+
const value =
627+
typeof raw === 'string' && raw.length > 0
628+
? (resolveBuiltInLanguage(raw) ?? raw)
629+
: USE_DEPLOYMENT_DEFAULT;
622630
setStored(value);
623631
setChoice(value);
624632
setRowRead(true);

‎ui/apps/console/src/pages/system/__tests__/ProfilePage.language.test.tsx‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,3 +271,37 @@ describe('ProfilePage — my language (objectui#7501)', () => {
271271
warn.mockRestore();
272272
});
273273
});
274+
275+
describe('ProfilePage — a stored spelling of a table language (objectstack#30514)', () => {
276+
beforeEach(() => {
277+
vi.clearAllMocks();
278+
user.value = { id: 'usr_1', name: 'Ada', email: 'ada@example.com' };
279+
writable.value = true;
280+
update.mockResolvedValue({});
281+
});
282+
283+
it('reads a stored zh-CN as the offered zh-Hans: one option, nothing to save', async () => {
284+
// The provider offers table tags; every first-party account that picked
285+
// Chinese before the table existed stores `zh-CN`.
286+
offerable.value = ['en', 'zh-Hans'];
287+
findOne.mockResolvedValue({ id: 'usr_1', locale: 'zh-CN' });
288+
const select = await renderProfile();
289+
290+
const options = await listed(select);
291+
// Deployment default + the two offered entries: no stray 中文(中国)
292+
// prepended beside 简体中文.
293+
expect(options).toHaveLength(3);
294+
expect(options).not.toContain('中文(中国)');
295+
expect(select).toHaveTextContent(options[2]);
296+
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled();
297+
});
298+
299+
it('still shows a stored tag the table does not name', async () => {
300+
offerable.value = ['en', 'zh-Hans'];
301+
findOne.mockResolvedValue({ id: 'usr_1', locale: 'th' });
302+
const select = await renderProfile();
303+
304+
expect(await listed(select)).toHaveLength(4);
305+
expect(select).toHaveTextContent('ไทย');
306+
});
307+
});

‎ui/packages/app-shell/src/hooks/__tests__/userLocale-10059.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ describe('pickRenderableLocale follows the server resolveLocale order', () => {
346346
</I18nProvider>,
347347
);
348348

349-
await waitFor(() => expect(shownLanguage()).toBe('zh-CN'));
349+
// The offered entry is the platform locale table tag since objectstack#30514.
350+
await waitFor(() => expect(shownLanguage()).toBe('zh-Hans'));
350351
});
351352
});

‎ui/packages/app-shell/src/layout/LocaleSwitcher.tsx‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
* Uses the i18n context to change language at runtime.
66
*
77
* The menu is not a list of its own (objectui#4039): it renders whatever the
8-
* i18n provider says is offerable — the app's own locale list ∩ what the
9-
* renderer can resolve. This file owns only the *labels*, because the native
8+
* i18n provider says is offerable — the platform locale table ∩ the app's own
9+
* locale list, as table tags (objectstack#30514). This file owns only the *labels*, because the native
1010
* names are the one piece of that no API response supplies:
1111
* `GET /api/v1/i18n/locales` returns descriptors whose `label` is the code
1212
* echoed back (`toLocaleDescriptors` in @objectstack/spec), so a server label
@@ -28,7 +28,7 @@ import {
2828
DropdownMenuItem,
2929
DropdownMenuTrigger,
3030
} from '@object-ui/components';
31-
import { useObjectTranslation } from '@object-ui/i18n';
31+
import { resolveBuiltInLanguage, useObjectTranslation } from '@object-ui/i18n';
3232
import { PLATFORM_LOCALES } from '@objectstack/spec/system';
3333
import { confirmUnsavedLeave } from '../chrome/unsavedEdits.js';
3434
import { useLanguageSelection } from '../hooks/useUserLocale.js';
@@ -89,6 +89,11 @@ export function LocaleSwitcher() {
8989
// past on an app that only ships two.
9090
if (offerableLanguages === null) return null;
9191

92+
// The entries are table tags (`zh-Hans`); the session may be running in a
93+
// stored spelling of one (`zh-CN`). Compare through the same resolution the
94+
// provider builds the entries with, so that session ticks 简体中文.
95+
const current = resolveBuiltInLanguage(language) ?? language;
96+
9297
// objectui#13254 — a switch drops a page's unsaved edits: the console shell
9398
// remounts every page on a language change (`key={language}` in
9499
// `ConnectedShellInner`, which relabels the labels the server translates). So
@@ -117,7 +122,7 @@ export function LocaleSwitcher() {
117122
className="gap-2"
118123
>
119124
{localeLabel(code)}
120-
{language === code && <span className="ml-auto text-xs">✓</span>}
125+
{current === code && <span className="ml-auto text-xs">✓</span>}
121126
</DropdownMenuItem>
122127
))}
123128
</DropdownMenuContent>

‎ui/packages/app-shell/src/layout/__tests__/LocaleSwitcher.appLocales.test.tsx‎

Lines changed: 52 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,19 @@
1111
* shipping only `en`+`zh` still listed all ten, so picking 日本語 handed the
1212
* user a half-translated UI its author never opted into.
1313
*
14-
* The ruling on the card is INTERSECTION: (the app's `/api/v1/i18n/locales`
15-
* response) ∩ (what this renderer can resolve — built-in packs,
16-
* `config.resources`, and anything the dynamic loader can fetch). The hardcoded
17-
* ten survive only as the offline/no-backend fallback.
14+
* The ruling on the card is INTERSECTION, narrowed by ruling F of
15+
* objectstack#29349 (objectstack#30514): (the platform locale table) ∩ (the
16+
* app's `/api/v1/i18n/locales` response, read through the table's read
17+
* aliases). Each entry is a table tag with the table's own label, two
18+
* spellings of one language are one entry, and a code the table does not
19+
* name (`th`) is not offered. The table's tags survive alone as the
20+
* offline/no-backend fallback.
1821
*/
1922

2023
import '@testing-library/jest-dom/vitest';
2124
import { describe, it, expect, beforeEach, vi } from 'vitest';
2225
import { render, screen, waitFor } from '@testing-library/react';
23-
import { I18nProvider } from '@object-ui/i18n';
26+
import { I18nProvider, LOCALE_STORAGE_KEY } from '@object-ui/i18n';
2427

2528
// Passthrough dropdown primitives — the open/close choreography is Radix's
2629
// business; what matters here is which items the menu is built from.
@@ -74,24 +77,61 @@ beforeEach(() => {
7477
});
7578

7679
describe('LocaleSwitcher — menu composed from the app locale list', () => {
77-
it('offers an app-shipped locale outside the built-in ten, named by Intl.DisplayNames', async () => {
80+
it('does not offer an app locale the platform locale table does not name', async () => {
7881
mountConsole({ locales: async () => ['en', 'zh-Hans', 'th'] });
7982

80-
// `th` has no built-in pack and no platform locale table row; CLDR names it.
81-
await waitFor(() => expect(screen.getByText('ไทย')).toBeInTheDocument());
82-
expect(screen.getByText('English')).toBeInTheDocument();
83+
// `th` has no Console pack, no Studio catalogue, no platform bundle and no
84+
// built-in email: offering it would offer an incomplete language, which
85+
// ruling F rules out. The app's other entries stay.
86+
await waitFor(() => expect(screen.getByText('English')).toBeInTheDocument());
8387
expect(screen.getByText('简体中文')).toBeInTheDocument();
88+
expect(screen.queryByText('ไทย')).not.toBeInTheDocument();
8489
});
8590

86-
it('offers an app-shipped locale supplied through config.resources', async () => {
91+
it('does not offer an out-of-table locale supplied through config.resources either', async () => {
8792
mountConsole({
8893
locales: async () => ['en', 'th'],
8994
resources: { th: { common: { save: 'บันทึก' } } },
9095
loader: false,
9196
});
9297

93-
await waitFor(() => expect(screen.getByText('ไทย')).toBeInTheDocument());
94-
expect(screen.getByText('English')).toBeInTheDocument();
98+
await waitFor(() => expect(screen.getByText('English')).toBeInTheDocument());
99+
expect(screen.queryByText('ไทย')).not.toBeInTheDocument();
100+
});
101+
102+
it.each([
103+
['app-crm / app-showcase', ['en', 'zh-CN'], ['English', '简体中文']],
104+
['app-todo', ['en', 'zh-CN', 'ja-JP'], ['English', '简体中文', '日本語']],
105+
['HotCRM sales', ['en', 'zh-CN', 'ja-JP', 'es-ES'], ['English', '简体中文', '日本語', 'Español']],
106+
])('reads a %s declaration in stored spellings as table entries, with table labels', async (_app, declared, labels) => {
107+
mountConsole({ locales: async () => declared });
108+
109+
await waitFor(() => expect(screen.getByText('English')).toBeInTheDocument());
110+
// Each table row once, never the CLDR name of the stored spelling
111+
// (中文(中国), 日本語 (日本), Español de España).
112+
for (const label of labels) expect(screen.getAllByText(label)).toHaveLength(1);
113+
expect(screen.queryByText('中文(中国)')).not.toBeInTheDocument();
114+
expect(screen.queryByText('日本語 (日本)')).not.toBeInTheDocument();
115+
expect(screen.queryByText('Español de España')).not.toBeInTheDocument();
116+
});
117+
118+
it('lists a stored spelling beside its own table tag as ONE entry', async () => {
119+
mountConsole({ locales: async () => ['en', 'zh-CN', 'zh-Hans'] });
120+
121+
await waitFor(() => expect(screen.getByText('English')).toBeInTheDocument());
122+
// One pack, one entry.
123+
expect(screen.getAllByText('简体中文')).toHaveLength(1);
124+
expect(screen.queryByText('中文(中国)')).not.toBeInTheDocument();
125+
});
126+
127+
it('ticks the table entry for a session running in a stored spelling', async () => {
128+
// A choice stored before the table existed: `zh-CN`, served by `zh-Hans`.
129+
window.localStorage.setItem(LOCALE_STORAGE_KEY, 'zh-CN');
130+
mountConsole({ locales: async () => ['en', 'zh-CN'] });
131+
132+
await waitFor(() => expect(screen.getByText('简体中文')).toBeInTheDocument());
133+
expect(screen.getByText('简体中文').textContent).toContain('✓');
134+
expect(screen.getByText('English').textContent).not.toContain('✓');
95135
});
96136

97137
it('names a regional app locale, capitalized like the built-in labels', async () => {

‎ui/packages/i18n/src/__tests__/provider-app-locale-restore.test.tsx‎

Lines changed: 56 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,16 @@
1515
*
1616
* A "reload" here is an unmount + a fresh `I18nProvider` mount — a new i18next
1717
* instance, so anything it knows had to come out of storage.
18+
*
19+
* objectstack#30514 (ruling F of objectstack#29349) narrowed the menu to the
20+
* platform locale table's languages, so an out-of-table app locale like `th`
21+
* is no longer offered: it still boots on the loader's credit, and the
22+
* self-heal then reverts and purges it once the app's list lands.
1823
*/
1924
import { describe, it, expect, beforeEach } from 'vitest';
2025
import { renderHook, act, waitFor } from '@testing-library/react';
2126
import React from 'react';
27+
import { PLATFORM_LOCALE_TAGS } from '@objectstack/spec/system';
2228
import { I18nProvider, useObjectTranslation, LOCALE_STORAGE_KEY } from '../provider';
2329

2430
/** The console's wiring: app packs fetched on demand, nothing in `resources`. */
@@ -42,20 +48,30 @@ beforeEach(() => {
4248
});
4349

4450
describe('app-locale restore (lockstep with the switcher)', () => {
45-
it('restores an app-shipped locale that has no built-in pack', async () => {
46-
const first = mountConsole();
47-
await act(async () => {
48-
await first.result.current.changeLanguage('th');
49-
});
50-
await waitFor(() => expect(window.localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('th'));
51-
first.unmount();
52-
53-
// Reload. Before the widening this asserted `en`: `th` is not a built-in
54-
// pack and not in `config.resources`, so the restore validation dropped
55-
// AND purged it — the user's pick lost on the first F5.
56-
const second = mountConsole();
57-
expect(second.result.current.language).toBe('th');
58-
expect(window.localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('th');
51+
it('boots a stored out-of-table locale, then reverts and purges it once the list lands', async () => {
52+
// objectstack#30514: the menu offers only the platform locale table's
53+
// languages, so `th` is never offered — not even when the app lists it.
54+
// The bootstrap still accepts it on the loader's credit (nothing
55+
// synchronous can tell), and the self-heal then adjudicates it against
56+
// what the menu OFFERS, not against the raw app list.
57+
window.localStorage.setItem(LOCALE_STORAGE_KEY, 'th');
58+
59+
const { result } = mountConsole();
60+
61+
expect(result.current.language).toBe('th');
62+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh-Hans']));
63+
await waitFor(() => expect(result.current.language).toBe('en'));
64+
expect(window.localStorage.getItem(LOCALE_STORAGE_KEY)).toBeNull();
65+
});
66+
67+
it('keeps a stored spelling of a table language, which the menu offers as its tag', async () => {
68+
window.localStorage.setItem(LOCALE_STORAGE_KEY, 'zh-CN');
69+
70+
const { result } = mountConsole({}, ['en', 'zh-CN']);
71+
72+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh-Hans']));
73+
expect(result.current.language).toBe('zh-CN');
74+
expect(window.localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('zh-CN');
5975
});
6076

6177
it('restores it in the BOOTSTRAP language, not as a late correction', () => {
@@ -153,10 +169,31 @@ describe('app-locale restore (lockstep with the switcher)', () => {
153169
});
154170

155171
describe('offerableLanguages — the intersection the switcher renders', () => {
156-
it('is the app list ∩ what this renderer can resolve', async () => {
157-
const { result } = mountConsole({}, ['en', 'zh', 'th']);
172+
it('is the platform locale table ∩ the app list, as table tags in the app order', async () => {
173+
// `zh` and `zh-CN` are two spellings of `zh-Hans`: one entry. `th` lands
174+
// on no table tag: not offered, although the loader could fetch it.
175+
const { result } = mountConsole({}, ['ja-JP', 'en', 'zh', 'zh-CN', 'th']);
176+
177+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['ja', 'en', 'zh-Hans']));
178+
});
179+
180+
it('reads region variants through the table, as the pack that serves them', async () => {
181+
const { result } = mountConsole({}, ['de-AT', 'zh-TW', 'en-GB']);
182+
183+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['de', 'zh-Hant', 'en']));
184+
});
185+
186+
it('falls back to the table when the app lists no table language', async () => {
187+
const { result } = mountConsole({}, ['th']);
188+
189+
await waitFor(() => expect(result.current.offerableLanguages).not.toBeNull());
190+
expect(result.current.offerableLanguages).toEqual(PLATFORM_LOCALE_TAGS);
191+
});
192+
193+
it('offers the table tags when no locale list is wired (control)', () => {
194+
const { result } = mountConsole({}, null);
158195

159-
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh', 'th']));
196+
expect(result.current.offerableLanguages).toEqual(PLATFORM_LOCALE_TAGS);
160197
});
161198

162199
it('drops an app locale this renderer cannot produce', async () => {
@@ -170,7 +207,7 @@ describe('offerableLanguages — the intersection the switcher renders', () => {
170207

171208
// No loader and no `config.resources`: `th` is in the app's list but this
172209
// renderer has no way to produce a single string of it.
173-
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh']));
210+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh-Hans']));
174211
});
175212

176213
it('is null while the app list is in flight', () => {
@@ -201,7 +238,7 @@ describe('offerableLanguages — the intersection the switcher renders', () => {
201238
);
202239
const { result, rerender } = renderHook(() => useObjectTranslation(), { wrapper });
203240

204-
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh']));
241+
await waitFor(() => expect(result.current.offerableLanguages).toEqual(['en', 'zh-Hans']));
205242
rerender();
206243
rerender();
207244
expect(calls.n).toBe(1);

0 commit comments

Comments
 (0)