diff --git a/.changeset/36504-menu-rename-translation.md b/.changeset/36504-menu-rename-translation.md new file mode 100644 index 00000000000..be031cdde88 --- /dev/null +++ b/.changeset/36504-menu-rename-translation.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(i18n): `GET /i18n/locales` names the source locale, and a design-mode menu rename outside it is stored as that language's translation + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-i18n/SKILL.md + +- **`GET /api/v1/i18n/locales` names the source locale.** The body gains an optional `sourceLocale` (`GetLocalesResponseSchema.sourceLocale`): the language the app's own text, a plain-string `label`, is written in. It is the declared `i18n.sourceLocale`, else the default locale, the same rule the metadata translators use. It differs from the `isDefault` locale on an app written in one language that defaults its users to another. It is absent only when the server knows neither. Nothing that parsed before stops parsing. +- **A menu rename in design mode is stored where the reader's language reads it.** The name field of 「Rename and icon」 is now open in every language. A name typed in the source language, over an entry shown by its stored label, is still written to the stored label. Any other name is written as that language's translation of the entry: a name typed in another language, or one typed in the source language over a translation the reader was shown. The stored label stays unchanged, so every other language keeps its name. The rename says so when the new name will be a translation ("The new name is shown in LANGUAGE. The app's other languages keep their names."). +- **Where the translation goes.** It is written to the `translation` item `APP_menu_LOCALE` (for example `crm_menu_zh_cn`), at `apps.APP.navigation.ID.label`, the key app navigation is translated by. It goes into the package the menu is written to: the app's own package when that is writable, else its customization package, whose own translations are read first (ADR-0146 D2). Like the menu, it is saved as a draft with the first-write pin and published at once. A pending draft of it is refused and the reason is shown. A translation-only rename writes the translation and leaves the app alone. +- **A link added in another language** is stored without a name, and the name typed for it becomes that language's translation. The source language names it when someone sets a name there. Until then, a reader in the source language sees the link's URL, as for any link with no label. +- Before this change, the console allowed a rename only when the reader was in the deployment's default language. The default language could differ from the source language, and a rename there was written to the stored label for every language. diff --git a/content/docs/api/plugin-endpoints.mdx b/content/docs/api/plugin-endpoints.mdx index 6047198bcee..573281d6046 100644 --- a/content/docs/api/plugin-endpoints.mdx +++ b/content/docs/api/plugin-endpoints.mdx @@ -139,7 +139,7 @@ protocol `ai.chatStream` parses and owns message state for you. | Method | Endpoint | Description | |:-------|:---------|:------------| -| GET | `/i18n/locales` | List available locales | +| GET | `/i18n/locales` | List available locales, and the source locale (`sourceLocale`) | | GET | `/i18n/translations/:locale` | Get translation bundle | | GET | `/i18n/labels/:object/:locale` | Get field labels | diff --git a/content/docs/kernel/services-checklist.mdx b/content/docs/kernel/services-checklist.mdx index ad94c614c60..473b7babb0f 100644 --- a/content/docs/kernel/services-checklist.mdx +++ b/content/docs/kernel/services-checklist.mdx @@ -508,7 +508,7 @@ declares no `i18n` block must not clear what another declared. | Method | Path | Description | |:-------|:-----|:------------| -| `GET` | `/api/v1/i18n/locales` | List available locales | +| `GET` | `/api/v1/i18n/locales` | List available locales (`isDefault` marks the default one) and name the source locale (`sourceLocale`: the declared `i18n.sourceLocale`, else the default locale) | | `GET` | `/api/v1/i18n/translations/:locale` | Get all translations for a locale | | `GET` | `/api/v1/i18n/labels/:object/:locale` | Get translated field labels for an object | diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index fc5064c4861..271f8b49380 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1378,6 +1378,7 @@ This schema accepts one of the following structures: | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **locales** | `{ code: string; label: string; isDefault?: boolean }[]` | ✅ | Available locales | +| **sourceLocale** | `string` | optional | The language the app's own text (a plain-string `label`) is written in: the declared `i18n.sourceLocale`, else the default locale. Absent when the server knows neither. Text typed in any other locale is a translation | ### Nested Shape: `GetLocalesResponse.locales[number]` diff --git a/packages/runtime/src/domains/i18n-anonymous-deny.test.ts b/packages/runtime/src/domains/i18n-anonymous-deny.test.ts index f3ffaeab324..2183b208c0d 100644 --- a/packages/runtime/src/domains/i18n-anonymous-deny.test.ts +++ b/packages/runtime/src/domains/i18n-anonymous-deny.test.ts @@ -94,7 +94,8 @@ const FACES: readonly Face[] = [ { face: 'the locale list', subPath: '/locales', - served: { locales: [{ code: 'en', label: 'en', isDefault: true }, { code: 'fr', label: 'fr', isDefault: false }] }, + // The source locale is the default one here: the provider declares no `sourceLocale` (#36504). + served: { locales: [{ code: 'en', label: 'en', isDefault: true }, { code: 'fr', label: 'fr', isDefault: false }], sourceLocale: 'en' }, reads: 'getLocales', }, { diff --git a/packages/runtime/src/domains/i18n.ts b/packages/runtime/src/domains/i18n.ts index 3154a44df51..6b3a6cbfd01 100644 --- a/packages/runtime/src/domains/i18n.ts +++ b/packages/runtime/src/domains/i18n.ts @@ -9,7 +9,7 @@ * dispatcher-owned (moving it into one provider would 404 the other). * * Routes (path is the sub-path after `/i18n`): - * GET /locales → getLocales + * GET /locales → getLocales (+ the source locale) * GET /translations/:locale → getTranslations (locale from path) * GET /translations?locale=xx → getTranslations (locale from query) * GET /labels/:object/:locale → getFieldLabels (both from path) @@ -237,11 +237,17 @@ export async function handleI18nRequest( // array through made one endpoint answer in two shapes depending on // which provider mounted it, the dispatcher's contradicting the SDK's // own `GetLocalesResponse` type. - const locales = toLocaleDescriptors( - i18nService.getLocales(), - typeof i18nService.getDefaultLocale === 'function' ? i18nService.getDefaultLocale() : undefined, - ); - return { handled: true, response: deps.success({ locales }) }; + const defaultLocale = typeof i18nService.getDefaultLocale === 'function' ? i18nService.getDefaultLocale() : undefined; + const locales = toLocaleDescriptors(i18nService.getLocales(), defaultLocale); + // [#36504] The language the app's own text is authored in: the + // declared `i18n.sourceLocale`, else the default locale — the + // collapse every metadata-document translator makes, and the CALLER's + // to make (`II18nService.getSourceLocale` reports only what was + // declared). A client that edits labels reads it to tell an edit of + // the source text from a translation. Absent when neither is known. + const declaredSource = typeof i18nService.getSourceLocale === 'function' ? i18nService.getSourceLocale() : undefined; + const sourceLocale = declaredSource || defaultLocale || undefined; + return { handled: true, response: deps.success({ locales, ...(sourceLocale ? { sourceLocale } : {}) }) }; } // GET /i18n/translations/:locale OR /i18n/translations?locale=xx diff --git a/packages/runtime/src/i18n-supported-locales.test.ts b/packages/runtime/src/i18n-supported-locales.test.ts index ade22772ea5..0ed50970122 100644 --- a/packages/runtime/src/i18n-supported-locales.test.ts +++ b/packages/runtime/src/i18n-supported-locales.test.ts @@ -37,6 +37,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// Paid at collection, not inside a clocked case: `AppPlugin` loads it lazily (check:test-source-alias). +import '@objectstack/metadata'; import { AppPlugin } from './app-plugin.js'; import { HttpDispatcher } from './http-dispatcher.js'; import { createMemoryI18n } from '@objectstack/core'; @@ -213,3 +215,30 @@ describe('GET /i18n/locales reports the app\'s declared supportedLocales (#7679) ]); }); }); + +/** + * [#36504] `GET /i18n/locales` names the language the app's own text is + * written in, so a client that edits labels (the console's design mode) can + * tell an edit of the source text from a translation. The declared + * `i18n.sourceLocale` wins; an app declaring none is authored in its default + * locale, the collapse every metadata-document translator makes. + */ +describe('GET /i18n/locales names the source locale (#36504)', () => { + async function body(i18nConfig: Record | undefined) { + const { dispatcher } = await bootStack(i18nConfig); + const result = await dispatcher.handleI18n('/locales', 'GET', {}, SIGNED_IN); + const parsed = GetLocalesResponseSchema.safeParse(result.response?.body?.data); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + return parsed.data!; + } + + it('an app authored in English that defaults its users to zh-CN: the source is en, the default zh-CN', async () => { + const read = await body({ defaultLocale: 'zh-CN', sourceLocale: 'en', supportedLocales: ['zh-CN', 'en'] }); + expect(read.sourceLocale).toBe('en'); + expect(read.locales.find((l) => l.isDefault)?.code).toBe('zh-CN'); + }); + + it('an app declaring no sourceLocale is authored in its default locale', async () => { + expect((await body({ defaultLocale: 'zh-CN', supportedLocales: ['zh-CN', 'en'] })).sourceLocale).toBe('zh-CN'); + }); +}); diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 3aa3e3fb863..8ba6e68603d 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -859,6 +859,7 @@ "api/GetInstalledPackageResponse:meta", "api/GetInstalledPackageResponse:success", "api/GetLocalesResponse:locales", + "api/GetLocalesResponse:sourceLocale", "api/GetMetaDiagnosticsResponse:entries", "api/GetMetaDiagnosticsResponse:scannedItems", "api/GetMetaDiagnosticsResponse:scannedTypes", diff --git a/packages/spec/src/api/protocol.test.ts b/packages/spec/src/api/protocol.test.ts index b2f284e6e2b..34d7d547cc9 100644 --- a/packages/spec/src/api/protocol.test.ts +++ b/packages/spec/src/api/protocol.test.ts @@ -467,6 +467,12 @@ describe('ObjectStack Protocol', () => { { code: 'es-ES', label: 'Spanish (Spain)' }, ], }).success).toBe(true); + // [#36504] The source locale is declared, so the parse keeps it (an + // undeclared key would be stripped), and it is optional. + expect(GetLocalesResponseSchema.parse({ + locales: [{ code: 'zh-CN', label: 'zh-CN', isDefault: true }], + sourceLocale: 'en', + }).sourceLocale).toBe('en'); expect(GetTranslationsRequestSchema.safeParse({ locale: 'en-US' }).success).toBe(true); // The request is locale-only. `namespace`/`keys` were declared here but read // by no serving surface, so they were trimmed (#3676). Asserting on the diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 2cc732b54d9..1c9a37ff18e 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4806,6 +4806,17 @@ export const GetLocalesRequestSchema = lazySchema(() => z.object({})); * the requester's `Accept-Language`) is a caller's choice the server cannot * make for it. Serving real names would put CLDR data behind an endpoint for * something every client can already compute, and no consumer asks for it. + * + * `sourceLocale` (#36504) names the language the app's inline metadata text + * is authored in — the declared `i18n.sourceLocale`, else the default locale, + * the same collapse the document translators make (`ResolveOptions.defaultLocale` + * fed from `getSourceLocale?.() ?? getDefaultLocale?.()`). It differs from the + * `isDefault` locale on a deployment authored in one language that defaults + * its users to another. A client that edits labels reads it to tell an edit + * of the source text from a translation: the console's design mode stores a + * menu rename made in any other language as that language's translation. + * Named after its config key, as `defaultLocale`'s `isDefault` mark is the + * config's `defaultLocale`. */ export const GetLocalesResponseSchema = lazySchema(() => z.object({ locales: z.array(z.object({ @@ -4815,6 +4826,10 @@ export const GetLocalesResponseSchema = lazySchema(() => z.object({ ), isDefault: z.boolean().default(false).describe('Whether this is the default locale'), })).describe('Available locales'), + sourceLocale: z.string().optional().describe( + 'The language the app\'s own text (a plain-string `label`) is written in: the declared `i18n.sourceLocale`, ' + + 'else the default locale. Absent when the server knows neither. Text typed in any other locale is a translation', + ), })); /** diff --git a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx index 9dc4020202a..64b6b79e338 100644 --- a/ui/packages/app-shell/src/layout/DesignModeMenu.tsx +++ b/ui/packages/app-shell/src/layout/DesignModeMenu.tsx @@ -21,13 +21,14 @@ * opens its page (objectstack#36538, review N13). A drop outside the menu * moves nothing (review N14). * - * A name is changed only in the app's source language (objectstack#36363, - * ruling (4)): the stored labels are the app's own, and a translation is - * written elsewhere. The rename's name field is open when the session - * language is the deployment's default (`GET /i18n/locales`, the server - * stating no source language of its own yet, objectstack#36504) and the - * entry's shown label is its stored one; else it is closed and says why. - * The icon, adding and moving are open in every language. + * A name is changed in any language, and lands where that language reads it + * (objectstack#36504, relaxing ruling (4) of objectstack#36363): in the app's + * source language (`sourceLocale` on `GET /i18n/locales`) over an entry shown + * by its stored label, the stored label; in any other language, or over a + * translation, that language's translation of the entry, the stored label + * kept (`saveAppMenu`). The rename says so when the name will be a + * translation. A link added outside the source language takes its name the + * same way: stored without one, translated (review N5 of objectstack#36437). * * An entry another package puts into the menu (its manifest's * `navigationContributions`, appended when the app is served) is not in the @@ -165,15 +166,17 @@ import { withEntryIds, withOwnBeforeForeignRuns, type Menu, + labelGoesToTranslation, type MenuEntry, type MenuTargetKind, } from './designModeMenuModel.js'; import { consoleAppMenuDoors, - fetchDefaultLocale, - isSameLanguage, + fetchDeploymentLocales, + labelLanguageOf, readStoredMenu, saveAppMenu, + type DeploymentLocales, } from './designModeMenuSave.js'; import { freeItemName, isNewMenuItemKind, saveAppMenuWithNewItem, type NewMenuItemKind } from './designModeMenuCreate.js'; import { dashboardEditArrival } from './designModeArrival.js'; @@ -262,14 +265,20 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso publishedMoved: t('designMode.menu.publishedMoved', { defaultValue: "Someone published this app's menu while you were saving, so nothing was saved. Save again to apply your changes over theirs.", }), + translationPendingDraft: t('designMode.menu.translationPendingDraft', { + defaultValue: "This app's menu names in this language have unpublished changes in Studio. Publish or discard them there, then save again.", + }), }), [t], ); const appName = app.name; + // The language the labels of an edit are typed in, as the edit is staged + // (objectstack#36504): the save stores each label where that language reads it. + const labels = React.useMemo(() => ({ language }), [language]); const commit = React.useCallback( (navigation: Menu) => - saveAppMenu({ appName, packageId, served, navigation }, texts, consoleAppMenuDoors(client as never)), - [appName, packageId, served, texts, client], + saveAppMenu({ appName, packageId, served, navigation, labels }, texts, consoleAppMenuDoors(client as never)), + [appName, packageId, served, labels, texts, client], ); const stage = change.stage; const update = React.useCallback((next: Menu) => stage(next, commit), [stage, commit]); @@ -277,14 +286,14 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso const [addAt, setAddAt] = React.useState(null); const [renaming, setRenaming] = React.useState(null); - // The stored menu and the deployment's default language, for the rename's - // source-language rule; both `undefined` while read. + // The stored menu and the deployment's languages, for where a rename lands + // (objectstack#36504); both `undefined` while read. const [storedMenu, setStoredMenu] = React.useState(undefined); - const [defaultLocale, setDefaultLocale] = React.useState(undefined); + const [locales, setLocales] = React.useState(undefined); React.useEffect(() => { let cancelled = false; void readStoredMenu(appName, packageId, client as never).then((nav) => !cancelled && setStoredMenu(nav)); - void fetchDefaultLocale().then((code) => !cancelled && setDefaultLocale(code)); + void fetchDeploymentLocales().then((read) => !cancelled && setLocales(read)); return () => { cancelled = true; }; @@ -483,7 +492,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso }; const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) => saveAppMenuWithNewItem( - { appName, packageId, served, navigation, item }, + { appName, packageId, served, navigation, labels, item }, itemTexts, consoleAppMenuDoors(client as never), ), @@ -521,7 +530,7 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso }; const saved = await saveWith(insertEntry(menu, addAt.parentId, addAt.index, entry), (navigation) => saveAppMenuWithNewItem( - { appName, packageId, served, navigation, item: { kind: 'report', name, label, body } }, + { appName, packageId, served, navigation, labels, item: { kind: 'report', name, label, body } }, itemTexts, consoleAppMenuDoors(client as never), ), @@ -648,13 +657,17 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso }; const renamed = renaming ? entryOf(menu, renaming) : null; - /** Whether the entry `id`'s name may be changed here (ruling (4)). */ - const nameOpen = (id: string): boolean => { - if (!defaultLocale || !isSameLanguage(language, defaultLocale)) return false; - const shown = entryOf(served, id); - if (!shown) return true; // added in this session: its name is the editor's own - const stored = storedById?.get(id); - return !!stored && labelOf(shown) === labelOf(stored); + /** + * The language a name typed for the entry `id` is a translation in, or + * `null` when it is the stored label (objectstack#36504): the save's own + * rule (`labelGoesToTranslation`), read here to say so. Unsaid while the + * languages or the stored menu are read. + */ + const translatedIn = (id: string): string | null => { + if (locales === undefined || storedMenu === undefined) return null; + const typedIn = labelLanguageOf(language, locales); + const goes = labelGoesToTranslation(typedIn, entryOf(served, id), storedById?.get(id)); + return goes ? typedIn.locale : null; }; return ( @@ -697,12 +710,14 @@ export default function DesignModeMenu({ app, basePath, resolveTargetLabel, reso setRenaming(null)} onDone={(label, icon) => { - // A name left as it was stays inherited (or as authored); a cleared one inherits again. + // A name left as it was stays inherited (or as authored); a cleared one inherits again + // (one that is a translation drops it). Where the name is stored is the save's. const patch: Record = { icon: icon || undefined }; - if (nameOpen(String(renamed.id)) && label !== labelOf(renamed)) patch.label = label || undefined; + if (label !== labelOf(renamed)) patch.label = label || undefined; update(patchEntry(menu, String(renamed.id), patch)); setRenaming(null); }} @@ -1242,17 +1257,32 @@ function NewItemDialog({ ); } +/** The name of the language `locale`, in the language `reader`; the tag itself where the runtime names none. */ +function languageName(locale: string, reader: string): string { + try { + return new Intl.DisplayNames([reader, 'en'], { type: 'language' }).of(locale) ?? locale; + } catch { + return locale; + } +} + function RenameDialog({ label, icon, - nameLocked, + translatedIn, + language, onClose, onDone, }: { label: string; icon: string; - /** The name is shown, not changed: the session is not in the app's source language. */ - nameLocked: boolean; + /** + * The language a new name is that language's translation in, the stored + * name kept (objectstack#36504); `null` when it is the stored name. + */ + translatedIn: string | null; + /** The reader's language, the one the hint names a language in. */ + language: string; onClose: () => void; onDone: (label: string, icon: string) => void; }) { @@ -1277,15 +1307,17 @@ function RenameDialog({ setName(e.target.value)} /> - {nameLocked && ( -

