Skip to content

Commit 1089e9e

Browse files
fix(console): a user with no personal language gets their browser's language when the app ships it, else the app default (#34399)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X5Dqh7NEiHRd1ETkL7pny2w)_ Fixes #33985 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:没有设置个人语言的用户打开 Console 时,浏览器语言在应用的支持列表里就用浏览器语言;不在列表里才用应用默认语言。个人语言(`sys_user.locale`)和在本设备上手动选的语言仍然优先。 - 为什么改:18.5.0 把应用默认语言放在浏览器语言之前,而应用总有默认语言,结果中文浏览器在「默认英文、也支持中文」的应用里一律看到英文(hotclm、duly、hotcrm 三家实测)。你裁定 B「浏览器语言受支持就优先」。 - 风险与回滚:只改 Console 前端两处语言请求头的取值,不改服务端和协议;回滚即 revert 本 PR。设备上已缓存的语言种子会在下次启动时被刷新为新答案。 - 先看:`ui/apps/console/src/languageSeed.ts` 的 `pickPreferredLocale`(匹配规则:走服务端同一条 `resolveLocaleAmong` 阶梯,精确、大小写不敏感、平台别名 `ja`→`ja-JP`、基础语言 `en-US`→`en`、变体 `es-MX`→`es-ES`、`zh`→`zh-CN`);`LocalizationFetchProvider.tsx` 的取值改名处。 - 两分钟验证:`cd ui && pnpm exec vitest run apps/console/src/languageSeed.test.ts` 应全绿,其中「zh-CN 浏览器 + 支持 en/zh-CN + 默认 en → zh-CN」与「fr 浏览器 → en」两条即裁决的钉子。 - 需要你做的:无,席位落地。 ## What changes For a signed-in user with no personal language, the Console's language is now the user's own `sys_user.locale`, else the browser's language when the app lists it in discovery `locale.supported`, else the app's declared default (discovery `locale.default`), else `en`. This carries out ruling 6915665005 on #33985 (letter B, maintainer 「B 浏览器语言受支持就优先」), unchanged. - `ui/apps/console/src/languageSeed.ts`: `loadAppDefaultLocale` becomes `loadPreferredLocale`, which reads discovery `locale.default` and `locale.supported` through the console's one shared discovery request and states `pickPreferredLocale(navigator.language, supported, default)` as the `Accept-Language` of the boot's `/api/v1/auth/me/localization` read. `startedAppDefaultLocale` and the test seam are renamed to match. The module docblock's #33231 section is rewritten to the ruling. - `pickPreferredLocale` (new, exported for the tests): the browser's top tag (`navigator.language`) is matched against `locale.supported` through `resolveLocaleAmong` (`@objectstack/spec/system`), the server's own `Accept-Language` ladder: exact, case-insensitive, platform table aliases (`ja` → `ja-JP`, `zh-TW` → `zh-Hant`), base language (`en-US` → `en`), variant (`es-MX` → `es-ES`, `zh` → `zh-CN`); no match ⇒ the app default. The answer is the app's own spelling of the entry. - `ui/apps/console/src/LocalizationFetchProvider.tsx`: the every-boot read states the same value (`startedPreferredLocale`), so the seed read and this read still share one request on a first visit. Unchanged: an explicit device choice is stated as before; with discovery answering nothing, the browser's own header goes out. - No server, spec or protocol change; `locale.supported` was already served. The ruling's finding 3 (the organization's Localization setting never reaches the Console's language, because the Console always states a language and the server's deployment-default rung never answers) is not in this PR, per the ruling. Confirmed from the code (discovery `locale.default` is the i18n service's `getDefaultLocale()`, the app's `i18n.defaultLocale`) and filed as #34392. ## Tests - `languageSeed.test.ts`: the #33231 block is rewritten per the ruling's "After the ruling". Rendered boot pins (seed → `preloadBootstrapLocale` → `I18nProvider` probe of `common.cancel` and `<html lang>`): a `zh-CN` browser with `supported: ['en','zh-CN']` and default `en` gets `zh-CN`; CONTROL, an `fr` browser on the same app gets `en`; the #33231 pin, rewritten to the case it still owns: an `en-US` browser on a `zh-CN`-only app gets `zh-CN`; an `en-US` browser on a `zh-CN` app that also ships `en` gets `en` (the ruling's stated cost of B); a personal locale still outranks both; with no locale block served the browser's own header goes. Plus unit pins of `pickPreferredLocale`. - `LocalizationFetchProvider.test.tsx`: the read states a supported browser language (`zh-CN` on an `en`-default app), and states the app default for an unsupported one (`fr` on a `zh-CN` app). - `__tests__/localizationBootDedup.test.tsx`: the one-request pin now runs on the browser-language path (both reads state `zh-CN`, one localization request). <details><summary>Test run and ablation at <code>b8ce00c8</code></summary> - `cd ui && pnpm exec vitest run apps/console/src/languageSeed.test.ts apps/console/src/LocalizationFetchProvider.test.tsx apps/console/src/__tests__/localizationBootDedup.test.tsx` (under `os-verify-lock.sh`, after the `@object-ui/console^...` closure build): `Test Files 3 passed (3)`, `Tests 47 passed (47)`, `VERDICT command-exit 0`. - Ablation (one, through `scripts/ablation-replace.mjs`, fix committed first): `languageSeed.ts` anchor `const tag = typeof browserTag === 'string' ? browserTag.trim().toLowerCase() : '';` replaced by `const tag = '';` (anchor x1 -> x0, blob `210683d22911` -> `25f7a6f1e9b3`), which is the 18.5.0 behaviour (app default always). Same three files: `Tests 6 failed | 41 passed (47)`; red: the zh-CN browser pin, the en-US-to-en pin, both `pickPreferredLocale` match pins, the provider's supported-browser pin, the one-request pin. The CONTROL (`fr` → `en`) and the unsupported-language pins stayed green, as they should. Restored: blob == HEAD (`210683d22911`), `git diff HEAD` empty. </details> ## Acceptance notes - Matching rule: the ruling says "the browser's language when the app lists it". This PR reads it as follows: the browser's top tag (`navigator.language`) is matched against `locale.supported` through `resolveLocaleAmong` (`@objectstack/spec/system`), the server's own `Accept-Language` ladder: exact, case-insensitive, platform table aliases (`ja` → `ja-JP`, `zh-TW` → `zh-Hant`), base language (`en-US` → `en`), variant (`es-MX` → `es-ES`, `zh` → `zh-CN`); no match ⇒ the app default. Changed in fix round 1 (L1 REWORK 6917299693) from a two-step matcher, so `ja`, `zh-TW` and `es-MX` browsers get the language the app ships. - Out of scope, filed: #34392 (finding 3 of the ruling record). ## Verification <details><summary>Local gates at <code>b8ce00c8</code> (38 derived + console type-check, all exit 0)</summary> - `pnpm --filter @object-ui/console type-check` :: exit 0 (`tsc --noEmit && tsc -b tsconfig.node.json --force`, after the closure build; compiles the test files). - `node scripts/pm/dispatch-gates.mjs --commands` derived 38 families; all 38 run, each exit 0; `--ran` reconciliation: `38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero — all 38 recorded an exit code and none of them is 3)`. Families: check-adr-0087-registration (base + self-test), check-changeset-no-major, check-closing-keyword-parity (+ self-test), check-comment-mask-corpus, check-empty-changeset (base + self-test), check-sdui-manifest (+ self-test), snapshot-next, check-governed-queue-guard, release-rehearsal-clone, release-pending-publish self-tests, `pnpm --dir ui exec vitest run scripts/`, spec check:duration-unit-keys, check:adr-anchors, check:changeset-gate-self-tests, check:closed-ceremony-text, check:cross-package-test-inputs, check:dispatcher-error-vocabulary, check:driver-memory-census, check:engine-double-contract, check:error-status-conformance, check:gitlink-declared, check:nul-bytes, check:published-files, check:query-options-erasure, check:refd-timer-probe, check:registry-log-declared, check:rest-log-spy-declared, check:test-source-alias, check:tier-file-adoption, check:type-check-coverage, check:type-check-debt, check:undeclared-dep-imports, check:watch-hint-literal, check:where-matcher. - Not run locally (CI-owned): the whole console vitest project, `pnpm lint`, `test:repo`, and the families outside the derivation. Full dogfood not owed (no `!` in the title, no `(narrowing)` arm). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes (CI-owned run). - [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 (the maintainer brief excepted). 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5mV676uKv5vXZ12fc8 <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5pmEYLVFDcQ1Z1CS8H --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cfcba53 commit 1089e9e

