Skip to content

Commit 51992df

Browse files
fix(i18n): Studio edits the Traditional Chinese entry in a Traditional session and never overwrites the other script (#31089)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoKnw5nKcC7y1QqoHK4wxk2W)_ Fixes #31074 Clause-②: no Metadata-protocol: none Clause-② is `no`: `SupportedLocale` gains `'zh-Hant'`, but it lives in `@object-ui/app-shell`, which is private and exports only its root, which does not carry that type. `@object-ui/i18n` and `@objectstack/cli` change behaviour, not their exports. Metadata-protocol is `none`: what an author can write is unchanged. ## 维护者速读 - 改了什么:繁体中文(zh-Hant / zh-TW / zh-HK)会话进入 Studio 时,设计器语言不再一律按简体处理;导航设计器显示并修改的是侧边栏同样显示的繁体条目。只写了简体的标签,在繁体会话里修改时会新增一条繁体,不再覆盖简体原文。`os i18n check` 也把“繁体条目留空”算作缺翻译。 - 为什么改:之前繁体管理员在 Studio 看到简体名称,改名会覆盖简体作者写的文字,繁体用户看到的条目却不更新;留空的繁体条目还被报告为“已翻译”。 - 风险与回滚:只影响中文会话;简体会话、英文及其他语言的设计器行为与改前一致(有测试钉住)。Studio 的界面文字在繁体会话下沿用简体(studio 词库只有一份中文),这是有意的回退。回滚即还原本 PR。 - 先看:`ui/packages/app-shell/src/views/metadata-admin/i18n.ts` 的 `designerLocaleOf`;`ui/packages/i18n/src/pickLocalized.ts` 的 `localeWriteKey`(共用写入分支的脚本检查);`packages/cli/src/utils/i18n-coverage.ts` 的 `inlineLocaleText`。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/useMetadataLocale.sessionScript-31074.test.tsx packages/i18n/src/__tests__/setLocalized.test.ts`,预期全绿。 - 需要你做的:无,席位落地。 - **席位意见**:ui 席 2 对照 head `410d25d6` 的 diff 复核:15 个文件、+304 / −60,无受治理路径,不碰 `packages/spec/src`,不欠契约复审。Studio 设计器语言改为跟随会话书写:繁体会话(zh-Hant / zh-TW / zh-HK)按 `zh-Hant` 读写标签条目,界面文字仍用简体目录;写入侧遇到只有另一种书写的标签时新增本书写条目、不覆盖原文;CLI 覆盖率把渲染器实际显示的空条目算作缺口。现场三项读数与三组消融见正文。CI 全绿,同意落地。 ## What changes 1. **The designer locale follows the session script.** `useMetadataLocale` (`metadata-admin/i18n.ts`) no longer collapses every `zh*` to `'zh-CN'`. A new pure `designerLocaleOf(language)` resolves the session language through the console's own `resolveBuiltInLanguage`. A session the console serves in `zh-Hant` (`zh-Hant`, `zh-TW`, `zh-HK`, …) designs as `'zh-Hant'`, every other Chinese session designs as `'zh-CN'`, and anything else as `'en-US'`. `SupportedLocale` gains `'zh-Hant'`. 2. **An edit in a script the map lacks adds its own entry.** The shared write limb (`localeWriteKey` in `pickLocalized.ts`, behind `setLocalized` / `clearLocalized`) stops owning an entry of the other script. A `zh-Hant` edit over `{ en, zh }` or `{ en, 'zh-CN' }` adds `zh-Hant`, and a clear there removes nothing. The same holds the other way round. Where the table does not name a script subtag (`zh-Hant-US`), the limb does not assume it is the editor's own. The read side is unchanged. `navItemLabel`'s `renamedLabel` / `clearedLabel` now go through `setLocalized` / `clearLocalized` instead of asking `resolveI18nLabel` for the owned key, so they inherit the rule. Their own "sibling-only map ⇒ add the exact tag" rule (objectui#11196) is kept in `ownsAnEntry`. 3. **CLI coverage.** `inlineLocaleText` judges an empty entry after the shared resolver picks, not before. A blank entry the renderer shows is a gap: `{ 'zh-CN': '成员', 'zh-TW': '' }` at `zh-Hant`, and `{ zh: '成员', 'zh-CN': '' }` at `zh-CN`. Server seat: no objection (#30985, 6702009928). ### Studio surfaces that read the designer locale - **Chrome (falls back to Simplified).** Of the 66 non-test files that call `useMetadataLocale`, and the components that take its value as a prop, almost all use it for chrome only (`t()` / `tFormat()` / `tOptional()` → `studioString`). The `studio` namespace ships one Chinese catalogue (`zh`), and `resolveStudioLanguage('zh-Hant')` serves it, so a Traditional designer reads Simplified chrome and never English. No Traditional strings were invented. Three chrome sites compared `=== 'zh-CN'` and would have dropped to English, so they now use `isZhLocale`: `PositionHoldersSection.tsx:110`, `AssignedUsersSection.tsx:132` and `ResourceEditPage.tsx:3059`. - **Label entries (follow the session script, no edit).** These pass the same locale to `pickLocalized`, `resolveI18nLabel`, `navItemLabelText` or `renamedLabel` / `clearedLabel`: `StudioNavItemInspector`, `AppNavInspector`, `AppNavCanvas`, `InterfacesNavRail`, `SourcePageProperties`, `StudioDesignSurface`, `ObjectActionsPanel`, `ObjectListViewInspector` / `ObjectListViewTitle`, `ListViewBulkActionsSection`, `AutomationsFlowRail`, `metadataError`, `packageSurfaces`, `useDatasetCatalog`, `AppPreview`, `DashboardPreview`, `ViewPreview`, `DashboardDefaultInspector`, `DashboardWidgetInspector` and `ReportDefaultInspector`. - **Not the designer locale.** `translationTable.ts` and `doc-draft.ts` key by the translation or doc language the author picks, so they are untouched. ### Re-pinned #31068 controls These pinned the cross-script overwrite as "unchanged" and now pin the added entry: - `setLocalized.test.ts` UNCHANGED: `{ en, 'zh-CN' }` @ `zh-Hant` → `zh-CN`; `{ en, zh }` @ `zh-TW` → `zh`; `{ en, 'zh-HK' }` @ `zh-Hans` → `zh-HK`. All three moved to the #31074 block, where they now add their own tag. - `navItemLabel.inherit-11196.test.ts` UNCHANGED: `{ en, zh }` renamed in `zh-Hant` → `{ en, zh: 'RENAMED' }`. Moved to the #31074 block, where it now adds `zh-Hant`. - `i18n-inline-locale-map-coverage.test.ts`: `{ 'zh-CN': '成员', 'zh-TW': '' }` @ `zh-Hant` was `'成员'` (covered) and is now a gap. - `BuilderLanding.environmentOverlayCopy-12171.test.ts` `DECLARED_LOCALES` lists `'zh-Hant'`. Its `satisfies Record<SupportedLocale, true>` exists to fail the type-check until a new locale is listed. The spec twin is untouched. The `packages/spec` test's verbatim copy of `pickLocalized` covers `splitScriptTagOf`, `localizedEntryKey` and `pickLocalized`, and none of them changed: only `localeWriteKey` did. Its provenance pin still names the revision the copy matches. ## Tests Head `410d25d60c`. <details><summary>Live readings (console from this tree, showcase backend)</summary> Setup: `examples/app-showcase` with two top-level nav labels set locally, `nav_capability_map` = `{ en: 'Proj EN', zh: '简体项目', 'zh-TW': '繁體專案' }` and `nav_start_here` = `{ en: 'Tasks EN', zh: '简体任务' }`. Their `apps.showcase_app.navigation.<id>.label` bundle rows were dropped, because a bundle row wins over the map. These edits were local only and are reverted. Console: `ui/apps/console` vite with `objectui-locale = zh-Hant`, logged in as admin, Studio → Interfaces. 1. The nav designer lists the first item as **繁體專案**, not 简体项目, in both the rail and edit mode. On `main` it listed 简体项目 (measured on PR #31068's head, #31074 body). 2. An inline rename of 繁體專案 to 改名繁體 autosaved `PUT /api/v1/meta/app/showcase_app?mode=draft&package=com.example.showcase.custom` with `label: { en: 'Proj EN', zh: '简体项目', 'zh-TW': '改名繁體' }`, so `zh-TW` was updated and `zh` left untouched. 3. Renaming 简体任务 to 新增繁體 sent `label: { en: 'Tasks EN', zh: '简体任务', 'zh-Hant': '新增繁體' }`: `zh-Hant` was added and the Simplified text kept. The inspector's Label field then read 新增繁體. Studio chrome in that session is Simplified (界面 / 权限 / 属性), which is the namespace fallback described above. </details> <details><summary>Suites</summary> - `pnpm --dir ui exec vitest run packages/i18n/src/__tests__ packages/app-shell/src/views/metadata-admin/previews packages/app-shell/src/views/metadata-admin/useMetadataLocale.sessionScript-31074.test.tsx`: all pass. - `pnpm --dir ui exec vitest run packages/app-shell/src/views/studio-design/BuilderLanding.environmentOverlayCopy-12171.test.ts`: 4 pass. - `packages/cli`: `vitest run test/i18n-inline-locale-map-coverage.test.ts` 17 pass. - Type-checks: `@object-ui/app-shell type-check`, `@object-ui/i18n type-check` and `@objectstack/cli typecheck` (with `NODE_OPTIONS=--max-old-space-size=6144`, because the 4096 run OOMed in `check:test-typecheck`) all exit 0. - `eslint` on every changed ui file: 0 errors. </details> <details><summary>Ablations (committed first, mutated, restored)</summary> - Designer locale (`designerLocaleOf` → always `'zh-CN'` for Chinese): 5 red in `useMetadataLocale.sessionScript-31074.test.tsx`, all of them the zh-Hant / zh-TW / zh-HK rows and both rename rows. 0 controls red. - Write limb (`localeWriteKey` → `return key`, which is the #31068 behaviour): 16 red across `setLocalized`, `clearLocalized`, `navItemLabel` and the designer pin, all of them new #31074 pins. 0 controls red. - CLI (`i18n-coverage.ts` at `main`): 2 red, the new empty-entry case and the parity sweep over the two new maps. </details> <details><summary>Derived gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` on `410d25d60c` derives 66 families, and all 66 exit 0. `--ran` reconciles them as 66 accounted and 0 NOT-MEASURED. One family needed a rerun: `pnpm --dir ui exec vitest run scripts/` first exited 1 on a 15 s timeout in `dollar-dialect-alias-census.test.ts` while the live console was running on the same box. A container restart then cut the sweep short. The resumed sweep reran every family that had not yet recorded exit 0, and that one passed. `node scripts/check-sdui-manifest.mjs` is in the derived set and exits 0. </details> ## Acceptance notes - Studio chrome stays Simplified in a Traditional session. The `studio` namespace has one Chinese catalogue, and inventing Traditional strings is out of scope. Only the label entries an author reads and edits follow the script. - Reading is unchanged: a `zh-Hant` reader of `{ en, zh }` still sees the `zh` text until a Traditional entry exists, and the first edit adds one. - `navItemLabel`'s "sibling-only map ⇒ add the exact tag" rule (objectui#11196) is unchanged. For example, `{ en, 'zh-TW' }` renamed in `zh-Hant` adds `zh-Hant`, as before. <!-- signed: domain:ui#2 · os-tesla · session_01L9qibw7DekEe3wx5f3zphf --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4123865 commit 51992df

15 files changed

Lines changed: 304 additions & 60 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
fix(cli): i18n coverage reports a blank inline-label entry the renderer shows as a gap
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
An inline locale map with an empty entry that the renderer reaches for a locale no longer counts that locale as translated. `{ 'zh-CN': '成员', 'zh-TW': '' }` was reported covered for `zh-Hant` by the Simplified text, while the console shows the blank Traditional entry; it is now a `missing translation` finding, as an empty bundle value already is. Readers that never reach the blank entry are covered as before.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/i18n': patch
3+
---
4+
5+
fix(i18n): an edit in a Chinese script the label lacks adds its own entry instead of overwriting the other script
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`setLocalized` and `clearLocalized` no longer treat the other Chinese script's entry as the editor's own. A `zh-Hant` (or `zh-TW`, `zh-HK`) edit of a label written as `{ en: 'Customer', zh: '客户' }` now adds a `zh-Hant` entry and keeps the Simplified text; before, it overwrote `zh` with Traditional text. A clear in that case removes nothing, because the box was showing the other script's text as a fallback. A Simplified editor over a Traditional-only map is handled the same way. Reading is unchanged: `pickLocalized` still shows the other script's entry until one of the reader's own script exists. Every other language, and every map that has an entry of the editor's script, writes exactly as before.

‎packages/cli/src/utils/i18n-coverage.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -545,27 +545,28 @@ function collectExpectedKeys(config: any): ExpectedKey[] {
545545
*
546546
* Empty values do not count, matching {@link lookupKey}'s rule on the bundle
547547
* side — an empty translation is not a translation, whichever side it is
548-
* written on.
548+
* written on. They are judged AFTER the resolver has picked, not before: the
549+
* renderer shows an empty entry when it is the one its limbs reach, so a blank
550+
* `zh-TW` beside `zh-CN` leaves a `zh-Hant` reader looking at nothing, and a
551+
* blank exact `zh-CN` beside `zh` leaves a `zh-CN` reader the same. Dropping
552+
* empties first would let the other entry stand in and report that reader
553+
* covered (#31074).
549554
*/
550555
export function inlineLocaleText(
551556
map: Readonly<Record<string, string>> | undefined,
552557
locale: string,
553558
): string | undefined {
554559
if (!map) return undefined;
555-
const read = (tag: string): string | undefined => {
556-
if (!Object.prototype.hasOwnProperty.call(map, tag)) return undefined;
557-
const value = map[tag];
558-
return typeof value === 'string' && value.length > 0 ? value : undefined;
559-
};
560560
const tag = (locale || 'en').trim();
561561
const base = tag.split('-')[0];
562562
const sameLanguage: Record<string, string> = {};
563563
for (const key of Object.keys(map)) {
564-
const value = read(key);
565-
if (value !== undefined && key.split('-')[0] === base) sameLanguage[key] = value;
564+
const value = map[key];
565+
if (typeof value === 'string' && key.split('-')[0] === base) sameLanguage[key] = value;
566566
}
567567
if (Object.keys(sameLanguage).length === 0) return undefined;
568-
return resolveI18nLabel(sameLanguage, tag);
568+
const shown = resolveI18nLabel(sameLanguage, tag);
569+
return shown !== undefined && shown.length > 0 ? shown : undefined;
569570
}
570571

571572
/**

‎packages/cli/test/i18n-inline-locale-map-coverage.test.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,9 @@ describe('coverage reads the map the way the renderer does', () => {
277277
{ en: 'Members', 'zh-CN': '成员', 'zh-TW': '成員' },
278278
{ en: 'Members', 'zh-TW': '成員', 'zh-CN': '成员' },
279279
{ en: 'Members', zh: '成员', 'zh-Hant': '成員' },
280+
// An empty entry the renderer reaches (#31074): that reader sees nothing.
281+
{ en: 'Members', 'zh-CN': '成员', 'zh-TW': '' },
282+
{ en: 'Members', zh: '成员', 'zh-CN': '' },
280283
];
281284
const locales = ['en', 'zh', 'zh-CN', 'zh-TW', 'zh-Hans', 'zh-Hant', 'zh-HK', 'ja-JP', 'es-ES'];
282285

@@ -309,7 +312,21 @@ describe('coverage reads the map the way the renderer does', () => {
309312
it("a map with both Chinese scripts covers each reader with its own script's entry (#30910)", () => {
310313
expect(inlineLocaleText({ 'zh-CN': '成员', 'zh-TW': '成員' }, 'zh-Hant')).toBe('成員');
311314
expect(inlineLocaleText({ 'zh-TW': '成員', 'zh-CN': '成员' }, 'zh')).toBe('成员');
312-
// An empty entry of the reader's script is no translation: the other script still covers.
313-
expect(inlineLocaleText({ 'zh-CN': '成员', 'zh-TW': '' }, 'zh-Hant')).toBe('成员');
315+
// (The row that pinned an empty `zh-TW` as covered by `zh-CN` at `zh-Hant`
316+
// moved to the #31074 case below: the renderer shows the empty entry.)
317+
});
318+
319+
it('an empty entry the renderer shows is a gap, not covered by another entry (#31074)', () => {
320+
// Own script: the reader of the Traditional script sees the blank `zh-TW`.
321+
expect(resolveI18nLabel({ 'zh-CN': '成员', 'zh-TW': '' }, 'zh-Hant')).toBe('');
322+
expect(inlineLocaleText({ 'zh-CN': '成员', 'zh-TW': '' }, 'zh-Hant')).toBeUndefined();
323+
expect(inlineLocaleText({ 'zh-CN': '成员', 'zh-TW': '' }, 'zh-HK')).toBeUndefined();
324+
// Own tag: an exact blank `zh-CN` shadows the bare `zh`.
325+
expect(resolveI18nLabel({ zh: '成员', 'zh-CN': '' }, 'zh-CN')).toBe('');
326+
expect(inlineLocaleText({ zh: '成员', 'zh-CN': '' }, 'zh-CN')).toBeUndefined();
327+
// CONTROL: the readers that never reach the blank entry stay covered.
328+
expect(inlineLocaleText({ 'zh-CN': '成员', 'zh-TW': '' }, 'zh-Hans')).toBe('成员');
329+
expect(inlineLocaleText({ zh: '成员', 'zh-CN': '' }, 'zh')).toBe('成员');
330+
expect(inlineLocaleText({ 'zh-CN': '成员' }, 'zh-TW')).toBe('成员');
314331
});
315332
});

‎ui/packages/app-shell/src/views/metadata-admin/AssignedUsersSection.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import { usePermissions } from '@object-ui/permissions';
8686
import { extractWriteErrorMessage, useAdapter, useMetadata } from '@object-ui/react';
8787
import { Plus, X, Users, Loader2, AlertCircle } from 'lucide-react';
8888
import { useMetadataLocale } from './i18n.js';
89+
import { isZhLocale } from './schema-field-label.js';
8990
import { membershipOrganization, readOrganizationMemberIds, type MemberFilter } from './organization-members.js';
9091

9192
/** The object a permission set's direct grants are rows of: ADD creates one, REMOVE deletes one. */
@@ -129,7 +130,7 @@ interface AssignedRow {
129130
* them: a space in English, none after a CJK full stop.
130131
*/
131132
function useCopy() {
132-
const zh = useMetadataLocale() === 'zh-CN';
133+
const zh = isZhLocale(useMetadataLocale());
133134
return React.useMemo(
134135
() =>
135136
zh

‎ui/packages/app-shell/src/views/metadata-admin/PositionHoldersSection.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ import { usePermissions } from '@object-ui/permissions';
6161
import { extractWriteErrorMessage, useAdapter, useMetadata } from '@object-ui/react';
6262
import { AlertCircle, Loader2, Plus, UserCheck, X } from 'lucide-react';
6363
import { useMetadataLocale } from './i18n.js';
64+
import { isZhLocale } from './schema-field-label.js';
6465
import { membershipOrganization, readOrganizationMemberIds, type MemberFilter } from './organization-members.js';
6566

6667
export interface PositionHoldersSectionProps {
@@ -107,7 +108,7 @@ const PICKER_EMAIL_FIELD = 'email';
107108
const refusalSentence = (err: unknown): string => extractWriteErrorMessage(err) ?? '';
108109

109110
function useCopy() {
110-
const zh = useMetadataLocale() === 'zh-CN';
111+
const zh = isZhLocale(useMetadataLocale());
111112
return React.useMemo(
112113
() =>
113114
zh

‎ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ import { useRegisterAssistantEditor, type AssistantEditorContext } from '../../a
147147
import { useRegisteredMetadataInspector } from './inspector-registry.js';
148148
import { useRegisteredMetadataDefaultInspector } from './default-inspector-registry.js';
149149
import { InspectorReadOnlyReason } from './inspectors/_shared.js';
150-
import { useMetadataLocale, t, tFormat, translateMetadataType, translateSchemaIssue, translateValidationMessage } from './i18n.js';
150+
import { isZhLocale, useMetadataLocale, t, tFormat, translateMetadataType, translateSchemaIssue, translateValidationMessage } from './i18n.js';
151151
import { JsonSourceEditor } from '../item-tools/JsonSourceEditor.js';
152152
import { validateMetadataDraft, hasClientValidator, type DraftMode } from './clientValidation.js';
153153
import {
@@ -3056,7 +3056,7 @@ function MetadataResourceEditPageImpl({
30563056
rel="noopener noreferrer"
30573057
className="mt-1 inline-flex items-center gap-1 text-amber-800 underline hover:text-amber-900 dark:text-amber-200 dark:hover:text-amber-100"
30583058
>
3059-
{locale === 'zh-CN' ? '查看文档' : 'View docs'} →
3059+
{isZhLocale(locale) ? '查看文档' : 'View docs'} →
30603060
</a>
30613061
)}
30623062
{layered?.packageId && (

‎ui/packages/app-shell/src/views/metadata-admin/i18n.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@
5858
* `ui/scripts/__tests__/check-i18n-dead-keys.test.ts`.
5959
*/
6060

61-
import { useObjectTranslation } from '@object-ui/i18n';
61+
import { resolveBuiltInLanguage, useObjectTranslation } from '@object-ui/i18n';
6262
// The designer strings' new home. Its `en` catalogue is resident; its other
6363
// catalogues are fetched on demand, and `useMetadataLocale()` re-renders its
6464
// caller when one lands. ⚠️ `ui/scripts/check-i18n-dead-keys.mjs` reads the
@@ -74,7 +74,15 @@ import type {
7474
MetadataOverlayScope,
7575
} from '@object-ui/data-objectstack';
7676

77-
export type SupportedLocale = 'en-US' | 'zh-CN';
77+
/**
78+
* The designer locale. `'zh-Hant'` is a Traditional Chinese session: Studio
79+
* reads and writes the Traditional entry of an inline label in it, and its
80+
* chrome strings fall back to the namespace's `zh` (Simplified) catalogue,
81+
* which is the only Chinese one it ships (`resolveStudioLanguage`). Compare a
82+
* value with `isZhLocale`, never `=== 'zh-CN'`, when the question is "Chinese
83+
* chrome?".
84+
*/
85+
export type SupportedLocale = 'en-US' | 'zh-CN' | 'zh-Hant';
7886

7987
const TYPE_LABELS_EN: Record<string, string> = {
8088
// Data
@@ -931,9 +939,23 @@ export function detectLocale(): SupportedLocale {
931939
return 'en-US';
932940
}
933941

942+
/**
943+
* The designer locale for an i18n `language` — {@link useMetadataLocale}'s
944+
* answer, as a pure function.
945+
*/
946+
export function designerLocaleOf(language: string | undefined): SupportedLocale {
947+
if (!/^zh/i.test(language ?? '')) return 'en-US';
948+
return resolveBuiltInLanguage(language ?? '') === 'zh-Hant' ? 'zh-Hant' : 'zh-CN';
949+
}
950+
934951
/**
935952
* React hook — the Studio/metadata-admin locale derived from the app's ACTIVE
936-
* i18n language, collapsed to one of the two locales this catalog ships.
953+
* i18n language: `'zh-Hant'` for a session the console serves in Traditional
954+
* Chinese (`zh-Hant`, `zh-TW`, `zh-HK`, … through `resolveBuiltInLanguage`,
955+
* the console's own resolution), `'zh-CN'` for every other Chinese session,
956+
* `'en-US'` otherwise. The Traditional value exists for the label entries an
957+
* author reads and edits (the nav designer shows and renames the entry the
958+
* sidebar shows); its chrome strings are the Simplified ones.
937959
*
938960
* Prefer this over {@link detectLocale} in components: `detectLocale()` reads
939961
* `navigator.language`, which never changes when the user switches languages
@@ -944,15 +966,15 @@ export function detectLocale(): SupportedLocale {
944966
*
945967
* ⛔ Never hand this value to `Intl` (`Intl.*Format`, `toLocale*String`) as the
946968
* locale a date, time or number is formatted in. It picks one of this file's
947-
* TWO string tables, so it is `'en-US'` for every language that is not zh — a
969+
* string tables, so it is `'en-US'` for every language that is not zh — a
948970
* de-DE session would read its faces in US English (objectui#10232). Faces
949971
* format with `useDisplayLocale()` from `@object-ui/i18n`, the channel every
950972
* date and number renderer resolves through; keep this value for `t()` /
951973
* `tFormat()` and the other lookups into the tables here.
952974
*/
953975
export function useMetadataLocale(): SupportedLocale {
954976
const { language } = useObjectTranslation();
955-
const locale: SupportedLocale = /^zh/i.test(language) ? 'zh-CN' : 'en-US';
977+
const locale = designerLocaleOf(language);
956978
// Starts the fetch of the `studio` namespace catalogue this locale reads and
957979
// re-renders the caller when it lands, so a moved key does not stay on the
958980
// `en` answer the first render gave.

‎ui/packages/app-shell/src/views/metadata-admin/previews/navItemLabel.inherit-11196.test.ts‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,8 @@ describe('#30910 — renamedLabel and clearedLabel change the entry the resolver
195195
// Neither the exact tag nor the bare language: the exact tag is added, a sibling region is not owned.
196196
[{ en: 'Customer', 'zh-CN': '客户', 'zh-TW': '客戶' }, 'zh-Hant', { en: 'Customer', 'zh-CN': '客户', 'zh-TW': '客戶', 'zh-Hant': 'RENAMED' }],
197197
[{ en: 'Customer', 'zh-TW': '客戶' }, 'zh-Hant', { en: 'Customer', 'zh-TW': '客戶', 'zh-Hant': 'RENAMED' }],
198-
// The bare language with no sibling of the locale's script: the bare language, as before.
199-
[{ en: 'Customer', zh: '客户' }, 'zh-Hant', { en: 'Customer', zh: 'RENAMED' }],
198+
// The bare language of the locale's own script: the bare language, as before.
199+
// (`{ en, zh }` renamed in `zh-Hant`, which wrote `zh` here, moved to the #31074 block.)
200200
[{ en: 'Customer', zh: '客户', 'zh-TW': '客戶' }, 'zh-CN', { en: 'Customer', zh: 'RENAMED', 'zh-TW': '客戶' }],
201201
// Languages the table names once.
202202
[{ en: 'Accounts', 'en-GB': 'Accounts (GB)' }, 'en-US', { en: 'RENAMED', 'en-GB': 'Accounts (GB)' }],
@@ -207,3 +207,29 @@ describe('#30910 — renamedLabel and clearedLabel change the entry the resolver
207207
expect(renamedLabel(map as I18nLabel, 'RENAMED', locale)).toEqual(expected);
208208
});
209209
});
210+
211+
/**
212+
* #31074 — a rename in a script the map lacks adds the locale's own entry
213+
* (the shared write limb, `setLocalized`), and a clear there removes nothing:
214+
* a Traditional designer over `{ en, zh }` used to overwrite the Simplified
215+
* text. The entry is shown in the other script until then, as the sidebar
216+
* shows it.
217+
*/
218+
describe('#31074 — a rename in a script the map lacks adds its own entry', () => {
219+
const CROSS: ReadonlyArray<readonly [Record<string, string>, string]> = [
220+
[{ en: 'Customer', zh: '客户' }, 'zh-Hant'],
221+
[{ en: 'Customer', 'zh-CN': '客户' }, 'zh-Hant'],
222+
[{ en: 'Customer', zh: '客户' }, 'zh-TW'],
223+
[{ en: 'Customer', 'zh-Hant': '客戶' }, 'zh-CN'],
224+
];
225+
226+
it.each(CROSS)('%j renamed in %s adds that tag, keeps the other script, and shows the new text', (map, locale) => {
227+
const next = renamedLabel(map as I18nLabel, 'RENAMED', locale) as Record<string, string>;
228+
expect(next).toEqual({ ...map, [locale]: 'RENAMED' });
229+
expect(navItemLabelText(next as I18nLabel, locale)).toBe('RENAMED');
230+
});
231+
232+
it.each(CROSS)('%j cleared in %s removes nothing', (map, locale) => {
233+
expect(clearedLabel(map as I18nLabel, locale)).toEqual(map);
234+
});
235+
});

‎ui/packages/app-shell/src/views/metadata-admin/previews/navItemLabel.ts‎

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
*/
2727

2828
import { resolveI18nLabel, type I18nLabel } from '@objectstack/spec/ui';
29+
import { clearLocalized, setLocalized } from '@object-ui/i18n';
2930
import { resolveNavItemLabel, type NavTargetLabelResolver } from '@object-ui/layout';
3031
import type { NavigationItem } from '@object-ui/types';
3132

@@ -116,16 +117,19 @@ export function navEntryLabelText(
116117
* `{ zh, 'zh-TW' }`, because bare `zh` means `zh-Hans`) — so the editor shows
117118
* the new text straight after the edit. A map with none of these gains an
118119
* entry under the exact tag; an entry the resolver only reached as another
119-
* language's fallback (`default`, `en` under `zh-CN`, a sibling region) is left
120-
* as it was. Because the new entry is under the exact
120+
* language's fallback (`default`, `en` under `zh-CN`, a sibling region, or the
121+
* other Chinese script's entry: `zh` under `zh-Hant`) is left as it was. The
122+
* entry is chosen by the shared write limb (`setLocalized`, see
123+
* {@link ownsAnEntry}). Because the new entry is under the exact
121124
* tag, the next edit finds it first: an editor that writes on every keystroke
122125
* adds that entry once, never one per keystroke.
123126
*/
124127
export function renamedLabel(cur: I18nLabel | undefined, next: string, locale: string): I18nLabel {
125128
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return next;
126129
const map: Record<string, string> = cur;
127-
const key = ownEntryKey(map, locale) ?? locale.trim();
128-
return { ...map, [key]: next };
130+
const tag = locale.trim();
131+
if (!ownsAnEntry(map, tag)) return { ...map, [tag]: next };
132+
return setLocalized(map, tag, next) as Record<string, string>;
129133
}
130134

131135
/**
@@ -142,37 +146,27 @@ export function renamedLabel(cur: I18nLabel | undefined, next: string, locale: s
142146
*/
143147
export function clearedLabel(cur: I18nLabel | undefined, locale: string): I18nLabel | undefined {
144148
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return undefined;
145-
const map: Record<string, string> = { ...cur };
146-
const key = ownEntryKey(map, locale);
147-
if (key !== undefined) delete map[key];
148-
return Object.values(map).some((v) => typeof v === 'string') ? map : undefined;
149+
const tag = locale.trim();
150+
const map = ownsAnEntry(cur, tag) ? clearLocalized(cur, tag) : cur;
151+
return map !== undefined && Object.values(map).some((v) => typeof v === 'string')
152+
? (map as Record<string, string>)
153+
: undefined;
149154
}
150155

151156
/**
152-
* The map entry an edit in `locale` owns: the exact tag, else the entry
153-
* `resolveI18nLabel` reads in place of the bare language, else the bare
154-
* language; `undefined` when the map has neither the tag nor the language.
155-
*
156-
* Which entry the resolver reads is asked of the resolver itself, over a map
157-
* of each usable key to its own name, so this module keeps no copy of the
158-
* resolver's limbs. With the bare language present the resolver reads it,
159-
* unless it prefers a sibling of the locale's own script (`zh-TW` under
160-
* `zh-Hant`, where bare `zh` means `zh-Hans`); then the sibling is the entry
161-
* on screen and the one an edit owns. A sibling the resolver reaches only
162-
* because the bare language is ABSENT stays another region's fallback, as
163-
* before: the edit adds the exact tag.
157+
* Whether an edit in `tag` owns an entry of `map` at all: the exact tag or the
158+
* bare language is present. Which entry it then owns is the shared write limb's
159+
* answer (`setLocalized` / `clearLocalized` in `@object-ui/i18n`), the entry
160+
* the resolver shows: the exact tag, else the bare language, else, where the
161+
* resolver prefers it, a sibling of the locale's own script (`zh-TW` under
162+
* `zh-Hant` in `{ zh, 'zh-TW' }`). Where the platform table splits the language
163+
* by script, an entry of the OTHER script is never owned: a `zh-Hant` edit over
164+
* `{ en, zh }` adds `zh-Hant` and keeps the Simplified text. A sibling the
165+
* resolver reaches only because the bare language is ABSENT stays another
166+
* region's fallback, as before: the edit adds the exact tag. So this module
167+
* keeps no copy of either side's limbs.
164168
*/
165-
function ownEntryKey(map: Record<string, string>, locale: string): string | undefined {
166-
const tag = locale.trim();
169+
function ownsAnEntry(map: Record<string, string>, tag: string): boolean {
167170
const own = (key: string) => Object.prototype.hasOwnProperty.call(map, key) && typeof map[key] === 'string';
168-
if (own(tag)) return tag;
169-
const base = tag.split('-')[0];
170-
if (!own(base)) return undefined;
171-
const keyOfEachEntry: Record<string, string> = Object.fromEntries(
172-
Object.keys(map)
173-
.filter(own)
174-
.map((key) => [key, key]),
175-
);
176-
const read = resolveI18nLabel(keyOfEachEntry, locale);
177-
return read !== undefined && read !== base && read.split('-')[0] === base ? read : base;
171+
return own(tag) || own(tag.split('-')[0]);
178172
}

0 commit comments

Comments
 (0)