- {t('designMode.menu.renameSourceOnly', { defaultValue: "Menu names are changed in the app's source language" })} + {translatedIn && ( +

+ {t('designMode.menu.renameTranslation', { + defaultValue: "The new name is shown in {{language}}. The app's other languages keep their names.", + language: languageName(translatedIn, language), + })}

)} @@ -1295,7 +1327,7 @@ function RenameDialog({ {preview} - setIconName(e.target.value)} placeholder="briefcase" /> + setIconName(e.target.value)} placeholder="briefcase" />

{t('designMode.menu.iconHint', { defaultValue: 'A Lucide icon name, such as "briefcase".' })} diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx index a49c88d43c4..f2ba86d537c 100644 --- a/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeMenu-36363.test.tsx @@ -21,7 +21,7 @@ import { SidebarProvider } from '@object-ui/components'; import { NavigationRenderer } from '@object-ui/layout'; import type { NavigationItem } from '@object-ui/types'; -const session = vi.hoisted(() => ({ language: 'en', defaultLocale: 'en' })); +const session = vi.hoisted(() => ({ language: 'en', defaultLocale: 'en', sourceLocale: undefined as string | undefined })); vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), useObjectTranslation: () => ({ @@ -96,7 +96,9 @@ const storedNav = vi.hoisted(() => ({ })); const client = vi.hoisted(() => ({ list: async (type: string) => listed[type] ?? [], - layered: async () => { + layered: async (type?: string) => { + // objectstack#36504: no menu translation item is stored yet. + if (type === 'translation') return { code: null, overlay: null, overlayScope: null, effective: null }; const gate = storedNav.gate; storedNav.gate = null; if (gate) await gate; @@ -239,6 +241,7 @@ beforeEach(() => { toastError.mockReset(); session.language = 'en'; session.defaultLocale = 'en'; + session.sourceLocale = undefined; storedNav.current = null; storedNav.failReads = 0; storedNav.missing = false; @@ -255,7 +258,8 @@ beforeEach(() => { vi.fn(async (url: string) => { if (String(url).endsWith('/api/v1/i18n/locales')) { const locales = ['en', 'zh-CN'].map((code) => ({ code, label: code, isDefault: code === session.defaultLocale })); - return new Response(JSON.stringify({ success: true, data: { locales } }), { status: 200 }); + const sourceLocale = session.sourceLocale ? { sourceLocale: session.sourceLocale } : {}; + return new Response(JSON.stringify({ success: true, data: { locales, ...sourceLocale } }), { status: 200 }); } throw new Error(`unexpected fetch ${url}`); }), @@ -372,33 +376,65 @@ describe('the menu under the design mode (objectstack#36363)', () => { expect(entry('leads')).toHaveTextContent('Prospects'); }); - // Ruling (4) on review 7081226692: a name is changed in the app's source language only. - it('under zh-CN, with English the default, the name is not changed: the field is closed and says why; the icon still is', async () => { + // objectstack#36504 relaxes ruling (4) on review 7081226692: a name is changed in any language, + // and lands where that language reads it. + it('under zh-CN over an English source, the name is changed: the rename says it is a zh-CN name, and the save writes the translation and keeps the stored label', async () => { session.language = 'zh-CN'; + session.defaultLocale = 'zh-CN'; + session.sourceLocale = 'en'; start(); await flush(); await act_on('leads', 'Rename and icon'); const dialog = await screen.findByTestId('design-menu-rename'); - expect(within(dialog).getByLabelText('Name')).toBeDisabled(); - expect(within(dialog).getByTestId('design-menu-rename-source-only')).toHaveTextContent( - "Menu names are changed in the app's source language", - ); + const name = within(dialog).getByLabelText('Name'); + expect(name).toBeEnabled(); + expect(within(dialog).getByTestId('design-menu-rename-translation')).toHaveTextContent(/The new name is shown in .+\. The app's other languages keep their names\./); + fireEvent.change(name, { target: { value: '潜在客户' } }); fireEvent.change(within(dialog).getByLabelText('Icon'), { target: { value: 'user-plus' } }); fireEvent.click(within(dialog).getByRole('button', { name: 'Done' })); await flush(); + expect(entry('leads')).toHaveTextContent('潜在客户'); fireEvent.click(screen.getByTestId('design-mode-save')); await flush(); await flush(); - const leads = (written[0][3] as { navigation: Array<{ children?: Array> }> }).navigation[1].children![0]; + await flush(); + expect(written.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save translation', 'publish translation', 'save app', 'publish app']); + expect(written[0][3]).toEqual({ name: 'crm_menu_zh_cn', locale: 'zh-CN', apps: { crm: { navigation: { leads: { label: '潜在客户' } } } } }); + const leads = (written[2][3] as { navigation: Array<{ children?: Array> }> }).navigation[1].children![0]; expect(leads).toEqual({ id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Leads', icon: 'user-plus' }); }); - it('in the default language, an entry shown under a label other than its stored one is not renamed here', async () => { + it('in the source language, an entry shown under a label other than its stored one is renamed in that language\'s translation', async () => { storedNav.current = NAVIGATION.map((e) => (e.id === 'home' ? { ...e, label: 'apps.crm.home' } : e)); start(); await flush(); await act_on('home', 'Rename and icon'); - expect(within(await screen.findByTestId('design-menu-rename')).getByLabelText('Name')).toBeDisabled(); + const dialog = await screen.findByTestId('design-menu-rename'); + expect(within(dialog).getByLabelText('Name')).toBeEnabled(); + expect(within(dialog).getByTestId('design-menu-rename-translation')).toBeInTheDocument(); + fireEvent.change(within(dialog).getByLabelText('Name'), { target: { value: 'Start' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Done' })); + await flush(); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(written.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save translation', 'publish translation']); + expect(written[0][3]).toMatchObject({ name: 'crm_menu_en', locale: 'en', apps: { crm: { navigation: { home: { label: 'Start' } } } } }); + }); + + it('in the source language, over the stored label, the rename says nothing of a translation and writes the stored label', async () => { + start(); + await flush(); + await act_on('leads', 'Rename and icon'); + const dialog = await screen.findByTestId('design-menu-rename'); + expect(within(dialog).queryByTestId('design-menu-rename-translation')).toBeNull(); + fireEvent.change(within(dialog).getByLabelText('Name'), { target: { value: 'Prospects' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Done' })); + await flush(); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(written.map(([verb, type]) => `${verb} ${type}`)).toEqual(['save app', 'publish app']); }); it("another package's entry (served, not in the stored menu) says where it is changed, and is not moved or removed here", async () => { diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts index 81deaaa934e..57d90f45454 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuModel-36363.test.ts @@ -12,6 +12,7 @@ import { groupsOf, inShownOrder, insertEntry, + labelGoesToTranslation, menuTargets, moveBy, moveEntry, @@ -20,6 +21,7 @@ import { placeOf, rebaseMenuEdits, removeEntry, + splitLabelEdits, storedEntriesById, targetKeyFor, targetKeyOf, @@ -261,3 +263,51 @@ describe('a level in the sidebar order, and that order written back as `order` ( expect(withOrderRewritten(MENU)).toBe(MENU); }); }); + +describe('the labels that are translations (objectstack#36504)', () => { + const ZH = { locale: 'zh-CN', source: false }; + const EN = { locale: 'en', source: true }; + const stored = { id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Leads' }; + const servedZh = { ...stored, label: '线索' }; + + it('outside the source language every label is a translation; in it, only one typed over a translation', () => { + expect(labelGoesToTranslation(ZH, servedZh, stored)).toBe(true); + expect(labelGoesToTranslation(ZH, null, undefined)).toBe(true); + expect(labelGoesToTranslation(EN, stored, stored)).toBe(false); + expect(labelGoesToTranslation(EN, null, undefined)).toBe(false); + expect(labelGoesToTranslation(EN, { ...stored, label: 'Leads (bundle)' }, stored)).toBe(true); + // An entry inheriting its target's name (no stored label) is renamed in its stored label. + const { label: _l, ...bare } = stored; + expect(labelGoesToTranslation(EN, bare, bare)).toBe(false); + }); + + it('the split puts a translated label back as served, takes an added entry\'s off, and leaves other edits', () => { + const served: Menu = [servedZh, { id: 'sales', type: 'group', label: '销售', children: [] }]; + let edited = patchEntry(served, 'leads', { label: '潜在客户', icon: 'user' }); + edited = insertEntry(edited, 'sales', 0, { id: 'nav_item_1', type: 'url', label: '帮助', url: 'https://h' }); + const split = splitLabelEdits(served, edited, storedEntriesById(served, [stored]), ZH); + expect([...split.labels]).toEqual([ + ['leads', '潜在客户'], + ['nav_item_1', '帮助'], + ]); + expect(split.navigation).toEqual([ + { ...servedZh, icon: 'user' }, + { id: 'sales', type: 'group', label: '销售', children: [{ id: 'nav_item_1', type: 'url', url: 'https://h' }] }, + ]); + }); + + it('in the source language the split takes nothing, and hands back the menu given', () => { + const edited = patchEntry([stored], 'leads', { label: 'Prospects' }); + const split = splitLabelEdits([stored], edited, storedEntriesById([stored], [stored]), EN); + expect(split.labels.size).toBe(0); + expect(split.navigation).toBe(edited); + }); + + it('an added entry whose id the stored menu took is written under a fresh id, and `writtenAs` is told', () => { + const writtenAs = new Map(); + const storedNav: Menu = [stored, { id: 'nav_item_1', type: 'page', pageName: 'secret' }]; + const out = rebaseMenuEdits([stored], [stored, { id: 'nav_item_1', type: 'url', url: 'https://h' }], storedNav, writtenAs); + expect(out.map((e) => e.id)).toEqual(['leads', 'nav_item_2', 'nav_item_1']); + expect([...writtenAs]).toEqual([['nav_item_1', 'nav_item_2']]); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts index 9cea4981a15..861d711d2be 100644 --- a/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts +++ b/ui/packages/app-shell/src/layout/__tests__/designModeMenuSave-36363.test.ts @@ -16,8 +16,18 @@ vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ emitMetadataRefresh, })); +import { TranslationItemSchema, translateApp } from '@objectstack/spec/system'; import { withEntryIds, moveBy, inShownOrder, insertEntry, patchEntry, type Menu } from '../designModeMenuModel'; -import { isSameLanguage, saveAppMenu, type AppMenuSaveDoors } from '../designModeMenuSave'; +import { + __resetDefaultLocale, + fetchDeploymentLocales, + isSameLanguage, + labelLanguageOf, + menuTranslationName, + saveAppMenu, + type AppMenuSaveDoors, + type DeploymentLocales, +} from '../designModeMenuSave'; const TEXTS = { notListed: 'not listed', pendingDraft: 'pending draft', noVersion: 'no version', notWritable: 'not writable' }; const NAV = [{ id: 'leads', type: 'object', objectName: 'crm_lead' }]; @@ -285,3 +295,271 @@ describe('the session language against the default one', () => { expect(isSameLanguage(language, locale)).toBe(same); }); }); + +/** + * objectstack#36504 — a name typed outside the app's source language is that + * language's translation (`apps.APP.navigation.ID.label` in the translation + * item `APP_menu_LOCALE`, in the package the menu is written to), and the + * stored label is kept; review N5 of objectstack#36437 — a link added outside + * the source language is stored without a name, its name translated. + */ +describe('a name typed outside the source language is that language\'s translation (objectstack#36504)', () => { + /** An English app, defaulting its users to zh-CN. */ + const EN_SOURCE: DeploymentLocales = { codes: ['zh-CN', 'en'], defaultLocale: 'zh-CN', sourceLocale: 'en' }; + const STORED: Menu = [ + { id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Leads' }, + { id: 'accounts', type: 'object', objectName: 'crm_account', label: 'Accounts' }, + ]; + const SERVED_ZH: Menu = [ + { id: 'leads', type: 'object', objectName: 'crm_lead', label: '线索' }, + { id: 'accounts', type: 'object', objectName: 'crm_account', label: '客户' }, + ]; + + /** The menu doors over `stored`, holding the translation item `translation` (when given) at every package. */ + function translationDoors(opts: { + writable?: boolean; + stored?: Menu; + translation?: Record; + locales?: DeploymentLocales | null; + saveTranslation?: () => Promise; + }) { + const calls: Array<[string, ...unknown[]]> = []; + const d: AppMenuSaveDoors = { + listPackages: async () => + new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: opts.writable ?? true, manifest: { version: '6.5.0' } }]]), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + return { basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: true }; + }, + readLocales: async () => (opts.locales === undefined ? EN_SOURCE : opts.locales), + client: { + layered: async (...args) => { + calls.push(['layered', ...args]); + if (args[0] === 'translation') { + return opts.translation ? { code: null, overlay: opts.translation, effective: opts.translation, overlayVersion: 'v7' } : { code: null, overlay: null, effective: null }; + } + const code = { name: 'crm', label: 'CRM', navigation: opts.stored ?? STORED }; + return { code, effective: code }; + }, + save: async (...args) => { + calls.push(['save', ...args]); + if (args[0] === 'translation' && opts.saveTranslation) return opts.saveTranslation(); + return {}; + }, + publish: async (...args) => { + calls.push(['publish', ...args]); + return {}; + }, + reset: async (...args) => { + calls.push(['reset', ...args]); + return {}; + }, + }, + }; + return { d, calls }; + } + const writes = (calls: Array<[string, ...unknown[]]>) => calls.filter(([c]) => c !== 'layered' && c !== 'ensure'); + const savedOf = (calls: Array<[string, ...unknown[]]>, type: string) => + calls.find(([c, t]) => c === 'save' && t === type)?.[3] as Record | undefined; + + it('a rename under zh-CN over an English source: the zh-CN translation is written and published, the stored label is not', async () => { + const { d, calls } = translationDoors({}); + const navigation = patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, TEXTS, d); + // A rename and nothing else: the translation alone is written, the app is not. + expect(writes(calls)).toEqual([ + [ + 'save', + 'translation', + 'crm_menu_zh_cn', + { name: 'crm_menu_zh_cn', locale: 'zh-CN', apps: { crm: { navigation: { leads: { label: '潜在客户' } } } } }, + { mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }, + ], + ['publish', 'translation', 'crm_menu_zh_cn', { packageId: 'com.acme.crm', ifNoneMatch: '*' }], + ]); + expect(emitMetadataRefresh).toHaveBeenCalledTimes(1); + // The item is one the metadata door takes. + expect(TranslationItemSchema.safeParse(savedOf(calls, 'translation')).success).toBe(true); + + // Read back the way the server serves the app: zh-CN reads the new name, an English reader the base label. + const bundle = { 'zh-CN': { apps: { crm: { navigation: { leads: { label: '潜在客户' } } } } } }; + const app = { name: 'crm', navigation: STORED as never }; + const zh = translateApp(app, bundle as never, { locale: 'zh-CN', defaultLocale: 'en' }); + const en = translateApp(app, bundle as never, { locale: 'en', defaultLocale: 'en' }); + expect((zh.navigation as any[]).map((n) => n.label)).toEqual(['潜在客户', 'Accounts']); + expect((en.navigation as any[]).map((n) => n.label)).toEqual(['Leads', 'Accounts']); + }); + + it('a rename beside a move under zh-CN: the translation first, then the menu with its stored labels', async () => { + const { d, calls } = translationDoors({}); + const navigation = moveBy(patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }), 'accounts', -1); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, TEXTS, d); + expect(writes(calls).map(([c, t]) => `${c} ${t}`)).toEqual(['save translation', 'publish translation', 'save app', 'publish app']); + expect(savedOf(calls, 'app')!.navigation).toEqual([STORED[1], STORED[0]]); + }); + + it('the translation item as stored keeps its other keys and entries; the publish is pinned to the row read', async () => { + const translation = { + name: 'crm_menu_zh_cn', + locale: 'zh-CN', + label: 'Menu names', + apps: { crm: { label: '客户关系', navigation: { accounts: { label: '客户' } } } }, + _packageId: 'com.acme.crm', + }; + const { d, calls } = translationDoors({ translation }); + const navigation = patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, TEXTS, d); + expect(savedOf(calls, 'translation')).toEqual({ + name: 'crm_menu_zh_cn', + locale: 'zh-CN', + label: 'Menu names', + apps: { crm: { label: '客户关系', navigation: { accounts: { label: '客户' }, leads: { label: '潜在客户' } } } }, + }); + expect(calls.find(([c, t]) => c === 'publish' && t === 'translation')).toEqual([ + 'publish', + 'translation', + 'crm_menu_zh_cn', + { packageId: 'com.acme.crm', ifMatch: 'v7' }, + ]); + }); + + it("an installed app: the translation goes to its customization package, the pair's own translations being read first", async () => { + const { d, calls } = translationDoors({ writable: false }); + const navigation = patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, TEXTS, d); + expect(writes(calls).map(([c, t, , , o]) => [c, t, (o as { packageId?: string } | undefined)?.packageId])).toEqual([ + ['save', 'translation', 'com.acme.crm.custom'], + ['publish', 'translation', undefined], + ]); + expect(calls.find(([c, t]) => c === 'publish' && t === 'translation')![3]).toMatchObject({ packageId: 'com.acme.crm.custom' }); + }); + + it('a rename in the source language over the stored label keeps today\'s write: the stored label, no translation', async () => { + const { d, calls } = translationDoors({}); + const navigation = patchEntry(STORED, 'leads', { label: 'Prospects' }); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: STORED, navigation, labels: { language: 'en-US' } }, TEXTS, d); + expect(writes(calls).map(([c, t]) => `${c} ${t}`)).toEqual(['save app', 'publish app']); + expect(savedOf(calls, 'app')!.navigation[0]).toEqual({ id: 'leads', type: 'object', objectName: 'crm_lead', label: 'Prospects' }); + }); + + it('a rename in the source language over a translation the reader was shown is that language\'s translation', async () => { + const served: Menu = [{ ...STORED[0], label: 'Leads (en bundle)' }, STORED[1]]; + const { d, calls } = translationDoors({}); + await saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served, navigation: patchEntry(served, 'leads', { label: 'Prospects' }), labels: { language: 'en' } }, + TEXTS, + d, + ); + expect(savedOf(calls, 'app')).toBeUndefined(); + expect(savedOf(calls, 'translation')).toMatchObject({ name: 'crm_menu_en', locale: 'en', apps: { crm: { navigation: { leads: { label: 'Prospects' } } } } }); + }); + + it('a source locale that differs from the default: a rename in the default language is a translation (the gap the card closes)', async () => { + const { d, calls } = translationDoors({ stored: SERVED_ZH }); + // Stored labels in Chinese, as served: the shown label equals the stored one. + await saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation: patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }), labels: { language: 'zh-CN' } }, + TEXTS, + d, + ); + expect(savedOf(calls, 'app')).toBeUndefined(); + expect(savedOf(calls, 'translation')!.apps.crm.navigation).toEqual({ leads: { label: '潜在客户' } }); + }); + + it('N5: a link added under zh-CN is stored without a name, its name the zh-CN translation of the id it is stored under', async () => { + // The stored menu took `nav_item_1` since the editor read it: the link is stored under a fresh id. + const stored: Menu = [...STORED, { id: 'nav_item_1', type: 'object', objectName: 'crm_case', label: 'Cases', requiredPermissions: ['x'] }]; + const { d, calls } = translationDoors({ stored }); + const link = { id: 'nav_item_1', type: 'url', label: '帮助中心', url: 'https://help.example.com' }; + const navigation = insertEntry(SERVED_ZH, null, 2, link); + await saveAppMenu({ appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, TEXTS, d); + const nav = savedOf(calls, 'app')!.navigation as Menu; + const written = nav.find((e) => e.type === 'url')!; + expect(written).toEqual({ id: 'nav_item_2', type: 'url', url: 'https://help.example.com' }); + expect(savedOf(calls, 'translation')!.apps.crm.navigation).toEqual({ nav_item_2: { label: '帮助中心' } }); + expect(writes(calls).map(([c, t]) => `${c} ${t}`)).toEqual(['save translation', 'publish translation', 'save app', 'publish app']); + }); + + it('N5 CONTROL: a link added in the source language keeps its typed name as its stored label', async () => { + const { d, calls } = translationDoors({}); + const link = { id: 'nav_item_1', type: 'url', label: 'Help', url: 'https://help.example.com' }; + await saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served: STORED, navigation: insertEntry(STORED, null, 2, link), labels: { language: 'en' } }, + TEXTS, + d, + ); + expect((savedOf(calls, 'app')!.navigation as Menu)[2]).toEqual(link); + expect(savedOf(calls, 'translation')).toBeUndefined(); + }); + + it('a cleared name under zh-CN drops the entry from the translation item, and leaves the stored label', async () => { + const translation = { name: 'crm_menu_zh_cn', locale: 'zh-CN', apps: { crm: { navigation: { leads: { label: '潜在客户' }, accounts: { label: '客户' } } } } }; + const { d, calls } = translationDoors({ translation }); + const served: Menu = [{ ...SERVED_ZH[0], label: '潜在客户' }, SERVED_ZH[1]]; + await saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served, navigation: patchEntry(served, 'leads', { label: undefined }), labels: { language: 'zh-CN' } }, + TEXTS, + d, + ); + expect(savedOf(calls, 'translation')!.apps.crm.navigation).toEqual({ accounts: { label: '客户' } }); + expect(savedOf(calls, 'app')).toBeUndefined(); + }); + + it('the languages unread: no language is known to be the source, so a rename is a translation and the base label is kept', async () => { + const { d, calls } = translationDoors({ locales: null }); + await saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served: STORED, navigation: patchEntry(STORED, 'leads', { label: 'Prospects' }), labels: { language: 'en' } }, + TEXTS, + d, + ); + expect(savedOf(calls, 'app')).toBeUndefined(); + expect(savedOf(calls, 'translation')).toMatchObject({ name: 'crm_menu_en', locale: 'en' }); + }); + + it('a pending draft of the translation is refused and said; nothing is published, the menu not written', async () => { + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const { d, calls } = translationDoors({ saveTranslation: () => Promise.reject(conflict) }); + const navigation = moveBy(patchEntry(SERVED_ZH, 'leads', { label: '潜在客户' }), 'accounts', -1); + await expect( + saveAppMenu( + { appName: 'crm', packageId: 'com.acme.crm', served: SERVED_ZH, navigation, labels: { language: 'zh-CN' } }, + { ...TEXTS, translationPendingDraft: 'translation pending' }, + d, + ), + ).rejects.toThrow('translation pending'); + expect(writes(calls).map(([c, t]) => `${c} ${t}`)).toEqual(['save translation']); + }); + + it('the language a label is typed in, as the deployment names it', () => { + expect(labelLanguageOf('zh', EN_SOURCE)).toEqual({ locale: 'zh-CN', source: false }); + expect(labelLanguageOf('EN-us', EN_SOURCE)).toEqual({ locale: 'en', source: true }); + expect(labelLanguageOf('ja-JP', EN_SOURCE)).toEqual({ locale: 'ja-JP', source: false }); + expect(labelLanguageOf('en', null)).toEqual({ locale: 'en', source: false }); + expect(menuTranslationName('crm', 'zh-CN')).toBe('crm_menu_zh_cn'); + expect(menuTranslationName('crm', 'zh-Hant-TW')).toBe('crm_menu_zh_hant_tw'); + }); +}); + +describe('the deployment\'s languages, its source language among them (objectstack#36504)', () => { + const answer = (data: Record) => + vi.fn(async () => new Response(JSON.stringify({ success: true, data }), { status: 200 })); + beforeEach(() => __resetDefaultLocale()); + + it('reads `sourceLocale` beside the default one', async () => { + vi.stubGlobal('fetch', answer({ locales: [{ code: 'zh-CN', label: 'zh-CN', isDefault: true }, { code: 'en', label: 'en', isDefault: false }], sourceLocale: 'en' })); + expect(await fetchDeploymentLocales()).toEqual({ codes: ['zh-CN', 'en'], defaultLocale: 'zh-CN', sourceLocale: 'en' }); + vi.unstubAllGlobals(); + }); + + it('a server that states no source language authors in its default one', async () => { + vi.stubGlobal('fetch', answer({ locales: [{ code: 'en', label: 'en', isDefault: true }] })); + expect(await fetchDeploymentLocales()).toEqual({ codes: ['en'], defaultLocale: 'en', sourceLocale: 'en' }); + vi.unstubAllGlobals(); + }); + + it('a failed read is no language at all', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response('nope', { status: 500 }))); + expect(await fetchDeploymentLocales()).toBeNull(); + vi.unstubAllGlobals(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts index 6d02915e796..5797227f64c 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuCreate.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuCreate.ts @@ -39,11 +39,11 @@ import { emitMetadataRefresh } from '../assistant/assistantBus.js'; import { slugify } from '../views/metadata-admin/createDerive.js'; import { loadHanRomanizer, romanizeHan, romanizerPending } from '../views/metadata-admin/romanizeHan.js'; import { saveAndPublishInPackage, saveDashboardInPlace } from '../views/runtime-metadata-persistence.js'; -import type { Menu } from './designModeMenuModel.js'; import { prepareAppMenuSave, writeAppMenu, type AppMenuSaveDoors, + type AppMenuSaveInput, type AppMenuSaveTexts, } from './designModeMenuSave.js'; @@ -137,7 +137,7 @@ export function newItemBody(item: NewMenuItem): Record { * same package; when the menu is refused, the item is removed again. */ export async function saveAppMenuWithNewItem( - input: { appName: string; packageId: string; served: Menu; navigation: Menu; item: NewMenuItem }, + input: AppMenuSaveInput & { item: NewMenuItem }, texts: NewMenuItemTexts, doors: AppMenuSaveDoors, ): Promise { diff --git a/ui/packages/app-shell/src/layout/designModeMenuModel.ts b/ui/packages/app-shell/src/layout/designModeMenuModel.ts index c9d2d032e30..cbc8342358f 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuModel.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuModel.ts @@ -581,9 +581,16 @@ export function withOwnBeforeForeignRuns(menu: Menu, served: Menu, foreign: (id: * since the editor read it, is not moved, patched or written, and takes no * part in the order comparison. Only an entry `served` does not hold is an * addition; one whose id a stored entry already holds is written under a - * fresh `nav_item_` that neither menu holds. + * fresh `nav_item_` that neither menu holds, and `writtenAs`, when given, + * is told so (the edited id, then the id written), so what is keyed by the + * entry's id elsewhere (its translation, objectstack#36504) follows it. */ -export function rebaseMenuEdits(served: Menu, edited: Menu, stored: Menu): Menu { +export function rebaseMenuEdits( + served: Menu, + edited: Menu, + stored: Menu, + writtenAs?: Map, +): Menu { const keyOf = storedKeyer(served, stored); const s = locate(served, idOf); const e = locate(edited, idOf); @@ -697,7 +704,10 @@ export function rebaseMenuEdits(served: Menu, edited: Menu, stored: Menu): Menu const now = e.get(id)!; let entry: MenuEntry; if (taken.has(id)) entry = taken.get(id)!; - else if (!s.has(id)) entry = keyOf.alias(storedIds.has(id) ? { ...now.entry, id: freshId() } : now.entry, id); + else if (!s.has(id)) { + entry = keyOf.alias(storedIds.has(id) ? { ...now.entry, id: freshId() } : now.entry, id); + if (entry.id !== id) writtenAs?.set(id, String(entry.id)); + } else continue; // A group the stored menu lacks: the entry goes to the end of the top level. const lost = now.parentId !== null && !groupEntries(result, now.parentId); @@ -717,3 +727,90 @@ export function rebaseMenuEdits(served: Menu, edited: Menu, stored: Menu): Menu } return result; } + +/** + * Where a label the editor took is stored (objectstack#36504): the language it + * was typed in, as the deployment names it (`locale`), and whether that is + * the app's source language (`source`), the one its stored labels are in. + */ +export interface MenuLabelLanguage { + readonly locale: string; + readonly source: boolean; +} + +/** + * Whether a label typed in `language` for an entry goes to that language's + * translation, not to the stored label (objectstack#36504, ruling (4) of + * objectstack#36363 relaxed by it). The stored label is the app's own text, so + * it takes only a label typed in the source language, and only where the + * label shown is the stored one: an entry added in this session (`shown` is + * `null`), or one whose served label (`translateApp`'s answer for the reader) + * equals its stored label. Every other label is a translation: one typed in + * another language, and one typed over a translation shown in the source + * language, which the stored label would never reach. An entry the stored + * menu does not hold (`stored` absent) has no stored label to take it. + */ +export function labelGoesToTranslation( + language: MenuLabelLanguage, + shown: MenuEntry | null, + stored: MenuEntry | null | undefined, +): boolean { + if (!language.source) return true; + if (!shown) return false; + if (!stored) return true; + return JSON.stringify(shown.label) !== JSON.stringify(stored.label); +} + +/** The label edits of a menu that are translations, and the menu left to store. */ +export interface MenuLabelSplit { + /** `edited` with each translated label put back as served (an added entry's taken off). */ + readonly navigation: Menu; + /** The translated labels, by the edited entry's id; `null` drops the entry's translation. */ + readonly labels: ReadonlyMap; +} + +/** + * Split the label edits that turned `served` into `edited` (objectstack#36504): + * those {@link labelGoesToTranslation} sends to `language`'s translation come + * out as `labels`, and the entry is put back with its served label, so the + * stored label is never written from them; an entry added with a label typed + * outside the source language is stored without one, its base label left + * for the source language to set (review N5 of objectstack#36437). A cleared + * name drops the entry's translation (`null`). `storedById` is the stored + * entry behind each served one (`storedEntriesById`). + */ +export function splitLabelEdits( + served: Menu, + edited: Menu, + storedById: ReadonlyMap, + language: MenuLabelLanguage, +): MenuLabelSplit { + const s = locate(served, idOf); + const labels = new Map(); + const visit = (entries: Menu): Menu => { + let changed = false; + const out = entries.map((entry) => { + let next = entry; + if (isGroup(entry)) { + const kids = childrenOf(entry); + const kept = visit(kids); + if (kept !== kids) next = { ...next, children: kept }; + } + const id = idOf(entry); + const was = id ? s.get(id)?.entry ?? null : null; + const typed = (entry as Record).label; + const relabelled = was ? JSON.stringify(typed) !== JSON.stringify(was.label) : typed !== undefined; + if (id && relabelled && labelGoesToTranslation(language, was, storedById.get(id))) { + const text = typeof typed === 'string' && typed ? typed : null; + // An entry added without a name has no translation to drop. + if (text !== null || was) labels.set(id, text); + const { label: _typed, ...rest } = next as Record; + next = was && was.label !== undefined ? { ...rest, label: was.label } : rest; + } + if (next !== entry) changed = true; + return next; + }); + return changed ? out : entries; + }; + return { navigation: visit(edited), labels }; +} diff --git a/ui/packages/app-shell/src/layout/designModeMenuSave.ts b/ui/packages/app-shell/src/layout/designModeMenuSave.ts index 51b208b17eb..f0e2d789969 100644 --- a/ui/packages/app-shell/src/layout/designModeMenuSave.ts +++ b/ui/packages/app-shell/src/layout/designModeMenuSave.ts @@ -55,6 +55,21 @@ * empty view) refuses the save (objectstack#36538): nothing served is * written, and the stored app's own keys are never dropped. * + * A name typed outside the app's source language is that language's + * translation, never the stored label (objectstack#36504): the stored labels + * are the app's own text, read in every language that has no translation. + * The source language is the one `GET /i18n/locales` names (`sourceLocale`, + * the declared `i18n.sourceLocale` else the default locale). Such a name, and + * one typed in the source language over a translation the reader was shown, + * is written to the `translation` item `APP_menu_LOCALE` in the package the + * menu is written to (`menuTranslationName`), at the key app navigation is + * translated by (`apps.APP.navigation.ID.label`, `translateApp`): on an + * installed app that is its customization package, whose own translations + * come first (ADR-0146 D2). An entry added with a name typed outside the + * source language is stored without one, and its name is its translation; + * the source language names it when someone sets it there. The translation + * is written before the menu, and alone when it is all the save holds. + * * @module */ @@ -71,12 +86,26 @@ import { type ListedPackageManifest, } from '../views/studio-design/packages-io.js'; import { navPayloadOf } from '../views/metadata-admin/previews/AppNavCanvas.js'; -import { inShownOrder, rebaseMenuEdits, withOrderRewritten, type Menu } from './designModeMenuModel.js'; +import { + inShownOrder, + rebaseMenuEdits, + splitLabelEdits, + storedEntriesById, + withOrderRewritten, + type Menu, + type MenuLabelLanguage, +} from './designModeMenuModel.js'; /** The doors the save goes through; the defaults are the console's own. */ export interface AppMenuSaveDoors { readonly listPackages: () => Promise>; readonly ensureCustomization: (basePackageId: string) => Promise; + /** + * The deployment's languages (`GET /i18n/locales`, {@link fetchDeploymentLocales}), + * read when a save routes labels by language (objectstack#36504). Absent, + * the language is unknown, and every typed label is a translation. + */ + readonly readLocales?: () => Promise; readonly client: { layered: (type: string, name: string, options: { packageId?: string }) => Promise; save: (type: string, name: string, body: unknown, options: Record) => Promise; @@ -106,6 +135,37 @@ export interface AppMenuSaveTexts { * refusal is passed on as it came. */ readonly publishedMoved?: string; + /** + * A draft of the menu's translation is already pending (objectstack#36504). + * Absent, said with {@link pendingDraft}. + */ + readonly translationPendingDraft?: string; +} + +/** + * A menu save's input: the app, the menu the editor was seeded from + * (`served`), the edited one (`navigation`), and the language its labels + * were typed in (`labels`, objectstack#36504). Without `labels`, every label + * edit is written to the stored label. + */ +export interface AppMenuSaveInput { + readonly appName: string; + readonly packageId: string; + readonly served: Menu; + readonly navigation: Menu; + readonly labels?: { readonly language: string }; +} + +/** + * The menu labels a save writes as one language's translation + * (objectstack#36504): the `translation` item `name`, for `locale`, holding + * `apps.APP.navigation.ID.label` for each entry of `labels` (by the id the + * entry is stored under; `null` drops the entry's label from the item). + */ +export interface MenuTranslationWrite { + readonly name: string; + readonly locale: string; + readonly labels: Readonly>; } /** A document as stored, less what a read adds and what belongs to its package. */ @@ -166,6 +226,14 @@ export interface PreparedAppMenuSave { * absent, the publish is not pinned. */ readonly publishPin?: DraftPin | null; + /** + * The menu's own edits are written (objectstack#36504): `false` when the + * save holds label translations only, so the app is not written at all. + * Absent, it is. + */ + readonly writesMenu?: boolean; + /** The labels written as a translation, in `target`, before the menu (objectstack#36504). */ + readonly translation?: MenuTranslationWrite | null; } /** @@ -175,11 +243,11 @@ export interface PreparedAppMenuSave { * where the menu cannot be saved; nothing is written then. */ export async function prepareAppMenuSave( - input: { appName: string; packageId: string; served: Menu; navigation: Menu }, + input: AppMenuSaveInput, texts: AppMenuSaveTexts, doors: AppMenuSaveDoors, ): Promise { - const { appName, packageId, served, navigation } = input; + const { appName, packageId, served } = input; const manifests = await doors.listPackages(); const listed = manifests.get(packageId); if (!listed) throw new Error(texts.notListed); @@ -195,7 +263,30 @@ export async function prepareAppMenuSave( // The stored menu in its shown order, as the editor's is (`inShownOrder`), // so the edits land where the editor showed them; the result's order is // then written as `order` on each level that carries it (objectstack#36591). - const rebased = rebaseMenuEdits(served, navigation, inShownOrder(storedNav)); + const shownStored = inShownOrder(storedNav); + // objectstack#36504: a label typed outside the source language, or over a + // translation, is that language's translation; the menu stored keeps its + // labels, and the translation is keyed by the id each entry is stored under. + let navigation = input.navigation; + let translation: MenuTranslationWrite | null = null; + const writtenAs = new Map(); + let translated: ReadonlyMap = new Map(); + if (input.labels) { + const language = labelLanguageOf(input.labels.language, doors.readLocales ? await doors.readLocales() : null); + const split = splitLabelEdits(served, navigation, storedEntriesById(served, shownStored), language); + navigation = split.navigation; + translated = split.labels; + if (translated.size > 0) translation = { name: menuTranslationName(appName, language.locale), locale: language.locale, labels: {} }; + } + const writesMenu = JSON.stringify(navigation) !== JSON.stringify(served); + const rebased = rebaseMenuEdits(served, navigation, shownStored, writtenAs); + if (translation) { + const labels: Record = {}; + translated.forEach((label, id) => { + labels[writtenAs.get(id) ?? id] = label; + }); + translation = { ...translation, labels }; + } const nextNav = withOrderRewritten(navPayloadOf(rebased as unknown[]) as Menu); let body: Record | null = { ...stored, name: appName, navigation: nextNav }; let target = packageId; @@ -210,16 +301,27 @@ export async function prepareAppMenuSave( // call created holds nothing yet; any other was not read, and is not pinned. publishPin = pair.packageId === listedPair ? pairPin : pair.created ? { ifNoneMatch: '*' } : null; } - return { appName, target, body, publishPin }; + return { appName, target, body, publishPin, writesMenu, translation }; } /** Write and publish a prepared menu save ({@link prepareAppMenuSave}). */ export async function writeAppMenu( prepared: PreparedAppMenuSave, - texts: Pick, + texts: Pick, doors: Pick, ): Promise { - const { appName, target, body, publishPin } = prepared; + const { appName, target, body, publishPin, translation } = prepared; + // The translation first (objectstack#36504): a translation the menu refused + // after it keys an entry the menu does not show yet, which reads as nothing; + // a menu published before a refused translation would be replayed by the + // next 「Save」 and its added entries written twice. + if (translation && Object.keys(translation.labels).length > 0) { + await writeMenuTranslation(appName, target, translation, texts, doors); + if (prepared.writesMenu === false) { + emitMetadataRefresh(); + return; + } + } try { await doors.client.save('app', appName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); } catch (err) { @@ -248,7 +350,7 @@ export async function writeAppMenu( * `packageId`, and publish it. */ export async function saveAppMenu( - input: { appName: string; packageId: string; served: Menu; navigation: Menu }, + input: AppMenuSaveInput, texts: AppMenuSaveTexts, doors: AppMenuSaveDoors, ): Promise { @@ -257,7 +359,81 @@ export async function saveAppMenu( /** The console's doors, around `client` (`useMetadataClient()`). */ export function consoleAppMenuDoors(client: AppMenuSaveDoors['client']): AppMenuSaveDoors { - return { listPackages: fetchListedPackageManifests, ensureCustomization: ensureCustomizationPackage, client }; + return { + listPackages: fetchListedPackageManifests, + ensureCustomization: ensureCustomizationPackage, + readLocales: fetchDeploymentLocales, + client, + }; +} + +/** Whether `value` is a plain object. */ +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** + * The `translation` item a menu's labels in `locale` are written to + * (objectstack#36504): one per app and language, `APP_menu_LOCALE` in the + * item-name grammar (`crm_menu_zh_cn`), so a save reads and writes the + * menu's labels of one language of one app and nothing else. + */ +export function menuTranslationName(appName: string, locale: string): string { + const snake = (text: string) => text.toLowerCase().replace(/[^a-z0-9_]+/g, '_').replace(/^_+|_+$/g, ''); + const name = `${snake(appName)}_menu_${snake(locale)}`; + return /^[a-z]/.test(name) ? name : `app_${name}`; +} + +/** + * Write the menu labels `write` as the translation of the app `appName` in + * `target` (objectstack#36504), and publish it: the item as stored, its other + * keys kept, with `apps.APP.navigation.ID.label` set (or dropped, for + * `null`) for each label. Translations of app navigation are read by entry + * id at those keys (`translateApp`), the pair's own first on a customized + * installed app (ADR-0146 D2), so the reader's language reads the new name + * and every other language keeps its own. + * + * Written by the menu's rule (`writeAppMenu`): the first-write pin, so a + * pending draft is refused and said; the publish pinned to the row read; a + * refused publish discards the draft. + */ +async function writeMenuTranslation( + appName: string, + target: string, + write: MenuTranslationWrite, + texts: Pick, + doors: Pick, +): Promise { + const layers = await doors.client.layered('translation', write.name, { packageId: target }); + const stored = holdsStoredApp(layers) ? storedApp(layers) : {}; + const apps = isRecord(stored.apps) ? stored.apps : {}; + const app = isRecord(apps[appName]) ? apps[appName] : {}; + const navigation: Record = { ...(isRecord(app.navigation) ? app.navigation : {}) }; + for (const [id, label] of Object.entries(write.labels)) { + if (label === null) delete navigation[id]; + else navigation[id] = { ...(isRecord(navigation[id]) ? navigation[id] : {}), label }; + } + const body = { ...stored, name: write.name, locale: write.locale, apps: { ...apps, [appName]: { ...app, navigation } } }; + const pin = publishPinAt(layers); + try { + await doors.client.save('translation', write.name, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + } catch (err) { + if (isDraftVersionConflict(err)) { + throw Object.assign(new Error(texts.translationPendingDraft ?? texts.pendingDraft), { cause: err }); + } + throw err; + } + try { + await doors.client.publish('translation', write.name, { packageId: target, ...(pin ?? {}) }); + } catch (err) { + try { + await doors.client.reset('translation', write.name, { state: 'draft', packageId: target }); + } catch (discardErr) { + console.error('[design-mode] a refused publish left the menu translation draft pending:', discardErr); + } + if (texts.publishedMoved && isDraftVersionConflict(err)) throw Object.assign(new Error(texts.publishedMoved), { cause: err }); + throw err; + } } /** @@ -283,34 +459,72 @@ export async function readStoredMenu( } } -let defaultLocaleRead: Promise | null = null; - /** - * The deployment's default language, as `GET /api/v1/i18n/locales` marks it - * (`isDefault`), read once per page load; `null` when the read fails or marks - * none. The stored labels are taken to be in it: the server states no - * `sourceLocale` of its own yet (objectstack#36504). + * The deployment's languages, as `GET /api/v1/i18n/locales` states them: its + * locale codes, the default one (`isDefault`), and the source language the + * app's own text is written in (`sourceLocale`, objectstack#36504; a server + * that states none is taken to author in its default locale, as before). */ -export function fetchDefaultLocale(): Promise { - if (defaultLocaleRead) return defaultLocaleRead; - defaultLocaleRead = (async () => { +export interface DeploymentLocales { + readonly codes: readonly string[]; + readonly defaultLocale: string | null; + readonly sourceLocale: string | null; +} + +let localesRead: Promise | null = null; + +/** The deployment's languages, read once per page load; `null` when the read fails. */ +export function fetchDeploymentLocales(): Promise { + if (localesRead) return localesRead; + localesRead = (async () => { try { const res = await fetch('/api/v1/i18n/locales', { credentials: 'include' }); if (!res.ok) return null; - const json = (await res.json()) as { data?: { locales?: unknown }; locales?: unknown }; - const locales = Array.isArray(json?.data?.locales) ? json.data.locales : Array.isArray(json?.locales) ? json.locales : []; - const marked = (locales as Array<{ code?: unknown; isDefault?: unknown }>).find((l) => l?.isDefault === true); - return typeof marked?.code === 'string' && marked.code ? marked.code : null; + const json = (await res.json()) as { data?: Record } & Record; + const body = isRecord(json?.data) ? json.data : json; + const locales = (Array.isArray(body?.locales) ? body.locales : []) as Array<{ code?: unknown; isDefault?: unknown }>; + const codes = locales.map((l) => l?.code).filter((code): code is string => typeof code === 'string' && code !== ''); + const marked = locales.find((l) => l?.isDefault === true); + const defaultLocale = typeof marked?.code === 'string' && marked.code ? marked.code : null; + const source = typeof body?.sourceLocale === 'string' && body.sourceLocale ? body.sourceLocale : null; + return { codes, defaultLocale, sourceLocale: source ?? defaultLocale }; } catch { return null; } })(); - return defaultLocaleRead; + return localesRead; +} + +/** + * The deployment's default language, as `GET /api/v1/i18n/locales` marks it + * (`isDefault`), read once per page load; `null` when the read fails or marks + * none. + */ +export async function fetchDefaultLocale(): Promise { + return (await fetchDeploymentLocales())?.defaultLocale ?? null; } -/** Test seam: forget the default-language read. Not public. */ +/** Test seam: forget the languages read. Not public. */ export function __resetDefaultLocale(): void { - defaultLocaleRead = null; + localesRead = null; +} + +/** + * Where a label typed in the session language `language` is stored + * (objectstack#36504): under the deployment's code for that language (the + * exact tag, else one {@link isSameLanguage} matches, else `language` as + * given), in the source language when it is the deployment's + * `sourceLocale`. With the languages unread (`null`), no language is known to + * be the source: a label is then a translation, which never changes what + * another language reads. + */ +export function labelLanguageOf(language: string, locales: DeploymentLocales | null): MenuLabelLanguage { + const codes = locales?.codes ?? []; + const lower = language.trim().toLowerCase().replace(/_/g, '-'); + const locale = + codes.find((code) => code.toLowerCase() === lower) ?? codes.find((code) => isSameLanguage(language, code)) ?? language; + const source = !!locales?.sourceLocale && isSameLanguage(language, locales.sourceLocale); + return { locale, source }; } /** diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 69e3622f00e..5be162fdf7c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3925,7 +3925,7 @@ const ar = { addBefore: 'إضافة عنصر قبله', addAfter: 'إضافة عنصر بعده', rename: 'إعادة التسمية والأيقونة', - renameSourceOnly: 'تُغيَّر أسماء القائمة بلغة التطبيق المصدر', + renameTranslation: 'يظهر الاسم الجديد باللغة {{language}}. تحتفظ لغات التطبيق الأخرى بأسمائها.', remove: 'إزالة من القائمة', contributed: 'تضيف حزمة أخرى هذا العنصر. يُنقل أو يُعاد تسميته أو يُزال هناك.', pickerTitle: 'إضافة عنصر قائمة', @@ -3953,6 +3953,7 @@ const ar = { notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', storedUnread: 'تعذّرت قراءة القائمة المحفوظة لهذا التطبيق، لذا لم يُحفظ شيء.', publishedMoved: 'نشر شخص آخر قائمة هذا التطبيق أثناء الحفظ، لذا لم يُحفظ شيء. احفظ مرة أخرى لتطبيق تغييراتك فوق تغييراته.', + translationPendingDraft: 'لأسماء قائمة هذا التطبيق بهذه اللغة تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', keyboardHint: 'اسحب عنصرًا لنقله، أو ركّز عليه واضغط مفتاح المسافة ثم مفاتيح الأسهم. يفتحه مفتاح Enter.', newDashboard: 'لوحة معلومات جديدة…', newDashboardTitle: 'لوحة معلومات جديدة', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 5a42d07297e..b941b28dca8 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3602,7 +3602,7 @@ const de = { addBefore: 'Eintrag davor einfügen', addAfter: 'Eintrag danach einfügen', rename: 'Umbenennen und Symbol', - renameSourceOnly: 'Menünamen werden in der Ausgangssprache der App geändert', + renameTranslation: 'Der neue Name wird auf {{language}} angezeigt. Die anderen Sprachen der App behalten ihre Namen.', remove: 'Aus dem Menü entfernen', contributed: 'Ein anderes Paket fügt diesen Eintrag hinzu. Er wird dort verschoben, umbenannt oder entfernt.', pickerTitle: 'Menüeintrag hinzufügen', @@ -3630,6 +3630,7 @@ const de = { notWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher kann ihr Menü nicht gespeichert werden.', storedUnread: 'Das gespeicherte Menü dieser App konnte nicht gelesen werden, daher wurde nichts gespeichert.', publishedMoved: 'Jemand hat das Menü dieser App während des Speicherns veröffentlicht, daher wurde nichts gespeichert. Speichern Sie erneut, um Ihre Änderungen darauf anzuwenden.', + translationPendingDraft: 'Die Menünamen dieser App in dieser Sprache haben unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und speichern Sie dann erneut.', keyboardHint: 'Ziehen Sie einen Eintrag, um ihn zu verschieben, oder fokussieren Sie ihn und drücken Sie die Leertaste, dann die Pfeiltasten. Die Eingabetaste öffnet ihn.', newDashboard: 'Neues Dashboard…', newDashboardTitle: 'Neues Dashboard', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 260974ee6a8..fa2e5da4469 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4351,7 +4351,7 @@ const en = { addBefore: 'Add an item before', addAfter: 'Add an item after', rename: 'Rename and icon', - renameSourceOnly: 'Menu names are changed in the app\'s source language', + renameTranslation: 'The new name is shown in {{language}}. The app\'s other languages keep their names.', remove: 'Remove from menu', contributed: 'Another package adds this item. It is moved, renamed or removed there.', pickerTitle: 'Add menu item', @@ -4379,6 +4379,7 @@ const en = { notWritable: 'This app\'s customization package cannot be written, so its menu cannot be saved.', storedUnread: 'This app\'s saved menu could not be read, so nothing was saved.', publishedMoved: 'Someone published this app\'s menu while you were saving, so nothing was saved. Save again to apply your changes over theirs.', + translationPendingDraft: 'This app\'s menu names in this language have unpublished changes in Studio. Publish or discard them there, then save again.', keyboardHint: 'Drag an item to move it, or focus it and press Space, then the arrow keys. Enter opens it.', newDashboard: 'New dashboard…', newDashboardTitle: 'New dashboard', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ddd409a9379..0c1ba24e3c3 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3684,7 +3684,7 @@ const es = { addBefore: 'Añadir un elemento antes', addAfter: 'Añadir un elemento después', rename: 'Cambiar nombre e icono', - renameSourceOnly: 'Los nombres del menú se cambian en el idioma de origen de la aplicación', + renameTranslation: 'El nuevo nombre se muestra en {{language}}. Los demás idiomas de la aplicación conservan sus nombres.', remove: 'Quitar del menú', contributed: 'Otro paquete añade este elemento. Se mueve, se renombra o se quita allí.', pickerTitle: 'Añadir elemento de menú', @@ -3712,6 +3712,7 @@ const es = { notWritable: 'El paquete de personalización de esta aplicación no se puede escribir, así que su menú no se puede guardar.', storedUnread: 'No se pudo leer el menú guardado de esta aplicación, así que no se guardó nada.', publishedMoved: 'Alguien publicó el menú de esta aplicación mientras guardabas, así que no se guardó nada. Vuelve a guardar para aplicar tus cambios sobre los suyos.', + translationPendingDraft: 'Los nombres del menú de esta aplicación en este idioma tienen cambios sin publicar en Studio. Publícalos o descártalos allí y vuelve a guardar.', keyboardHint: 'Arrastra un elemento para moverlo, o enfócalo y pulsa Espacio y luego las flechas. Intro lo abre.', newDashboard: 'Nuevo panel…', newDashboardTitle: 'Nuevo panel', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d4773b6cb88..e4bbe4ea68d 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3680,7 +3680,7 @@ const fr = { addBefore: 'Ajouter un élément avant', addAfter: 'Ajouter un élément après', rename: 'Renommer et icône', - renameSourceOnly: 'Les noms du menu se modifient dans la langue source de l’application', + renameTranslation: 'Le nouveau nom s’affiche en {{language}}. Les autres langues de l’application gardent leurs noms.', remove: 'Retirer du menu', contributed: 'Un autre package ajoute cet élément. Il se déplace, se renomme ou se retire là-bas.', pickerTitle: 'Ajouter un élément de menu', @@ -3708,6 +3708,7 @@ const fr = { notWritable: 'Le package de personnalisation de cette application n’est pas modifiable : son menu ne peut pas être enregistré.', storedUnread: 'Le menu enregistré de cette application n’a pas pu être lu : rien n’a été enregistré.', publishedMoved: 'Quelqu’un a publié le menu de cette application pendant l’enregistrement : rien n’a été enregistré. Enregistrez de nouveau pour appliquer vos modifications par-dessus les siennes.', + translationPendingDraft: 'Les noms du menu de cette application dans cette langue ont des modifications non publiées dans Studio. Publiez-les ou abandonnez-les là-bas, puis enregistrez de nouveau.', keyboardHint: 'Faites glisser un élément pour le déplacer, ou placez le focus dessus et appuyez sur Espace, puis sur les flèches. Entrée l’ouvre.', newDashboard: 'Nouveau tableau de bord…', newDashboardTitle: 'Nouveau tableau de bord', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index fd62978d577..e6e8b1b9d8f 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3604,7 +3604,7 @@ const ja = { addBefore: '前に項目を追加', addAfter: '後ろに項目を追加', rename: '名前とアイコンを変更', - renameSourceOnly: 'メニュー名はアプリのソース言語で変更します', + renameTranslation: '新しい名前は{{language}}で表示されます。アプリのほかの言語では元の名前のままです。', remove: 'メニューから削除', contributed: 'この項目は別のパッケージが追加しています。移動・名前の変更・削除はそのパッケージで行います。', pickerTitle: 'メニュー項目を追加', @@ -3632,6 +3632,7 @@ const ja = { notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', storedUnread: 'このアプリの保存済みメニューを読み取れなかったため、何も保存されませんでした。', publishedMoved: '保存中に他のユーザーがこのアプリのメニューを公開したため、何も保存されませんでした。もう一度保存すると、その変更の上にあなたの変更が適用されます。', + translationPendingDraft: 'このアプリのこの言語のメニュー名には Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', keyboardHint: '項目をドラッグして移動するか、フォーカスしてスペースキーを押し、矢印キーで移動します。Enter キーで開きます。', newDashboard: '新しいダッシュボード…', newDashboardTitle: '新しいダッシュボード', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 1d6ddf07f16..f992d4133fd 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3602,7 +3602,7 @@ const ko = { addBefore: '앞에 항목 추가', addAfter: '뒤에 항목 추가', rename: '이름 및 아이콘 변경', - renameSourceOnly: '메뉴 이름은 앱의 원본 언어에서 변경합니다', + renameTranslation: '새 이름은 {{language}}에서 표시됩니다. 앱의 다른 언어는 기존 이름을 유지합니다.', remove: '메뉴에서 제거', contributed: '이 항목은 다른 패키지가 추가합니다. 이동, 이름 변경, 제거는 그 패키지에서 합니다.', pickerTitle: '메뉴 항목 추가', @@ -3630,6 +3630,7 @@ const ko = { notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', storedUnread: '이 앱의 저장된 메뉴를 읽을 수 없어 아무것도 저장하지 않았습니다.', publishedMoved: '저장하는 동안 다른 사용자가 이 앱의 메뉴를 게시하여 아무것도 저장하지 않았습니다. 다시 저장하면 그 변경 위에 내 변경이 적용됩니다.', + translationPendingDraft: '이 앱의 이 언어 메뉴 이름에 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', keyboardHint: '항목을 끌어서 옮기거나, 포커스한 뒤 스페이스 키를 누르고 화살표 키로 옮기세요. Enter 키를 누르면 열립니다.', newDashboard: '새 대시보드…', newDashboardTitle: '새 대시보드', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 50ac83b45a8..50661e5c987 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3679,7 +3679,7 @@ const pt = { addBefore: 'Adicionar um item antes', addAfter: 'Adicionar um item depois', rename: 'Renomear e ícone', - renameSourceOnly: 'Os nomes do menu são alterados no idioma de origem do aplicativo', + renameTranslation: 'O novo nome aparece em {{language}}. Os outros idiomas do aplicativo mantêm seus nomes.', remove: 'Remover do menu', contributed: 'Outro pacote adiciona este item. Ele é movido, renomeado ou removido lá.', pickerTitle: 'Adicionar item de menu', @@ -3707,6 +3707,7 @@ const pt = { notWritable: 'O pacote de personalização deste aplicativo não pode ser gravado, então o menu não pode ser salvo.', storedUnread: 'Não foi possível ler o menu salvo deste aplicativo, então nada foi salvo.', publishedMoved: 'Alguém publicou o menu deste aplicativo enquanto você salvava, então nada foi salvo. Salve novamente para aplicar suas alterações sobre as dele.', + translationPendingDraft: 'Os nomes do menu deste aplicativo neste idioma têm alterações não publicadas no Studio. Publique ou descarte-as lá e salve novamente.', keyboardHint: 'Arraste um item para movê-lo, ou foque-o e pressione Espaço e depois as setas. Enter o abre.', newDashboard: 'Novo painel…', newDashboardTitle: 'Novo painel', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index df5b86e31c3..e54b9b3805c 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3771,7 +3771,7 @@ const ru = { addBefore: 'Добавить пункт перед', addAfter: 'Добавить пункт после', rename: 'Имя и значок', - renameSourceOnly: 'Названия пунктов меню меняются на исходном языке приложения', + renameTranslation: 'Новое название отображается на языке «{{language}}». В других языках приложения названия не меняются.', remove: 'Убрать из меню', contributed: 'Этот пункт добавляет другой пакет. Перемещайте, переименовывайте или удаляйте его там.', pickerTitle: 'Добавить пункт меню', @@ -3799,6 +3799,7 @@ const ru = { notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', storedUnread: 'Не удалось прочитать сохранённое меню этого приложения, поэтому ничего не сохранено.', publishedMoved: 'Кто-то опубликовал меню этого приложения во время сохранения, поэтому ничего не сохранено. Сохраните ещё раз, чтобы применить свои изменения поверх его изменений.', + translationPendingDraft: 'У названий пунктов меню этого приложения на этом языке есть неопубликованные изменения в Studio. Опубликуйте или отмените их там, затем сохраните ещё раз.', keyboardHint: 'Перетащите пункт, чтобы переместить его, или выделите его и нажмите Пробел, затем клавиши со стрелками. Enter открывает его.', newDashboard: 'Новая панель…', newDashboardTitle: 'Новая панель', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e59964a7316..f33fc1bb2f5 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3745,7 +3745,7 @@ const zh = { addBefore: '在前面加一项', addAfter: '在后面加一项', rename: '改名和图标', - renameSourceOnly: '菜单名称需在应用的源语言下修改', + renameTranslation: '新名称只在{{language}}下显示,应用的其他语言保留原来的名称。', remove: '从菜单移除', contributed: '此菜单项由另一个包添加,请在那个包中移动、改名或移除。', pickerTitle: '添加菜单项', @@ -3773,6 +3773,7 @@ const zh = { notWritable: '这个应用的定制包不可写,菜单无法保存。', storedUnread: '无法读取这个应用已保存的菜单,所以没有保存任何内容。', publishedMoved: '保存期间有人发布了这个应用的菜单,所以没有保存任何内容。再次保存即可把你的修改应用在他们的修改之上。', + translationPendingDraft: '这个应用在当前语言下的菜单名称在 Studio 里有未发布的改动。请先在那里发布或放弃,再保存。', keyboardHint: '拖动菜单项即可移动;也可以聚焦后按空格键,再用方向键移动。按回车键打开。', newDashboard: '新建仪表盘…', newDashboardTitle: '新建仪表盘', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 30f5cec4fdd..54929cf4694 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3745,7 +3745,7 @@ const zhHant = { addBefore: '在前面加一項', addAfter: '在後面加一項', rename: '改名和圖示', - renameSourceOnly: '選單名稱需在應用的源語言下修改', + renameTranslation: '新名稱只在{{language}}下顯示,應用的其他語言保留原來的名稱。', remove: '從選單移除', contributed: '此選單項由另一個包新增,請在那個包中移動、改名或移除。', pickerTitle: '新增選單項', @@ -3773,6 +3773,7 @@ const zhHant = { notWritable: '這個應用的定製包不可寫,選單無法儲存。', storedUnread: '無法讀取這個應用已儲存的選單,所以沒有儲存任何內容。', publishedMoved: '儲存期間有人釋出了這個應用的選單,所以沒有儲存任何內容。再次儲存即可把你的修改應用在他們的修改之上。', + translationPendingDraft: '這個應用在當前語言下的選單名稱在 Studio 裡有未釋出的改動。請先在那裡釋出或放棄,再儲存。', keyboardHint: '拖動選單項即可移動;也可以聚焦後按空格鍵,再用方向鍵移動。按回車鍵開啟。', newDashboard: '新建儀表盤…', newDashboardTitle: '新建儀表盤',