6 files changed

Lines changed: 248 additions & 88 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/console': patch
3+
---
4+
5+
fix(console): a user with no personal language gets their browser's language when the app ships it, and the app's default language otherwise
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Since 18.5.0 the Console stated the app's declared default (discovery `locale.default`) as the `Accept-Language` of its language reads whenever the device held no explicit choice. Discovery always serves a default, so the browser's language was never asked: a zh-CN browser on an app with `i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }` booted an English Console, where 18.3.0 booted Chinese.
11+
12+
For a signed-in user with no `sys_user.locale`, the Console's language is now the browser's language when the app lists it in discovery `locale.supported`, else the app's declared default, else `en` (maintainer ruling, letter B). The browser's language is its top tag (`navigator.language`), and "the app lists it" is answered by the platform's one locale ladder (`resolveLocaleAmong`), the same matcher the server's `Accept-Language` rung uses: `ja` matches `ja-JP`, `zh-TW` matches `zh-Hant`, `en-US` matches `en`, `es-MX` matches `es-ES`. The Console states the app's own spelling of that entry. A browser language the app does not ship still gets the app's default, as in 18.5.0. A stored `sys_user.locale` or a language picked on the device still wins over both. No server or protocol change.

‎ui/apps/console/src/LocalizationFetchProvider.test.tsx‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import { notifyDataChanged } from '@object-ui/react';
3232
import { resetInflightGetsForTesting } from '../../../packages/types/src/http-inflight';
3333
import { clearSharedDiscoveryCache } from '../../../packages/data-objectstack/src/sharedDiscovery';
3434
import { LocalizationFetchProvider } from './LocalizationFetchProvider';
35-
import { __resetAppDefaultLocaleForTests, loadAppDefaultLocale } from './languageSeed';
35+
import { __resetPreferredLocaleForTests, loadPreferredLocale } from './languageSeed';
3636
// Not on the `@object-ui/auth` barrel; the vitest alias maps that barrel to
3737
// `packages/auth/src`, so this deep path is the SAME module instance the
3838
// provider's `getSessionOwnerChangeCount` reads.
@@ -403,32 +403,49 @@ describe('LocalizationFetchProvider', () => {
403403
authUser = null;
404404
window.localStorage.clear();
405405
resetInflightGetsForTesting();
406-
__resetAppDefaultLocaleForTests();
406+
__resetPreferredLocaleForTests();
407+
vi.restoreAllMocks();
407408
clearSharedDiscoveryCache();
408409
});
409410

