diff --git a/.changeset/36809-console-flow-labels-fallback-chain.md b/.changeset/36809-console-flow-labels-fallback-chain.md new file mode 100644 index 00000000000..a33999eec0c --- /dev/null +++ b/.changeset/36809-console-flow-labels-fallback-chain.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +'@objectstack/runtime': minor +'@object-ui/i18n': minor +'@object-ui/app-shell': minor +'@object-ui/plugin-detail': minor +'@object-ui/console': minor +--- + +feat(i18n): console flow labels follow the server's declared fallback chain + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: none — the new member is a response field the console reads, not something a metadata author writes; no skills/ page teaches `GET /i18n/locales` or how the console resolves flow labels + +- **`GET /api/v1/i18n/locales` names the declared fallback chain.** `GetLocalesResponseSchema` (`@objectstack/spec/api`) gains an optional `fallbackChain: string[]`, and the runtime's `/i18n` domain fills it from the i18n service's `getFallbackLocale()` (the stack's `i18n.fallbackLocale`, else its `defaultLocale`), the same accessor the server's metadata translations hand the spec resolvers as `ResolveOptions.fallbackChain`. A service that declares no fallback (no accessor, or an empty answer, such as the core in-memory provider) serves no member. Nothing existing changes meaning. +- **The console loads the fallback locale's flow translations.** The console's language loader reads the chain and `sourceLocale` beside the active language's bundle and, unless the language is the authored one, fetches each fallback locale's bundle and keeps its `flows` group (`withDeclaredFlowsFallback`, `@object-ui/i18n`). +- **Flow labels walk the same locales as the server.** `activeFlowsBundle` returns the fallback locales' rows too, and the new `flowsResolveOptions` hands the spec resolvers `{ locale, fallbackChain, defaultLocale }`. The flow runner (flow name, field copy, option labels), the flow designer and docs viewer (`flowLabelTranslations`, `useFlowLabelTranslations`, which take the declared options) and the stage-change confirm now read a declared fallback locale's text for a label the active language lacks, before the authored label. A stack that declares no fallback keeps "requested locale, then the authored label". diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index 8c44f7522b5..70db1cd3c32 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1379,6 +1379,7 @@ This schema accepts one of the following structures: | :--- | :--- | :--- | :--- | | **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 | +| **fallbackChain** | `string[]` | optional | The locales the server consults, in order, after the requested one and before the authored text: the deployment's declared fallback (`i18n.fallbackLocale`, else `defaultLocale`). Absent when the i18n service reports none; the requested locale alone is then consulted. A request tag is negotiated against `locales[].code` first, and the chain is not walked for a request that negotiates to `sourceLocale` | ### Nested Shape: `GetLocalesResponse.locales[number]` diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 0a8709e0875..8303aaf32cc 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -213,6 +213,16 @@ Resolved labels are served straight from the REST metadata endpoints (the locale is part of the ETag), so the Console and any SDUI client get translated metadata without doing lookups themselves. +Where the Console resolves a string itself (the `flows` group below), it walks +the same chain. `GET /api/v1/i18n/locales` names the declared chain as +`fallbackChain` (absent when the stack declares none) beside `sourceLocale`, +and the Console loads each fallback locale's `flows` group with the active +locale's bundle. It first matches its own language against the locales that +answer lists, as the server matches a request's locale, so a `zh-Hans` Console +on a stack authored in `zh-CN` reads the authored Chinese and walks no chain. A flow label the active locale lacks then reads the fallback +locale's text before the authored one, as the server's own reads do; with no +declared chain it reads the active locale, then the authored label. + ### An edit beats the packaged catalog A package's bundle translates the strings that package shipped, so it applies @@ -497,8 +507,8 @@ Honest limits worth knowing before you plan around them: console's screen-flow runner; - the flow's own `label` names the flow in the runner's header, above the step's heading, and in the completion toast. A locale the bundle does not - cover shows the label authored on the flow, and a backend that serves no - label shows the flow's API name. + cover reads the declared fallback locale's label, then the label authored + on the flow, and a backend that serves no label shows the flow's API name. A `successMessage` authored on the flow replaces the completion sentence, so the translated label appears in the toast only when the flow declares none. diff --git a/packages/runtime/src/domains/i18n-locales-fallback-chain-36809.test.ts b/packages/runtime/src/domains/i18n-locales-fallback-chain-36809.test.ts new file mode 100644 index 00000000000..4f6e54c6440 --- /dev/null +++ b/packages/runtime/src/domains/i18n-locales-fallback-chain-36809.test.ts @@ -0,0 +1,89 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36809 — `GET /i18n/locales` names the deployment's DECLARED + * fallback chain (`fallbackChain`), produced from the i18n service's + * `getFallbackLocale()`: the accessor the server's own metadata translations + * read to hand the spec resolvers their `fallbackChain` + * (`metaTranslateOptions`, `@objectstack/rest`). The console reads it to walk + * the same locales for the strings it resolves itself (its flow labels). + * + * Pinned: the member is the accessor's answer, wrapped as a one-entry chain; + * a service that declares no fallback (no accessor, or one answering nothing) + * serves no member, never an invented `en` or default; the body still parses + * as `GetLocalesResponseSchema`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { createMemoryI18n } from '@objectstack/core'; +import { GetLocalesResponseSchema } from '@objectstack/spec/api'; + +import { handleI18nRequest } from './i18n.js'; +import { apiErrorResponse } from '../error-envelope.js'; +import type { DomainHandlerDeps } from '../domain-handler-registry.js'; +import type { HttpProtocolContext } from '../http-dispatcher.js'; + +const member = () => ({ + request: { headers: {} }, + executionContext: { userId: 'usr_member', isSystem: false, positions: [], permissions: [], systemPermissions: [] }, +}) as unknown as HttpProtocolContext; + +function makeDeps(service: unknown): DomainHandlerDeps { + return { + getService: vi.fn(async () => service), + resolveService: vi.fn(async () => service), + success: (data: any) => ({ status: 200, body: { success: true, data } }), + error: (message: string, httpStatus = 500, details?: any) => apiErrorResponse({ message, httpStatus, details }), + } as unknown as DomainHandlerDeps; +} + +async function readLocales(service: unknown) { + const result: any = await handleI18nRequest(makeDeps(service), '/locales', 'GET', {}, member()); + expect(result.handled).toBe(true); + expect(result.response.status).toBe(200); + const parsed = GetLocalesResponseSchema.safeParse(result.response.body.data); + expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true); + return result.response.body.data as Record; +} + +function serviceWith(extra: Record) { + return { + getLocales: vi.fn(() => ['zh-CN', 'en']), + getDefaultLocale: vi.fn(() => 'zh-CN'), + getTranslations: vi.fn(() => ({})), + ...extra, + }; +} + +describe('GET /i18n/locales names the declared fallback chain (objectstack#36809)', () => { + it('is produced from getFallbackLocale(): the declared fallback, as a one-entry chain', async () => { + const getFallbackLocale = vi.fn(() => 'en'); + const data = await readLocales(serviceWith({ getFallbackLocale })); + expect(getFallbackLocale).toHaveBeenCalled(); + expect(data.fallbackChain).toEqual(['en']); + // Beside the authored language the resolvers take as `defaultLocale`. + expect(data.sourceLocale).toBe('zh-CN'); + }); + + it('follows the accessor, not a constant: another declared fallback is served as declared', async () => { + const data = await readLocales(serviceWith({ getFallbackLocale: () => 'ja-JP' })); + expect(data.fallbackChain).toEqual(['ja-JP']); + }); + + it.each([ + ['a service with no getFallbackLocale accessor', {}], + ['an accessor answering undefined', { getFallbackLocale: () => undefined }], + ['an accessor answering an empty string', { getFallbackLocale: () => '' }], + ])('%s serves no fallbackChain member', async (_label, extra) => { + const data = await readLocales(serviceWith(extra)); + expect('fallbackChain' in data).toBe(false); + }); + + it('the core in-memory provider, which declares no accessor, serves none even when told a fallback', async () => { + const i18n = createMemoryI18n(); + i18n.setDefaultLocale?.('zh-CN'); + i18n.setFallbackLocale?.('en'); + const data = await readLocales(i18n); + expect('fallbackChain' in data).toBe(false); + }); +}); diff --git a/packages/runtime/src/domains/i18n.ts b/packages/runtime/src/domains/i18n.ts index 6b3a6cbfd01..ca4e8bdd630 100644 --- a/packages/runtime/src/domains/i18n.ts +++ b/packages/runtime/src/domains/i18n.ts @@ -247,7 +247,24 @@ export async function handleI18nRequest( // 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 } : {}) }) }; + // [objectstack#36809] The deployment's DECLARED fallback chain — the + // `getFallbackLocale()` the server's own metadata translations hand + // the spec resolvers as `fallbackChain` (`metaTranslateOptions`, + // `@objectstack/rest`), read by the same feature-detected accessor + // under the same condition (a non-empty string), so a client that + // resolves translated metadata itself walks the locales the server + // walks. Absent when the service declares none: the server threads a + // declaration, it never invents one. + const declaredFallback = typeof i18nService.getFallbackLocale === 'function' ? i18nService.getFallbackLocale() : undefined; + const fallbackChain = typeof declaredFallback === 'string' && declaredFallback.length > 0 ? [declaredFallback] : undefined; + return { + handled: true, + response: deps.success({ + locales, + ...(sourceLocale ? { sourceLocale } : {}), + ...(fallbackChain ? { fallbackChain } : {}), + }), + }; } // GET /i18n/translations/:locale OR /i18n/translations?locale=xx diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 8ba6e68603d..f1f98275e93 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -858,6 +858,7 @@ "api/GetInstalledPackageResponse:error", "api/GetInstalledPackageResponse:meta", "api/GetInstalledPackageResponse:success", + "api/GetLocalesResponse:fallbackChain", "api/GetLocalesResponse:locales", "api/GetLocalesResponse:sourceLocale", "api/GetMetaDiagnosticsResponse:entries", diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 1c9a37ff18e..eb19a9df5c6 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -4817,6 +4817,22 @@ export const GetLocalesRequestSchema = lazySchema(() => z.object({})); * 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`. + * + * `fallbackChain` names the locales the server consults after the requested + * one and before the authored text, the deployment's DECLARED chain: the i18n + * service's `getFallbackLocale()` (the stack's `i18n.fallbackLocale`, else its + * `defaultLocale`, as the boot collapses them), which the server's own + * metadata translations already hand the spec resolvers as + * `ResolveOptions.fallbackChain`. It is absent when the i18n service reports + * no fallback (the file-backed service always reports one, collapsed from + * `fallbackLocale || defaultLocale || 'en'`), and a client then resolves the + * requested locale alone, as the server does. A client that resolves + * translated metadata itself (the console's flow labels) reads it beside + * `sourceLocale` (the resolvers' `defaultLocale`), after negotiating its + * request tag against `locales[].code` as the server negotiates a request's + * tag (`resolveLocaleAmong`), so its answer and the server's walk the same + * locales: a `zh-Hans` request on a deployment holding `zh-CN` is the + * `zh-CN` request, and walks no chain when `zh-CN` is the source locale. */ export const GetLocalesResponseSchema = lazySchema(() => z.object({ locales: z.array(z.object({ @@ -4830,6 +4846,12 @@ export const GetLocalesResponseSchema = lazySchema(() => z.object({ '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', ), + fallbackChain: z.array(z.string()).optional().describe( + 'The locales the server consults, in order, after the requested one and before the authored text: the deployment\'s ' + + 'declared fallback (`i18n.fallbackLocale`, else `defaultLocale`). Absent when the i18n service reports none; the ' + + 'requested locale alone is then consulted. A request tag is negotiated against `locales[].code` first, and the chain ' + + 'is not walked for a request that negotiates to `sourceLocale`', + ), })); /** diff --git a/ui/apps/console/src/loadLanguage.fallbackChain-36809.test.tsx b/ui/apps/console/src/loadLanguage.fallbackChain-36809.test.tsx new file mode 100644 index 00000000000..29162ecc0df --- /dev/null +++ b/ui/apps/console/src/loadLanguage.fallbackChain-36809.test.tsx @@ -0,0 +1,165 @@ +/** + * objectstack#36809 — the console loader brings the server's declared + * fallback chain along with the active language's bundle. + * + * `GET /api/v1/i18n/locales` names the chain (`fallbackChain`) and the + * authored language (`sourceLocale`). The real loader reads both, fetches + * each fallback locale's bundle unless the requested language is the authored + * one, and lays the fallback `flows` groups beside the app namespace. Handed + * to i18next the way `I18nProvider` does, the flow-label readers then answer + * the fallback locale's text for a label the active language lacks, and the + * resolvers' answer equals the server's for the same declaration. A server + * that declares no chain gets exactly the old answer and no extra bundle read. + */ +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { translateFlow, type TranslationBundle } from '@objectstack/spec/system'; +import { + activeFlowsBundle, + createI18n, + DECLARED_FLOWS_FALLBACK_KEY, + flowLabelTranslations, + flowsResolveOptions, +} from '@object-ui/i18n'; +import { TokenStorage } from '@object-ui/auth'; +import { loadLanguage } from './loadLanguage'; +import { publishAuthState } from './i18nSession'; + +const FLOW = 'deal_review'; +const ZH = { flows: { [FLOW]: { nodes: { score_deal: { label: '评分' } } } } }; +const EN = { flows: { [FLOW]: { label: 'Deal review', nodes: { score_deal: { label: 'Score' } } } } }; + +/** Serve the `/i18n` reads by URL, as the server would, and record each URL asked. */ +function serve(locales: Record, bundles: Record) { + const asked: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + asked.push(url); + if (url.endsWith('/api/v1/i18n/locales')) { + return new Response(JSON.stringify({ success: true, data: locales }), { status: 200 }); + } + const match = /\/api\/v1\/i18n\/translations\/([^/?]+)$/.exec(url); + if (match && bundles[match[1]]) { + return new Response(JSON.stringify({ success: true, data: { locale: match[1], translations: bundles[match[1]] } }), { status: 200 }); + } + return new Response('{}', { status: 404 }); + }), + ); + return asked; +} + +const LOCALES = [{ code: 'zh-CN', label: 'zh-CN', isDefault: true }, { code: 'en', label: 'en', isDefault: false }, { code: 'ja-JP', label: 'ja-JP', isDefault: false }]; + +async function loaded(lang: string) { + const resources = await loadLanguage(lang); + const instance = createI18n({ defaultLanguage: lang, detectBrowserLanguage: false }); + instance.addResourceBundle(lang, 'translation', resources, true, true); + return { resources, instance }; +} + +beforeEach(() => { + publishAuthState({ isAuthenticated: true, isLoading: false }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + TokenStorage.clear(); +}); + +describe('loadLanguage brings the declared fallback chain (objectstack#36809)', () => { + it('a flow label the active language lacks reads the fallback locale text, matching the server', async () => { + const asked = serve({ locales: LOCALES, sourceLocale: 'zh-CN', fallbackChain: ['en'] }, { 'ja-JP': ZH, en: EN }); + const { instance } = await loaded('ja-JP'); + expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(true); + + const options = flowsResolveOptions(instance, 'ja-JP'); + expect(options).toEqual({ locale: 'ja-JP', fallbackChain: ['en'], defaultLocale: 'zh-CN' }); + const t = flowLabelTranslations(activeFlowsBundle(instance, 'ja-JP', FLOW), FLOW, 'ja-JP', options); + + const serverBundle = { 'ja-JP': ZH, en: EN } as unknown as TranslationBundle; + const server = translateFlow<{ name: string; label?: string }>({ name: FLOW }, serverBundle, options).label; + expect(server).toBe('Deal review'); + expect(t?.flowLabel).toBe(server); + // The requested locale still wins where it translates. + expect(t?.stepLabel({ id: 'score_deal', type: 'script' })).toBe('评分'); + }); + + it('no declared chain: the old answer, and no fallback bundle is read', async () => { + const asked = serve({ locales: LOCALES, sourceLocale: 'zh-CN' }, { 'ja-JP': ZH, en: EN }); + const { resources, instance } = await loaded('ja-JP'); + expect(resources).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY); + expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(false); + expect(flowsResolveOptions(instance, 'ja-JP')).toEqual({ locale: 'ja-JP' }); + const t = flowLabelTranslations(activeFlowsBundle(instance, 'ja-JP', FLOW), FLOW, 'ja-JP', flowsResolveOptions(instance, 'ja-JP')); + expect(t?.flowLabel).toBeUndefined(); + }); + + it('the authored language walks no chain, so its fallback bundle is not read', async () => { + const asked = serve({ locales: LOCALES, sourceLocale: 'zh-CN', fallbackChain: ['en'] }, { 'zh-CN': ZH, en: EN }); + const { resources } = await loaded('zh-CN'); + expect(resources).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY); + expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(false); + }); + + it('a failing locale-list read degrades to the old answer', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + if (url.endsWith('/api/v1/i18n/locales')) return new Response('nope', { status: 500 }); + return new Response(JSON.stringify({ data: { locale: 'ja-JP', translations: ZH } }), { status: 200 }); + }), + ); + const resources = await loadLanguage('ja-JP'); + expect(resources).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY); + expect(resources).toHaveProperty('app.flows'); + }); +}); + +describe('the language is negotiated against the server locales first (objectstack#36809)', () => { + // The server negotiates a request's tag against the locales it holds before + // it resolves (`negotiatedTranslationLocale`, `@objectstack/rest`), so an + // alias of the authored locale is the authored request and walks no chain. + const ALIAS_LOCALES = [{ code: 'zh-CN', label: 'zh-CN', isDefault: true }, { code: 'en', label: 'en', isDefault: false }]; + + it.each(['zh-Hans', 'zh'])('a %s console on a zh-CN-authored stack with fallback en shows the authored Chinese, as the server does', async (lang) => { + const asked = serve({ locales: ALIAS_LOCALES, sourceLocale: 'zh-CN', fallbackChain: ['en'] }, { [lang]: ZH, en: EN }); + const { resources, instance } = await loaded(lang); + expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(false); + expect(resources).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY); + + // The server: the request negotiated to zh-CN, the source locale, so its + // own bundle and then the authored label answer. + const serverBundle = { 'zh-CN': ZH, en: EN } as unknown as TranslationBundle; + const server = translateFlow<{ name: string; label?: string }>( + { name: FLOW, label: '交易审核 (authored)' }, + serverBundle, + { locale: 'zh-CN', fallbackChain: ['en'], defaultLocale: 'zh-CN' }, + ).label; + expect(server).toBe('交易审核 (authored)'); + + const options = flowsResolveOptions(instance, lang); + const consoleLabel = translateFlow<{ name: string; label?: string }>( + { name: FLOW, label: '交易审核 (authored)' }, + activeFlowsBundle(instance, lang, FLOW), + options, + ).label; + expect(consoleLabel).toBe(server); + }); + + it('a ja console on a stack holding ja-JP resolves as ja-JP and still reads the fallback', async () => { + const asked = serve( + { locales: [...LOCALES.filter((l) => l.code !== 'ja-JP'), { code: 'ja-JP', label: 'ja-JP', isDefault: false }], sourceLocale: 'zh-CN', fallbackChain: ['en'] }, + { ja: ZH, en: EN }, + ); + const { instance } = await loaded('ja'); + expect(asked.some((url) => url.endsWith('/translations/en'))).toBe(true); + const options = flowsResolveOptions(instance, 'ja'); + expect(options).toEqual({ locale: 'ja-JP', fallbackChain: ['en'], defaultLocale: 'zh-CN' }); + const t = flowLabelTranslations(activeFlowsBundle(instance, 'ja', FLOW), FLOW, 'ja', options); + expect(t?.flowLabel).toBe('Deal review'); + expect(t?.stepLabel({ id: 'score_deal', type: 'script' })).toBe('评分'); + }); +}); diff --git a/ui/apps/console/src/loadLanguage.test.tsx b/ui/apps/console/src/loadLanguage.test.tsx index ff682127af8..368d1177323 100644 --- a/ui/apps/console/src/loadLanguage.test.tsx +++ b/ui/apps/console/src/loadLanguage.test.tsx @@ -188,9 +188,12 @@ describe('loadLanguage — reads only for a signed-in page load, with its creden publishAuthState({ isAuthenticated: true, isLoading: false }); expect(Object.keys(await pending)).toEqual(['app']); - expect(fetchSpy).toHaveBeenCalledTimes(1); - const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]; - expect(url).toBe('/api/v1/i18n/translations/zh-CN'); - expect(new Headers(init.headers).get('Authorization')).toBe('Bearer tok-12034'); + // The bundle, and the locale list that names the server's declared + // fallback chain beside it (objectstack#36809): both with the bearer. + const calls = fetchSpy.mock.calls as Array<[string, RequestInit]>; + expect(calls.map(([url]) => url).sort()).toEqual(['/api/v1/i18n/locales', '/api/v1/i18n/translations/zh-CN']); + for (const [, init] of calls) { + expect(new Headers(init.headers).get('Authorization')).toBe('Bearer tok-12034'); + } }); }); diff --git a/ui/apps/console/src/loadLanguage.ts b/ui/apps/console/src/loadLanguage.ts index ed8dac749d1..1548333845c 100644 --- a/ui/apps/console/src/loadLanguage.ts +++ b/ui/apps/console/src/loadLanguage.ts @@ -15,32 +15,131 @@ * signed in, with the session's credentials (objectui#12034, see * `./i18nSession.ts`). Signed out, it requests nothing and answers `{}`, so the * sign-in page renders from the built-in packs. + * + * ## The server's declared fallback chain rides along (objectstack#36809) + * + * The server resolves translated metadata through the deployment's declared + * fallback chain: the requested locale, then each fallback, then the authored + * text. `GET /api/v1/i18n/locales` names that chain (`fallbackChain`), the + * authored language (`sourceLocale`) and the locales the server holds + * (`locales[].code`). The loader reads them beside the bundle and first + * negotiates `lang` against those codes, as the server negotiates a request's + * tag before it resolves (`resolveLocaleAmong(lang, codes) ?? lang`; + * `negotiatedTranslationLocale` in `@objectstack/rest`): a `zh-Hans` or `zh` + * console on a stack holding `zh-CN` is the `zh-CN` request. Unless that + * negotiated language is the authored one (the server walks no chain then), + * it fetches each fallback locale's bundle too, keeping its `flows` group. It lays them beside the app namespace + * (`withDeclaredFlowsFallback`, `@object-ui/i18n`), where the flow-label + * readers find them, so a flow label `lang` does not carry reads the fallback + * locale's text, as the server's own reads do. A server that declares no chain + * costs nothing more than the locale-list read: the answer is exactly what it + * was. Either extra read failing degrades to that same answer. */ -import { isSpecTranslationData, transformSpecTranslations } from '@object-ui/i18n'; +import { + isSpecTranslationData, + transformSpecTranslations, + withDeclaredFlowsFallback, + type DeclaredFlowsFallback, + type FlowsTranslation, +} from '@object-ui/i18n'; +import { resolveLocaleAmong } from '@objectstack/spec/system'; import { i18nFetch, whenSessionAnswered } from './i18nSession'; +const serverUrl = () => import.meta.env.VITE_SERVER_URL || ''; + +/** `data.translations` out of the spec envelope, else the raw JSON (a mock or local-dev server). */ +async function fetchTranslations(lang: string): Promise | null> { + const res = await i18nFetch(`${serverUrl()}/api/v1/i18n/translations/${lang}`); + if (!res.ok) { + console.warn(`[i18n] Failed to load translations for '${lang}': HTTP ${res.status}`); + return null; + } + const json = await res.json(); + if (json?.data?.translations && typeof json.data.translations === 'object') { + return json.data.translations as Record; + } + return json; +} + +interface DeclaredChain { + fallbackChain: string[]; + sourceLocale?: string; + /** `locales[].code`: what the server negotiates a request's tag against. */ + codes: string[]; +} + +/** + * The declared chain, authored language and held locales off + * `GET /api/v1/i18n/locales`, or `null` when the server declares no chain or + * the read fails. + */ +async function fetchDeclaredChain(): Promise { + try { + const res = await i18nFetch(`${serverUrl()}/api/v1/i18n/locales`); + if (!res.ok) return null; + const json = await res.json(); + const body = json?.data && typeof json.data === 'object' ? json.data : json; + const chain: unknown[] = Array.isArray(body?.fallbackChain) ? body.fallbackChain : []; + const fallbackChain = chain.filter((code): code is string => typeof code === 'string' && code.length > 0); + if (fallbackChain.length === 0) return null; + const sourceLocale = typeof body?.sourceLocale === 'string' && body.sourceLocale ? body.sourceLocale : undefined; + const descriptors: unknown[] = Array.isArray(body?.locales) ? body.locales : []; + const codes = descriptors + .map((d) => (d && typeof d === 'object' ? (d as { code?: unknown }).code : undefined)) + .filter((code): code is string => typeof code === 'string' && code.length > 0); + return { fallbackChain, sourceLocale, codes }; + } catch { + return null; + } +} + +const sameTag = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + +/** + * The fallback locales' `flows` groups for `lang`, or `undefined` when there + * is nothing to lay beside its bundle: no declared chain, or `lang`, + * negotiated against the server's locales, is the authored language (the + * resolvers walk no chain for it). + */ +async function declaredFlowsFallback( + lang: string, + declared: DeclaredChain | null, +): Promise { + if (!declared) return undefined; + const locale = resolveLocaleAmong(lang, declared.codes) ?? lang; + if (declared.sourceLocale && sameTag(locale, declared.sourceLocale)) return undefined; + const bundles: DeclaredFlowsFallback['bundles'] = {}; + await Promise.all( + declared.fallbackChain + .filter((code) => !sameTag(code, locale)) + .map(async (code) => { + try { + const translations = await fetchTranslations(code); + const flows = translations?.flows; + if (flows && typeof flows === 'object') bundles[code] = { flows: flows as FlowsTranslation }; + } catch (err) { + console.warn(`[i18n] Failed to load fallback translations for '${code}':`, err); + } + }), + ); + return { + locale, + fallbackChain: declared.fallbackChain, + ...(declared.sourceLocale ? { defaultLocale: declared.sourceLocale } : {}), + bundles, + }; +} + export async function loadLanguage(lang: string): Promise> { if (!(await whenSessionAnswered())) return {}; try { - const serverUrl = import.meta.env.VITE_SERVER_URL || ''; - const res = await i18nFetch(`${serverUrl}/api/v1/i18n/translations/${lang}`); - if (!res.ok) { - console.warn(`[i18n] Failed to load translations for '${lang}': HTTP ${res.status}`); - return {}; - } - const json = await res.json(); - // Unwrap the spec REST API envelope when present - let translations: Record; - if (json?.data?.translations && typeof json.data.translations === 'object') { - translations = json.data.translations as Record; - } else { - // Fallback: mock server / local dev returns flat translation objects - translations = json; - } - if (isSpecTranslationData(translations)) { - return transformSpecTranslations(translations); - } - return translations; + const [translations, declared] = await Promise.all([fetchTranslations(lang), fetchDeclaredChain()]); + if (!translations) return {}; + if (!isSpecTranslationData(translations)) return translations; + return withDeclaredFlowsFallback( + transformSpecTranslations(translations), + await declaredFlowsFallback(lang, declared), + ); } catch (err) { console.warn(`[i18n] Failed to load translations for '${lang}':`, err); return {}; diff --git a/ui/packages/app-shell/src/views/FlowRunner.tsx b/ui/packages/app-shell/src/views/FlowRunner.tsx index 2c374ce54e8..44a106e502a 100644 --- a/ui/packages/app-shell/src/views/FlowRunner.tsx +++ b/ui/packages/app-shell/src/views/FlowRunner.tsx @@ -159,8 +159,9 @@ * * WHERE the bundle comes from is the channel the console already has: * `activeFlowsBundle` (`@object-ui/i18n`) reads the `flows` group back out - * of the i18next resource tree the provider loaded, for the active language. - * There is no second loader. + * of the i18next resource tree the provider loaded, for the active language, + * with the fallback locales' groups when the server declares a fallback chain + * (`flowsResolveOptions`, objectstack#36809). There is no second loader. * * Deliberately NOT localized here: the runner chrome (Cancel / Submit / * Submitting… / the terminal toast's default sentence) — the console's own @@ -358,8 +359,10 @@ import { UploadingScopeProvider, useUploadingScope } from '@object-ui/fields'; import type { ActionCopyTemplate } from '@object-ui/core'; import { FLOW_SCREEN_FIELD_COPY_KEYS, + resolveBundleLocale, resolveFlowScreenFieldOptions, translateFlow, + type ResolveOptions, type TranslationBundle, } from '@objectstack/spec/system'; import type { AutomationResult } from '@objectstack/spec/contracts'; @@ -379,7 +382,7 @@ import { } from './ScreenView.js'; import { flowSuccessCopy, interpretFlowResponse } from '../utils/flowResponse.js'; import { announceFlowDroppedFields } from '../utils/flowLaunch.js'; -import { activeFlowsBundle, type FlowsTranslation } from '@object-ui/i18n'; +import { activeFlowsBundle, flowsLocaleChain, flowsResolveOptions, type FlowsTranslation } from '@object-ui/i18n'; export type { ScreenSpec, ScreenFieldSpec } from './ScreenView.js'; @@ -420,7 +423,7 @@ function overlayFieldOptions( flowName: string, nodeId: string, bundle: TranslationBundle, - language: string, + resolveOptions: ResolveOptions, ): ScreenFieldSpec { // Handed the two members it reads: the served `ScreenFieldSpec` is an // interface, so it does not meet the resolver's open `FlowScreenFieldLike`. @@ -429,7 +432,7 @@ function overlayFieldOptions( flowName, nodeId, { name: field.name, options: field.options }, - { locale: language }, + resolveOptions, ); if (options === field.options) return field; // The resolver copies each served option and replaces only its `label` with @@ -444,17 +447,32 @@ function overlayFieldOptions( * served — the engine already translated them (objectstack#22507 ruling A, see * the header) — and everything else is the payload, untouched. With no bundle * the input comes back as-is. + * + * Each copy key walks the locales the resolvers walk (`flowsLocaleChain`: the + * active language, then the server's declared fallback chain, objectstack#36809), + * so a key the active language lacks reads the fallback locale's copy before + * the authored one, on its own. */ function localizeScreen( screen: ScreenSpec, flowName: string, bundle: TranslationBundle | undefined, - language: string, + resolveOptions: ResolveOptions, ): ScreenSpec { if (!bundle || !Array.isArray(screen.fields)) return screen; - const fieldCopy = bundle[language]?.flows?.[flowName]?.screens?.[screen.nodeId]?.fields; + // Overlaid last locale first, so the earlier one in the walk wins each key. + const fieldCopies = flowsLocaleChain(resolveOptions) + .map((code) => resolveBundleLocale(bundle, code)) + .map((locale) => (locale === undefined ? undefined : bundle[locale]?.flows?.[flowName]?.screens?.[screen.nodeId]?.fields)) + .reverse(); const fields = screen.fields.map((field) => - overlayFieldOptions(overlayFieldCopy(field, fieldCopy?.[field.name]), flowName, screen.nodeId, bundle, language), + overlayFieldOptions( + fieldCopies.reduce((next, copy) => overlayFieldCopy(next, copy?.[field.name]), field), + flowName, + screen.nodeId, + bundle, + resolveOptions, + ), ); return { ...screen, fields }; } @@ -470,9 +488,9 @@ function displayFlowLabel( flowName: string, flowLabel: string | undefined, bundle: TranslationBundle | undefined, - language: string, + resolveOptions: ResolveOptions, ): string { - return translateFlow({ name: flowName, label: flowLabel }, bundle, { locale: language }).label || flowName; + return translateFlow({ name: flowName, label: flowLabel }, bundle, resolveOptions).label || flowName; } /** @@ -634,10 +652,13 @@ export function FlowRunner({ state, authFetch, baseUrl, onClose, onComplete, dat // to keep stable (AGENTS.md §5 #10). `screen` stays the payload the run is // driven by; `shown` differs from it in copy only, so every DISPLAY read — // including the labels the required refusal below names — goes through it. + // With the server's declared fallback chain (objectstack#36809): a string + // the active language lacks reads the fallback locale's, as on the server. const bundle = activeFlowsBundle(i18n, language, flowName); - const shown = localizeScreen(screen, flowName, bundle, language); + const resolveOptions = flowsResolveOptions(i18n, language); + const shown = localizeScreen(screen, flowName, bundle, resolveOptions); // The flow's name as the user reads it (objectui#11092), from the same bundle. - const shownFlowLabel = displayFlowLabel(flowName, flowLabel, bundle, language); + const shownFlowLabel = displayFlowLabel(flowName, flowLabel, bundle, resolveOptions); const setVal = (name: string, v: unknown) => { setValues((p) => ({ ...p, [name]: v })); @@ -775,7 +796,7 @@ export function FlowRunner({ state, authFetch, baseUrl, onClose, onComplete, dat toast.success( flowSuccessCopy(state.actionSuccessMessage, outcome.successMessage)?.text || t('flowRunner.completed', { - flow: displayFlowLabel(flowName, outcome.flowLabel, bundle, language), + flow: displayFlowLabel(flowName, outcome.flowLabel, bundle, resolveOptions), defaultValue: 'Flow "{{flow}}" completed', }), ); diff --git a/ui/packages/app-shell/src/views/__tests__/FlowRunner.fallbackChain-36809.test.tsx b/ui/packages/app-shell/src/views/__tests__/FlowRunner.fallbackChain-36809.test.tsx new file mode 100644 index 00000000000..87ef83ff058 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/FlowRunner.fallbackChain-36809.test.tsx @@ -0,0 +1,86 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36809 — the screen-flow runner follows the server's declared + * fallback chain for the strings it resolves itself. + * + * The console loader lays the declared chain and the fallback locale's `flows` + * group beside the active language's tree (`withDeclaredFlowsFallback`). The + * runner names the flow and overlays each field's copy per key across the + * walk: the active language where it translates, then the fallback locale, + * then the authored text. With no declared chain it reads the active language + * alone, as before. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import { createI18n, I18nProvider, transformSpecTranslations, withDeclaredFlowsFallback } from '@object-ui/i18n'; +import type { TranslationData } from '@objectstack/spec/system'; +import { FlowRunner, type ScreenFlowState } from '../FlowRunner'; + +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); + +const STATE: ScreenFlowState = { + flowName: 'lead_conversion', + flowLabel: 'Lead Conversion (authored)', + runId: 'run-1', + screen: { + nodeId: 'screen_1', + title: 'Conversion Details', + fields: [ + { name: 'opportunityName', label: 'Opportunity Name (authored)', type: 'text', placeholder: 'authored placeholder' }, + ], + }, +}; + +/** The active language (ja-JP) translates the field's placeholder only. */ +const JA: TranslationData = { + flows: { lead_conversion: { screens: { screen_1: { fields: { opportunityName: { placeholder: '例:年間更新' } } } } } }, +}; +/** The declared fallback (en) translates the flow label and the field label. */ +const EN_FLOWS = { + lead_conversion: { + label: 'Lead conversion', + screens: { screen_1: { fields: { opportunityName: { label: 'Opportunity name', placeholder: 'e.g. renewal' } } } }, + }, +}; + +function renderRunner(declared: boolean) { + const instance = createI18n({ defaultLanguage: 'ja-JP', detectBrowserLanguage: false }); + const resources = withDeclaredFlowsFallback( + transformSpecTranslations(JA as Record), + declared ? { fallbackChain: ['en'], defaultLocale: 'zh-CN', bundles: { en: { flows: EN_FLOWS as never } } } : undefined, + ); + instance.addResourceBundle('ja-JP', 'translation', resources, true, true); + render( + + new Response('{}'))} + baseUrl="" + onClose={vi.fn()} + onComplete={vi.fn()} + /> + , + ); + return within(screen.getByRole('dialog')); +} + +describe('FlowRunner follows a declared fallback chain (objectstack#36809)', () => { + it('reads the fallback locale where the active language lacks a string, per key', () => { + const dialog = renderRunner(true); + expect(dialog.getByText('Lead conversion')).toBeInTheDocument(); + expect(dialog.getByText('Opportunity name')).toBeInTheDocument(); + // The active language still wins the key it translates. + expect(dialog.getByPlaceholderText('例:年間更新')).toBeInTheDocument(); + expect(dialog.queryByText('Opportunity Name (authored)')).not.toBeInTheDocument(); + }); + + it('no declared chain: the active language, then the authored text', () => { + const dialog = renderRunner(false); + expect(dialog.getByText('Lead Conversion (authored)')).toBeInTheDocument(); + expect(dialog.getByText('Opportunity Name (authored)')).toBeInTheDocument(); + expect(dialog.getByPlaceholderText('例:年間更新')).toBeInTheDocument(); + expect(dialog.queryByText('Lead conversion')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx index 91456cd2703..966894e1341 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/flow-label-translations.tsx @@ -25,6 +25,7 @@ import { useObjectTranslation } from '@object-ui/react'; import { activeFlowsBundle, flowLabelTranslations, + flowsResolveOptions, type FlowLabelTranslations, } from '@object-ui/i18n'; @@ -35,14 +36,17 @@ export { flowLabelTranslations, useFlowLabelTranslations, type FlowLabelTranslat * Automations rail names each row by it. Each call is * {@link flowLabelTranslations}' `flowLabel` in the console's active language, * the reading the designer header makes for the open flow, so a row and the - * flow it opens cannot disagree. `undefined` where the bundle carries no label + * flow it opens cannot disagree, the server's declared fallback chain + * included (objectstack#36809). `undefined` where the bundle carries no label * for that flow, and the caller keeps the authored label. A fresh function on * every render: a handful of property reads that follow the live resource tree * and a language switch. */ export function useFlowLabelOf(): (flowName: string) => string | undefined { const { i18n, language } = useObjectTranslation(); - return (flowName) => flowLabelTranslations(activeFlowsBundle(i18n, language, flowName), flowName, language)?.flowLabel; + const declared = flowsResolveOptions(i18n, language); + return (flowName) => + flowLabelTranslations(activeFlowsBundle(i18n, language, flowName), flowName, language, declared)?.flowLabel; } const FlowLabelTranslationsContext = React.createContext(undefined); diff --git a/ui/packages/i18n/src/__tests__/flowLabels-fallback-chain-36809.test.ts b/ui/packages/i18n/src/__tests__/flowLabels-fallback-chain-36809.test.ts new file mode 100644 index 00000000000..097deedf13e --- /dev/null +++ b/ui/packages/i18n/src/__tests__/flowLabels-fallback-chain-36809.test.ts @@ -0,0 +1,177 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36809 — the console's flow labels follow the server's declared + * fallback chain. + * + * The server resolves a flow label through the spec resolvers with + * `{ locale, fallbackChain: [getFallbackLocale()], defaultLocale }`. The + * console's loader lays the declared chain and the fallback locales' `flows` + * groups beside the active language's tree (`withDeclaredFlowsFallback`), and + * the readers (`activeFlowsBundle`, `flowsResolveOptions`, + * `flowLabelTranslations`) hand the resolvers the same options. Pinned: + * + * - with a declared fallback, a label the active language lacks reads the + * fallback locale's text, equal to the server's answer for the same bundle + * and options, for every label the readers serve (flow, approval step, + * plain node, untitled screen); + * - with no declared chain, nothing changes: the active language, then + * nothing (the caller keeps the authored label); + * - a request in the authored language walks no chain, as on the server; + * - the walk the readers run for the keys no spec resolver reads + * (`flowsLocaleChain`) visits the locales the resolvers visit. + */ + +import { describe, expect, it } from 'vitest'; +import { + resolveFlowApprovalStepLabel, + translateFlow, + type ResolveOptions, + type TranslationBundle, +} from '@objectstack/spec/system'; +import { createI18n } from '../i18n'; +import { flowLabelTranslations } from '../flowLabels'; +import { + activeFlowsBundle, + DECLARED_FLOWS_FALLBACK_KEY, + flowsLocaleChain, + flowsResolveOptions, + withDeclaredFlowsFallback, + type FlowsTranslation, + type TranslationResourceReader, +} from '../flowsBundle'; + +const FLOW = 'deal_review'; +const approval = { id: 'manager_ok', type: 'approval' }; +const plainNode = { id: 'score_deal', type: 'script' }; +const untitledScreen = { id: 'collect_notes', type: 'screen', config: {} }; + +/** The active language (fr) translates only the plain node. */ +const FR_FLOWS = { [FLOW]: { nodes: { score_deal: { label: 'Noter' } } } } as unknown as FlowsTranslation; +/** The declared fallback (en) translates everything. */ +const EN_FLOWS = { + [FLOW]: { + label: 'Deal review', + approvals: { manager_ok: { label: 'Manager approval' } }, + nodes: { score_deal: { label: 'Score' } }, + screens: { collect_notes: { title: 'Collect notes' } }, + }, +} as unknown as FlowsTranslation; + +/** What the server holds and resolves against: every locale's bundle. */ +const SERVER_BUNDLE = { fr: { flows: FR_FLOWS }, en: { flows: EN_FLOWS } } as unknown as TranslationBundle; +const SERVER_OPTIONS: ResolveOptions = { locale: 'fr', fallbackChain: ['en'], defaultLocale: 'zh-CN' }; + +/** A reader whose `fr` tree is what the console's loader hands the provider. */ +function reader(trees: Record>): TranslationResourceReader { + return { getResourceBundle: (lng: string) => trees[lng] }; +} + +const declaredTree = withDeclaredFlowsFallback( + { app: { flows: FR_FLOWS } }, + { fallbackChain: ['en'], defaultLocale: 'zh-CN', bundles: { en: { flows: EN_FLOWS } } }, +); +const undeclaredTree = withDeclaredFlowsFallback({ app: { flows: FR_FLOWS } }, undefined); + +function consoleLabels(i18n: TranslationResourceReader, language: string) { + return flowLabelTranslations(activeFlowsBundle(i18n, language, FLOW), FLOW, language, flowsResolveOptions(i18n, language)); +} + +describe('console flow labels follow a declared fallback chain (objectstack#36809)', () => { + it('a label missing in the requested locale reads the fallback locale text, matching the server', () => { + const t = consoleLabels(reader({ fr: declaredTree }), 'fr'); + // The server's answers, from the spec resolvers with the server's options. + const serverFlowLabel = translateFlow<{ name: string; label?: string }>({ name: FLOW }, SERVER_BUNDLE, SERVER_OPTIONS).label; + const serverApproval = resolveFlowApprovalStepLabel(SERVER_BUNDLE, FLOW, approval.id, undefined, SERVER_OPTIONS); + expect(serverFlowLabel).toBe('Deal review'); + expect(serverApproval).toBe('Manager approval'); + expect(t?.flowLabel).toBe(serverFlowLabel); + expect(t?.stepLabel(approval)).toBe(serverApproval); + // The keys no spec resolver reads walk the same locales. + expect(t?.stepLabel(untitledScreen)).toBe('Collect notes'); + expect(t?.screenTitle(untitledScreen)).toBe('Collect notes'); + // The requested locale still wins where it translates. + expect(t?.stepLabel(plainNode)).toBe('Noter'); + }); + + it('the readers hand the resolvers the server options', () => { + expect(flowsResolveOptions(reader({ fr: declaredTree }), 'fr')).toEqual(SERVER_OPTIONS); + }); + + it('a flow only the fallback locale translates still yields a bundle', () => { + const tree = withDeclaredFlowsFallback( + { app: { flows: {} } }, + { fallbackChain: ['en'], bundles: { en: { flows: EN_FLOWS } } }, + ); + const i18n = reader({ fr: tree }); + expect(activeFlowsBundle(i18n, 'fr', FLOW)).toEqual({ en: { flows: EN_FLOWS } }); + expect(consoleLabels(i18n, 'fr')?.flowLabel).toBe('Deal review'); + }); + + it('survives the real i18next store the provider writes into', () => { + const instance = createI18n({ defaultLanguage: 'fr', detectBrowserLanguage: false }); + instance.addResourceBundle('fr', 'translation', declaredTree, true, true); + expect(flowsResolveOptions(instance, 'fr')).toEqual(SERVER_OPTIONS); + expect(consoleLabels(instance, 'fr')?.flowLabel).toBe('Deal review'); + }); +}); + +describe('no declared chain: unchanged (objectstack#36809)', () => { + it('the requested locale, then nothing — the caller keeps the authored label', () => { + expect(undeclaredTree).not.toHaveProperty(DECLARED_FLOWS_FALLBACK_KEY); + const i18n = reader({ fr: undeclaredTree, en: { app: { flows: EN_FLOWS } } }); + expect(flowsResolveOptions(i18n, 'fr')).toEqual({ locale: 'fr' }); + expect(activeFlowsBundle(i18n, 'fr', FLOW)).toEqual({ fr: { flows: FR_FLOWS } }); + const t = consoleLabels(i18n, 'fr'); + expect(t?.flowLabel).toBeUndefined(); + expect(t?.stepLabel(approval)).toBeUndefined(); + expect(t?.stepLabel(untitledScreen)).toBeUndefined(); + expect(t?.stepLabel(plainNode)).toBe('Noter'); + }); + + it('an empty declared chain lays nothing', () => { + expect(withDeclaredFlowsFallback({ app: {} }, { fallbackChain: [], bundles: {} })).toEqual({ app: {} }); + }); +}); + +describe('a request in the authored language walks no chain (objectstack#36809)', () => { + it('reads its own row, then nothing, as the server does', () => { + const tree = withDeclaredFlowsFallback( + { app: { flows: FR_FLOWS } }, + { fallbackChain: ['en'], defaultLocale: 'fr', bundles: { en: { flows: EN_FLOWS } } }, + ); + const t = consoleLabels(reader({ fr: tree }), 'fr'); + const serverOptions: ResolveOptions = { locale: 'fr', fallbackChain: ['en'], defaultLocale: 'fr' }; + expect(translateFlow<{ name: string; label?: string }>({ name: FLOW }, SERVER_BUNDLE, serverOptions).label).toBeUndefined(); + expect(t?.flowLabel).toBeUndefined(); + expect(t?.stepLabel(untitledScreen)).toBeUndefined(); + expect(t?.stepLabel(plainNode)).toBe('Noter'); + }); +}); + +describe('flowsLocaleChain visits the locales the spec resolvers visit (objectstack#36809)', () => { + // Each locale's row carries a label naming that locale, and only the rows + // the case lists exist, so the resolver's answer names the first locale its + // walk found; the chain's first listed locale must be the same one. + const cases: Array<[string, ResolveOptions, string[]]> = [ + ['no chain', { locale: 'fr' }, ['de', 'en']], + ['a chain', { locale: 'fr', fallbackChain: ['en'] }, ['de', 'en']], + ['a two-entry chain', { locale: 'fr', fallbackChain: ['de', 'en'] }, ['en', 'de']], + ['the authored request', { locale: 'fr', fallbackChain: ['en'], defaultLocale: 'FR' }, ['en']], + ['a chain naming the request', { locale: 'en', fallbackChain: ['en'] }, ['en']], + ]; + it.each(cases)('%s', (_label, options, rows) => { + const bundle = Object.fromEntries( + rows.map((code) => [code, { flows: { [FLOW]: { approvals: { manager_ok: { label: code } } } } }]), + ) as unknown as TranslationBundle; + const resolved = resolveFlowApprovalStepLabel(bundle, FLOW, approval.id, undefined, options); + const walked = flowsLocaleChain(options).find((code) => rows.includes(code)); + expect(walked).toBe(resolved); + }); +}); diff --git a/ui/packages/i18n/src/flowLabels.ts b/ui/packages/i18n/src/flowLabels.ts index 5130034ce87..23ae9cba223 100644 --- a/ui/packages/i18n/src/flowLabels.ts +++ b/ui/packages/i18n/src/flowLabels.ts @@ -40,10 +40,11 @@ import { resolveBundleLocale, resolveFlowApprovalStepLabel, translateFlow, + type ResolveOptions, type TranslationBundle, } from '@objectstack/spec/system'; import { useObjectTranslation } from './provider.js'; -import { activeFlowsBundle } from './flowsBundle.js'; +import { activeFlowsBundle, flowsLocaleChain, flowsResolveOptions } from './flowsBundle.js'; /** A flow's translated labels in one language. Every member answers `undefined` where the bundle carries nothing. */ export interface FlowLabelTranslations { @@ -71,26 +72,42 @@ export interface FlowLabelTranslations { * The flow label goes through the spec's `translateFlow`, the runner's * resolution path, and an approval step's label through the spec's * `resolveFlowApprovalStepLabel`, the server's; both are asked with the same - * options (`{ locale: language }`, no declared fallback chain, as - * `activeFlowsBundle` promises). Any other step label is the spec-typed - * address of the node's name (see the module note), read by node type out of - * the bundle row the same locale matching picks (`resolveBundleLocale`). + * options: `{ locale: language }` plus the server's declared `fallbackChain` + * and `defaultLocale` (and the negotiated `locale`) when `declared` carries + * them ({@link flowsResolveOptions}, + * objectstack#36809), so a label the active language lacks reads the declared + * fallback locale's text before the authored one, as on the server. Any other + * step label is the spec-typed address of the node's name (see the module + * note), read by node type out of the bundle rows the same locale walk visits + * ({@link flowsLocaleChain}, each tag matched by `resolveBundleLocale`). */ export function flowLabelTranslations( bundle: TranslationBundle | undefined, flowName: string, language: string, + declared?: Pick, ): FlowLabelTranslations | undefined { if (!bundle || !flowName) return undefined; - const resolveOptions = { locale: language }; + // `declared.locale` is the language as the server negotiated it, when the + // loader recorded one (`flowsResolveOptions`); else `language` as it is. + const resolveOptions: ResolveOptions = { ...declared, locale: declared?.locale ?? language }; const flowLabel = translateFlow<{ name: string; label?: string }>({ name: flowName }, bundle, resolveOptions).label; - // The `nodes` and `screens` reads match the locale tag by the spec's one - // locale ladder (`resolveBundleLocale`), the one `translateFlow` and - // `resolveFlowApprovalStepLabel` run for `{ locale: language }`: a `zh-cn` - // session reads a `zh-CN` row. One locale, no fallback chain. - const locale = resolveBundleLocale(bundle, language); - const flow = locale === undefined ? undefined : bundle[locale]?.flows?.[flowName]; + // The `nodes` and `screens` reads walk the locales the resolvers above walk + // (`flowsLocaleChain`), each tag matched by the spec's one locale ladder + // (`resolveBundleLocale`): a `zh-cn` session reads a `zh-CN` row, and a key + // that row lacks reads the declared fallback locale's row. + const flows = flowsLocaleChain(resolveOptions) + .map((code) => resolveBundleLocale(bundle, code)) + .map((locale) => (locale === undefined ? undefined : bundle[locale]?.flows?.[flowName])); const text = (value: unknown) => (typeof value === 'string' && value ? value : undefined); + const first = (read: (flow: NonNullable<(typeof flows)[number]>) => T | undefined): T | undefined => { + for (const flow of flows) { + if (!flow) continue; + const value = read(flow); + if (value !== undefined) return value; + } + return undefined; + }; return { flowLabel: text(flowLabel), stepLabel: (node) => { @@ -101,14 +118,19 @@ export function flowLabelTranslations( if (node.type === 'screen') { const config = node.config && typeof node.config === 'object' ? (node.config as { title?: unknown }) : {}; if (config.title === undefined || config.title === null || config.title === '') { - const title = text(flow?.screens?.[node.id]?.title); + const id = node.id; + const title = first((flow) => text(flow.screens?.[id]?.title)); return title?.includes('{{') ? undefined : title; } } - return text(flow?.nodes?.[node.id]?.label); + const id = node.id; + return first((flow) => text(flow.nodes?.[id]?.label)); + }, + screenTitle: (node) => { + if (node.type !== 'screen' || typeof node.id !== 'string' || !node.id) return undefined; + const id = node.id; + return first((flow) => text(flow.screens?.[id]?.title)); }, - screenTitle: (node) => - node.type === 'screen' && typeof node.id === 'string' && node.id ? text(flow?.screens?.[node.id]?.title) : undefined, }; } @@ -119,5 +141,10 @@ export function flowLabelTranslations( */ export function useFlowLabelTranslations(flowName: string): FlowLabelTranslations | undefined { const { i18n, language } = useObjectTranslation(); - return flowLabelTranslations(activeFlowsBundle(i18n, language, flowName), flowName, language); + return flowLabelTranslations( + activeFlowsBundle(i18n, language, flowName), + flowName, + language, + flowsResolveOptions(i18n, language), + ); } diff --git a/ui/packages/i18n/src/flowsBundle.ts b/ui/packages/i18n/src/flowsBundle.ts index ab417002b3c..63dd4334aa7 100644 --- a/ui/packages/i18n/src/flowsBundle.ts +++ b/ui/packages/i18n/src/flowsBundle.ts @@ -22,10 +22,14 @@ * * The provider's `loadLanguage` hands the app's translation payload to * i18next (`transformSpecTranslations` forwards `flows` verbatim under the app - * namespace), so there is no second loader. + * namespace), so there is no second loader. When the server declares a + * fallback chain, the same loader also fetches each fallback locale's bundle + * and lays its `flows` group beside the tree (objectstack#36809, + * {@link withDeclaredFlowsFallback}), so a label the active language lacks + * reads the fallback locale's text, as the server's does. */ -import type { TranslationBundle, TranslationData } from '@objectstack/spec/system'; +import type { ResolveOptions, TranslationBundle, TranslationData } from '@objectstack/spec/system'; /** The `flows` group of a spec `TranslationData` — typed by the spec, so the address below is checked against it. */ export type FlowsTranslation = NonNullable; @@ -40,29 +44,156 @@ export interface TranslationResourceReader { } /** - * The active language's `flows` group as a spec `TranslationBundle`, or - * `undefined` when the resource tree translates nothing for `flowName`. + * Where a language's resource tree carries the server's declared fallback + * chain and the fallback locales' `flows` groups (objectstack#36809). The + * console's loader writes it beside the app namespace when it loads a + * language ({@link withDeclaredFlowsFallback}); {@link activeFlowsBundle} and + * {@link flowsResolveOptions} read it. It holds no `flows` member of its own, + * so the namespace scan below never mistakes it for an app namespace, and no + * `objects` / `settings` member, so the label readers' scans skip it too. + */ +export const DECLARED_FLOWS_FALLBACK_KEY = '__declaredFlowsFallback'; + +/** What a language's tree holds under {@link DECLARED_FLOWS_FALLBACK_KEY}. */ +export interface DeclaredFlowsFallback { + /** + * The active language NEGOTIATED against `GET /i18n/locales` `locales[].code` + * (`resolveLocaleAmong(language, codes) ?? language`), the tag the server + * hands the resolvers (`negotiatedTranslationLocale`, `@objectstack/rest`): + * a `zh-Hans` console on a stack holding `zh-CN` resolves as `zh-CN`. + * Absent: the active language as it is. + */ + locale?: string; + /** `GET /i18n/locales` `fallbackChain`: the locales the server consults after the requested one. */ + fallbackChain: string[]; + /** `GET /i18n/locales` `sourceLocale`: the authored language, the resolvers' `defaultLocale`. */ + defaultLocale?: string; + /** Each fallback locale's `flows` group, keyed by the locale as the chain names it. */ + bundles: Record; +} + +/** + * `resources` (a language's app resource tree) with `fallback` laid beside + * it under {@link DECLARED_FLOWS_FALLBACK_KEY}, or `resources` itself when + * the server declares no chain. The one writer of that entry. + */ +export function withDeclaredFlowsFallback( + resources: Record, + fallback: DeclaredFlowsFallback | undefined, +): Record { + if (!fallback || fallback.fallbackChain.length === 0) return resources; + return { ...resources, [DECLARED_FLOWS_FALLBACK_KEY]: fallback }; +} + +function readTree(i18n: TranslationResourceReader | undefined, language: string): Record | undefined { + if (typeof i18n?.getResourceBundle !== 'function') return undefined; + const tree = i18n.getResourceBundle(language, 'translation'); + return tree && typeof tree === 'object' ? (tree as Record) : undefined; +} + +function readDeclared(tree: Record | undefined): DeclaredFlowsFallback | undefined { + const entry = tree?.[DECLARED_FLOWS_FALLBACK_KEY] as Partial | undefined; + if (!entry || typeof entry !== 'object' || !Array.isArray(entry.fallbackChain)) return undefined; + const fallbackChain = entry.fallbackChain.filter((code): code is string => typeof code === 'string' && code.length > 0); + if (fallbackChain.length === 0) return undefined; + return { + locale: typeof entry.locale === 'string' && entry.locale ? entry.locale : undefined, + fallbackChain, + defaultLocale: typeof entry.defaultLocale === 'string' && entry.defaultLocale ? entry.defaultLocale : undefined, + bundles: entry.bundles && typeof entry.bundles === 'object' ? entry.bundles : {}, + }; +} + +const sameTag = (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + +/** + * The spec `ResolveOptions` the flow-label readers hand the resolvers in + * `language`: `{ locale: language }`, plus the server's declared + * `fallbackChain` and `defaultLocale` when the loaded tree carries them, with + * `locale` the language as the server negotiated it against its own locales + * ({@link DeclaredFlowsFallback.locale}). The server's metadata translations + * pass the same three (`metaTranslateOptions`, `@objectstack/rest`), so the + * console and the server walk the same locales, and an alias of the authored + * locale (`zh-Hans` for `zh-CN`) walks no chain on either side. With no + * declared chain the answer is `{ locale: language }`: the requested locale, + * then the authored copy. + */ +export function flowsResolveOptions(i18n: TranslationResourceReader | undefined, language: string): ResolveOptions { + const declared = readDeclared(readTree(i18n, language)); + if (!declared) return { locale: language }; + return { + locale: declared.locale ?? language, + fallbackChain: declared.fallbackChain, + ...(declared.defaultLocale ? { defaultLocale: declared.defaultLocale } : {}), + }; +} + +/** + * The locales a lookup with `options` consults, in order — the walk the spec + * resolvers run (`localeChain`, `@objectstack/spec/system` i18n-resolver, + * not exported): the requested locale, then the declared `fallbackChain`, + * unless the requested locale is the authored one (`defaultLocale`, tags + * compared case-insensitively), duplicates dropped. For the keys no spec + * resolver reads (a step's `nodes` / `screens` label, a screen field's copy); + * `flowLabels-fallback-chain-36809.test.ts` pins it equal to the resolvers'. + */ +export function flowsLocaleChain(options: ResolveOptions): string[] { + const locale = options.locale ?? 'en'; + const authored = typeof options.defaultLocale === 'string' && options.defaultLocale.length > 0 + && sameTag(locale, options.defaultLocale); + const chain: string[] = []; + for (const code of [locale, ...(authored ? [] : (options.fallbackChain ?? []))]) { + if (!chain.includes(code)) chain.push(code); + } + return chain; +} + +/** + * The `flows` groups that translate `flowName` for `language`, as a spec + * `TranslationBundle`, or `undefined` when none does. * - * App translations sit under an app namespace at the top of that tree (`app` - * for a spec payload, whatever the payload named for an already-namespaced - * one), so the first namespace whose `flows` group addresses this flow is the - * one read. The bundle is keyed by `language` itself, and the resolvers are - * asked for `language` with no fallback chain: a string the active language - * does not carry falls back to the author's copy, never to a third locale. + * The active language's row comes from the app namespace at the top of its + * resource tree (`app` for a spec payload, whatever the payload named for an + * already-namespaced one): the first namespace whose `flows` group addresses + * this flow, keyed by the language as the server negotiated it when the loader + * recorded one ({@link DeclaredFlowsFallback.locale}), else by `language`. + * When the server declares a fallback chain (`GET /i18n/locales` + * `fallbackChain`, objectstack#36809), each fallback locale whose `flows` + * group addresses this flow adds its own row, keyed by the locale as the + * chain names it, out of the entry the console's loader laid beside the tree + * ({@link DECLARED_FLOWS_FALLBACK_KEY}). + * + * Ask the resolvers with {@link flowsResolveOptions}: a string the active + * language does not carry then reads the declared fallback locale's text, + * and the authored copy only after the whole chain, as on the server. With no + * declared chain the bundle holds the active language alone and the options + * are `{ locale: language }`: requested locale, then the authored copy. */ export function activeFlowsBundle( i18n: TranslationResourceReader | undefined, language: string, flowName: string, ): TranslationBundle | undefined { - if (!flowName || typeof i18n?.getResourceBundle !== 'function') return undefined; - const tree = i18n.getResourceBundle(language, 'translation'); - if (!tree || typeof tree !== 'object') return undefined; - for (const namespace of Object.values(tree as Record)) { + if (!flowName) return undefined; + const tree = readTree(i18n, language); + if (!tree) return undefined; + const bundle: TranslationBundle = {}; + const declared = readDeclared(tree); + // The active row is keyed by the tag the resolvers are asked for + // (`flowsResolveOptions`): the negotiated one when the server declared a chain. + const active = declared?.locale ?? language; + for (const [key, namespace] of Object.entries(tree)) { + if (key === DECLARED_FLOWS_FALLBACK_KEY) continue; const flows = (namespace as { flows?: unknown } | null)?.flows; if (flows && typeof flows === 'object' && (flows as Record)[flowName]) { - return { [language]: { flows: flows as FlowsTranslation } }; + bundle[active] = { flows: flows as FlowsTranslation }; + break; } } - return undefined; + for (const code of declared?.fallbackChain ?? []) { + if (sameTag(code, active) || bundle[code]) continue; + const flows = declared?.bundles[code]?.flows; + if (flows && typeof flows === 'object' && flows[flowName]) bundle[code] = { flows }; + } + return Object.keys(bundle).length > 0 ? bundle : undefined; } diff --git a/ui/packages/i18n/src/index.ts b/ui/packages/i18n/src/index.ts index 95656d9fac4..15667463d99 100644 --- a/ui/packages/i18n/src/index.ts +++ b/ui/packages/i18n/src/index.ts @@ -203,6 +203,11 @@ export { firstDayOfWeek, type WeekdayIndex } from './utils/index.js'; // flow embed. export { activeFlowsBundle, + flowsResolveOptions, + flowsLocaleChain, + withDeclaredFlowsFallback, + DECLARED_FLOWS_FALLBACK_KEY, + type DeclaredFlowsFallback, type FlowsTranslation, type TranslationResourceReader, } from './flowsBundle.js'; diff --git a/ui/packages/plugin-detail/src/stageChangeStarts.tsx b/ui/packages/plugin-detail/src/stageChangeStarts.tsx index 053c0a8b46f..a2327d4c8d6 100644 --- a/ui/packages/plugin-detail/src/stageChangeStarts.tsx +++ b/ui/packages/plugin-detail/src/stageChangeStarts.tsx @@ -36,7 +36,7 @@ import * as React from 'react'; import { SchemaRendererContext } from '@object-ui/react'; -import { activeFlowsBundle, useObjectTranslation } from '@object-ui/i18n'; +import { activeFlowsBundle, flowsResolveOptions, useObjectTranslation } from '@object-ui/i18n'; import { RecordUpdateStartsResponseSchema, type RecordUpdateStart } from '@objectstack/spec/api'; import { translateFlow } from '@objectstack/spec/system'; import { useDetailTranslation } from './useDetailTranslation'; @@ -100,10 +100,14 @@ export function StageChangeStarts({ flows }: { flows: readonly RecordUpdateStart const { t } = useDetailTranslation(); const { i18n, language } = useObjectTranslation(); if (flows.length === 0) return null; + // The server's declared fallback chain rides along (objectstack#36809), so + // a flow the reader's language does not name reads the fallback locale's + // label before the authored one, as the server's own reads do. + const resolveOptions = flowsResolveOptions(i18n, language); const labelOf = (flow: RecordUpdateStart): string => { const bundle = activeFlowsBundle(i18n, language, flow.name); if (!bundle) return flow.label; - const translated = translateFlow({ name: flow.name, label: flow.label }, bundle, { locale: language }).label; + const translated = translateFlow({ name: flow.name, label: flow.label }, bundle, resolveOptions).label; return typeof translated === 'string' && translated ? translated : flow.label; }; return (