410-
it("with no choice on this device, the read states the app's declared default (objectstack#33231)", async () => {
411-
// Discovery serves `locale.default: 'zh-CN'`; the server answers the
412-
// `Accept-Language` rung with what it was told, else the browser's en-US.
411+
/** Discovery serving `locale`, and a server answering the `Accept-Language` rung with what it was told. */
412+
function serveDiscovery(locale: { default: string; supported: string[] }) {
413413
fetchMock().mockImplementation(async (url: string, init: RequestInit) =>
414414
String(url).endsWith('/api/v1/discovery')
415-
? ok({ success: true, data: { locale: { default: 'zh-CN', supported: ['zh-CN'], timezone: 'UTC' } } })
415+
? ok({ success: true, data: { locale: { ...locale, timezone: 'UTC' } } })
416416
: ok({
417417
authenticated: true,
418418
currency: null,
419419
locale: (init.headers as Record<string, string>)['Accept-Language'] ?? 'en-US',
420420
timezone: 'UTC',
421421
}),
422422
);
423+
}
424+
425+
it('with no choice on this device, the read states a browser language the app ships (objectstack#33985)', async () => {
426+
serveDiscovery({ default: 'en', supported: ['en', 'zh-CN'] });
427+
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zh-CN');
423428
// The boot starts this read before the app mounts (`seedTenantLanguage`).
424-
void loadAppDefaultLocale('');
429+
void loadPreferredLocale('');
425430

426431
renderUnderLanguage('zh-CN');
427432

428433
await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日'));
429434
expect(statedOn(1)).toBe('zh-CN');
430435
expect(fetchMock()).toHaveBeenCalledTimes(2);
431-
// The seed the next boot reads is the app's default, not the browser's.
436+
// The seed the next boot reads is the browser's supported language.
437+
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('zh-CN');
438+
});
439+
440+
it("with no choice on this device, a browser language the app does not ship states the app's default", async () => {
441+
serveDiscovery({ default: 'zh-CN', supported: ['zh-CN'] });
442+
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('fr');
443+
void loadPreferredLocale('');
444+
445+
renderUnderLanguage('zh-CN');
446+
447+
await waitFor(() => expect(screen.getByTestId('display')).toHaveTextContent('zh-CN|2026年10月11日'));
448+
expect(statedOn(1)).toBe('zh-CN');
432449
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('zh-CN');
433450
});
434451

‎ui/apps/console/src/LocalizationFetchProvider.tsx‎

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -66,16 +66,17 @@
6666
* one still in flight under the old language: the in-flight key includes the
6767
* headers.
6868
*
69-
* ## With no choice, state the app's declared default (objectstack#33231)
69+
* ## With no choice, state a supported browser language, else the app default (objectstack#33985)
7070
*
7171
* The browser's header answered the `Accept-Language` rung for a user with no
72-
* `sys_user.locale`, so both the dates here and the language seed this read
73-
* refreshes followed the browser, never the app's declared default (discovery
74-
* `locale.default`). With no explicit choice on the device, this read states
75-
* that default instead, the same value `seedTenantLanguage()` states, so the
76-
* two still share one request on a first visit. Only when no default is
77-
* served (discovery failed, or never asked, as outside the console's boot)
78-
* does the browser's own header go out.
72+
* `sys_user.locale`, whatever the app ships. With no explicit choice on the
73+
* device, this read states the language the maintainer's ruling (letter B,
74+
* record 6915665005) names for that user: the browser's language when the app
75+
* lists it in discovery `locale.supported`, else the app's declared default
76+
* (`locale.default`). It is the same value `seedTenantLanguage()` states
77+
* (`loadPreferredLocale`), so the two still share one request on a first
78+
* visit. Only when discovery answers neither (it failed, or was never asked,
79+
* as outside the console's boot) does the browser's own header go out.
7980
*/
8081
import { useEffect, useState } from 'react';
8182
import {
@@ -86,7 +87,7 @@ import {
8687
type LocalizationValue,
8788
} from '@object-ui/i18n';
8889
import { getSessionOwnerChangeCount, useAuth } from '@object-ui/auth';
89-
import { startedAppDefaultLocale } from './languageSeed';
90+
import { startedPreferredLocale } from './languageSeed';
9091
import { useDataInvalidation } from '@object-ui/react';
9192
import {
9293
HttpFetchError,
@@ -126,8 +127,8 @@ export function LocalizationFetchProvider({
126127
// Bumps on every write to the signed-in user's own row (objectstack#27498).
127128
const userRowWrites = useDataInvalidation(userId ? 'sys_user' : undefined, userId);
128129
// The device's chosen UI language, stated as this read's `Accept-Language`
129-
// (objectstack#27625); none chosen, the app's declared default is stated
130-
// inside the effect (objectstack#33231).
130+
// (objectstack#27625); none chosen, a supported browser language, else the
131+
// app's declared default, is stated inside the effect (objectstack#33985).
131132
const { language } = useObjectTranslation();
132133
const statedLanguage = readStoredLanguage() ? language : undefined;
133134

@@ -140,12 +141,13 @@ export function LocalizationFetchProvider({
140141

141142
// Read when the effect runs, not at render: `seedTenantLanguage()` starts it
142143
// before the app mounts, and nothing in it is React state.
143-
const appDefaultRead = statedLanguage ? null : startedAppDefaultLocale();
144+
const preferredRead = statedLanguage ? null : startedPreferredLocale();
144145

145146
void (async () => {
146-
// No explicit choice ⇒ the app's declared default decides the rung below
147-
// the user's own locale; none served, the browser's own header goes out.
148-
const preference = statedLanguage ?? (appDefaultRead ? await appDefaultRead : undefined);
147+
// No explicit choice ⇒ a supported browser language, else the app's
148+
// declared default, decides the rung below the user's own locale;
149+
// discovery answering neither, the browser's own header goes out.
150+
const preference = statedLanguage ?? (preferredRead ? await preferredRead : undefined);
149151
if (cancelled) return;
150152
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
151153
// Whose answer this attempt will be (objectui#10193). The request

‎ui/apps/console/src/__tests__/localizationBootDedup.test.tsx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,15 @@ import { render, screen, waitFor } from '@testing-library/react';
1818
import { useLocalization, readCachedLanguageSeed } from '@object-ui/i18n';
1919
import { clearSharedDiscoveryCache } from '../../../../packages/data-objectstack/src/sharedDiscovery';
2020
import { resetInflightGetsForTesting } from '../../../../packages/types/src/http-inflight';
21-
import { __resetAppDefaultLocaleForTests, seedTenantLanguage } from '../languageSeed';
21+
import { __resetPreferredLocaleForTests, seedTenantLanguage } from '../languageSeed';
2222
import { LocalizationFetchProvider } from '../LocalizationFetchProvider';
2323

2424
const ENDPOINT = '/api/v1/auth/me/localization';
2525
const DISCOVERY = '/api/v1/discovery';
2626

2727
/**
28-
* The boot's discovery read (objectstack#33231) is the data adapter's request,
29-
* not this endpoint's: these answer it as a server serving no default, unless a
28+
* The boot's discovery read (objectstack#33985) is the data adapter's request,
29+
* not this endpoint's: these answer it as a server serving no locale, unless a
3030
* test says otherwise, and count only the localization requests.
3131
*/
3232
const isDiscovery = (url: unknown) => String(url).endsWith(DISCOVERY);
@@ -59,12 +59,13 @@ function Consumer() {
5959
beforeEach(() => {
6060
resetInflightGetsForTesting();
6161
localStorage.clear();
62-
__resetAppDefaultLocaleForTests();
62+
__resetPreferredLocaleForTests();
6363
clearSharedDiscoveryCache();
6464
});
6565

6666
afterEach(() => {
6767
vi.unstubAllGlobals();
68+
vi.restoreAllMocks();
6869
resetInflightGetsForTesting();
6970
localStorage.clear();
7071
});
@@ -101,14 +102,15 @@ describe('first-visit localization request budget', () => {
101102
expect(meCalls(fetchStub)).toBe(1);
102103
});
103104

104-
it("still ONE request when both state the app's declared default (objectstack#33231)", async () => {
105+
it('still ONE request when both state the supported browser language (objectstack#33985)', async () => {
105106
const gate = deferred<Response>();
106107
const fetchStub = vi.fn((url: string, _init?: RequestInit) =>
107108
isDiscovery(url)
108-
? Promise.resolve(jsonResponse({ locale: { default: 'zh-CN', supported: ['zh-CN'], timezone: 'UTC' } }))
109+
? Promise.resolve(jsonResponse({ locale: { default: 'en', supported: ['en', 'zh-CN'], timezone: 'UTC' } }))
109110
: gate.promise,
110111
);
111112
vi.stubGlobal('fetch', fetchStub);
113+
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zh-CN');
112114

113115
await seedTenantLanguage('', 1);
114116
await waitFor(() => expect(meCalls(fetchStub)).toBe(1));

‎ui/apps/console/src/languageSeed.test.ts‎

Lines changed: 96 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,15 @@ import {
1818
useObjectTranslation,
1919
} from '@object-ui/i18n';
2020
import { clearSharedDiscoveryCache } from '../../../packages/data-objectstack/src/sharedDiscovery';
21-
import { __resetAppDefaultLocaleForTests, seedTenantLanguage } from './languageSeed';
21+
import { __resetPreferredLocaleForTests, pickPreferredLocale, seedTenantLanguage } from './languageSeed';
2222

2323
const BASE = '';
2424
const TENANT_LOCALE = 'zh-CN';
2525
const DISCOVERY = '/api/v1/discovery';
2626

2727
/**
28-
* Discovery as a server that serves no `locale.default` (a 404): the browser
29-
* rung, which is what every test above the objectstack#33231 block exercises.
28+
* Discovery as a server that serves no `locale` block (a 404): the browser
29+
* rung, which is what every test above the objectstack#33985 block exercises.
3030
*/
3131
const noDiscovery = { ok: false, status: 404, json: async () => ({}) };
3232

@@ -62,7 +62,7 @@ function immediateFetch(body: unknown, ok = true) {
6262

6363
beforeEach(() => {
6464
window.localStorage.clear();
65-
__resetAppDefaultLocaleForTests();
65+
__resetPreferredLocaleForTests();
6666
clearSharedDiscoveryCache();
6767
});
6868

@@ -176,18 +176,26 @@ describe('seedTenantLanguage', () => {
176176
});
177177
});
178178

179-
describe("the app's declared default outranks the browser (objectstack#33231)", () => {
179+
describe('a supported browser language, else the app default (objectstack#33985)', () => {
180180
/**
181181
* A server that answers `/auth/me/localization` by its three rungs: the
182182
* user's own `sys_user.locale`, else the request's `Accept-Language`, else
183183
* the deployment default. A request that states no `Accept-Language` carries
184-
* the browser's own, which is what a bare `fetch` sends.
184+
* the browser's own, which is what a bare `fetch` sends. Discovery serves the
185+
* app's `locale.default` and `locale.supported` (the default alone when no
186+
* list is given).
185187
*/
186-
function fakeServer(opts: { appDefault?: string; userLocale?: string; browser: string }) {
188+
function fakeServer(opts: {
189+
appDefault?: string;
190+
supported?: string[];
191+
userLocale?: string;
192+
browser: string;
193+
}) {
187194
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
188195
if (String(url).endsWith(DISCOVERY)) {
189196
if (!opts.appDefault) return noDiscovery;
190-
const data = { locale: { default: opts.appDefault, supported: [opts.appDefault], timezone: 'UTC' } };
197+
const supported = opts.supported ?? [opts.appDefault];
198+
const data = { locale: { default: opts.appDefault, supported, timezone: 'UTC' } };
191199
return { ok: true, status: 200, json: async () => ({ success: true, data }) };
192200
}
193201
const stated = (init?.headers as Record<string, string> | undefined)?.['Accept-Language'];
@@ -199,6 +207,12 @@ describe("the app's declared default outranks the browser (objectstack#33231)",
199207
return fetchMock;
200208
}
201209

210+
/** The `Accept-Language` the boot's localization read stated, if any. */
211+
function statedLanguage(fetchMock: ReturnType<typeof fakeServer>): string | undefined {
212+
const meInit = fetchMock.mock.calls.find(([url]) => !String(url).endsWith(DISCOVERY))?.[1];
213+
return (meInit?.headers as Record<string, string> | undefined)?.['Accept-Language'];
214+
}
215+
202216
/** The console's first paint after the boot's seed: language, `<html lang>`, a label. */
203217
function Probe() {
204218
const { t, language } = useObjectTranslation();
@@ -218,37 +232,103 @@ describe("the app's declared default outranks the browser (objectstack#33231)",
218232
document.documentElement.lang = '';
219233
});
220234

221-
it('a user with no personal locale gets the declared zh-CN in an en-US browser', async () => {
222-
const fetchMock = fakeServer({ appDefault: 'zh-CN', browser: 'en-US' });
235+
it('a zh-CN browser on an app that ships zh-CN beside an en default gets zh-CN', async () => {
236+
const fetchMock = fakeServer({ appDefault: 'en', supported: ['en', 'zh-CN'], browser: 'zh-CN' });
223237

224238
const seen = await bootConsole();
225239

226240
expect(seen.text).toBe('zh-CN|取消');
227241
expect(seen.htmlLang).toBe('zh-CN');
242+
expect(statedLanguage(fetchMock)).toBe('zh-CN');
228243
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('zh-CN');
229244
// One discovery read, one localization read; nothing chosen on the device.
230245
expect(meCalls(fetchMock)).toBe(1);
231246
expect(window.localStorage.getItem(LOCALE_STORAGE_KEY)).toBeNull();
232247
});
233248

234-
it("a personal locale still outranks the app's declared default", async () => {
235-
fakeServer({ appDefault: 'zh-CN', userLocale: 'en', browser: 'zh-CN' });
249+
it('CONTROL: an fr browser on the same app gets the app default en', async () => {
250+
const fetchMock = fakeServer({ appDefault: 'en', supported: ['en', 'zh-CN'], browser: 'fr' });
236251

237252
const seen = await bootConsole();
238253

239254
expect(seen.text).toBe('en|Cancel');
240255
expect(seen.htmlLang).toBe('en');
256+
expect(statedLanguage(fetchMock)).toBe('en');
257+
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('en');
258+
});
259+
260+
it('a browser language the app does not ship gets the app default (en-US browser, zh-CN app)', async () => {
261+
const fetchMock = fakeServer({ appDefault: 'zh-CN', supported: ['zh-CN'], browser: 'en-US' });
262+
263+
const seen = await bootConsole();
264+
265+
expect(seen.text).toBe('zh-CN|取消');
266+
expect(seen.htmlLang).toBe('zh-CN');
267+
expect(statedLanguage(fetchMock)).toBe('zh-CN');
268+
expect(window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY)).toBe('zh-CN');
269+
});
270+
271+
it("an en-US browser on a zh-CN app that also ships en gets the app's en", async () => {
272+
const fetchMock = fakeServer({ appDefault: 'zh-CN', supported: ['zh-CN', 'en'], browser: 'en-US' });
273+
274+
const seen = await bootConsole();
275+
276+
expect(seen.text).toBe('en|Cancel');
277+
// The app's own spelling of the language it ships is what the server is asked for.
278+
expect(statedLanguage(fetchMock)).toBe('en');
279+
});
280+
281+
it("a personal locale still outranks the browser and the app's declared default", async () => {
282+
fakeServer({ appDefault: 'en', supported: ['en', 'zh-CN'], userLocale: 'ja', browser: 'zh-CN' });
283+
284+
const seen = await bootConsole();
285+
286+
expect(seen.text).toBe('ja|キャンセル');
287+
expect(seen.htmlLang).toBe('ja');
241288
});
242289

243-
it('with no default served, the browser language decides', async () => {
290+
it('with no locale block served, the browser language decides', async () => {
244291
const fetchMock = fakeServer({ browser: 'ja' });
245292

246293
const seen = await bootConsole();
247294

248295
expect(seen.text).toBe('ja|キャンセル');
249296
expect(seen.htmlLang).toBe('ja');
250-
// No default to state, so the request carried the browser's own header.
251-
const meInit = fetchMock.mock.calls.find(([url]) => !String(url).endsWith(DISCOVERY))?.[1];
252-
expect((meInit?.headers as Record<string, string>)['Accept-Language']).toBeUndefined();
297+
// Nothing to state, so the request carried the browser's own header.
298+
expect(statedLanguage(fetchMock)).toBeUndefined();
299+
});
300+
});
301+
302+
describe('pickPreferredLocale', () => {
303+
it('picks the browser language when the app lists it, in the app spelling', () => {
304+
expect(pickPreferredLocale('zh-CN', ['en', 'zh-CN'], 'en')).toBe('zh-CN');
305+
expect(pickPreferredLocale('zh-cn', ['en', 'zh-CN'], 'en')).toBe('zh-CN');
306+
});
307+
308+
it('matches a regional browser tag to the bare language the app ships', () => {
309+
expect(pickPreferredLocale('en-US', ['zh-CN', 'en'], 'zh-CN')).toBe('en');
310+
});
311+
312+
it("reads the browser tag through the platform table's aliases, as the server's rung does", () => {
313+
expect(pickPreferredLocale('ja', ['en', 'ja-JP'], 'en')).toBe('ja-JP');
314+
expect(pickPreferredLocale('zh-TW', ['en', 'zh-Hant'], 'en')).toBe('zh-Hant');
315+
expect(pickPreferredLocale('zh-HK', ['en', 'zh-Hant'], 'en')).toBe('zh-Hant');
316+
});
317+
318+
it('expands a browser language to a variant the app ships', () => {
319+
expect(pickPreferredLocale('es-MX', ['en', 'es-ES'], 'en')).toBe('es-ES');
320+
expect(pickPreferredLocale('pt', ['en', 'pt-BR'], 'en')).toBe('pt-BR');
321+
// The platform table reads a bare `zh` as Simplified, as the server answers that header.
322+
expect(pickPreferredLocale('zh', ['en', 'zh-CN', 'zh-TW'], 'en')).toBe('zh-CN');
323+
});
324+
325+
it('CONTROL: falls to the app default for an unsupported or absent browser language', () => {
326+
expect(pickPreferredLocale('fr', ['en', 'zh-CN'], 'en')).toBe('en');
327+
expect(pickPreferredLocale(undefined, ['en', 'zh-CN'], 'en')).toBe('en');
328+
expect(pickPreferredLocale('zh-CN', [], 'en')).toBe('en');
329+
});
330+
331+
it('answers nothing when neither matches nor a default is served', () => {
332+
expect(pickPreferredLocale('fr', ['en'], undefined)).toBeUndefined();
253333
});
254334
});

0 commit comments

Comments
 (0)