diff --git a/.changeset/30126-console-copy-titles-toast-money.md b/.changeset/30126-console-copy-titles-toast-money.md new file mode 100644 index 00000000000..92338e8b979 --- /dev/null +++ b/.changeset/30126-console-copy-titles-toast-money.md @@ -0,0 +1,16 @@ +--- +'@object-ui/i18n': patch +'@object-ui/core': patch +'@object-ui/app-shell': patch +'@object-ui/plugin-dashboard': patch +--- + +fix(console): four copy and display details from a real-user walkthrough: Latin object names spaced in zh form titles, a title on the lookup's create dialog, a success toast that names the action, and money metrics at the currency's decimals + +Clause-②: yes (widening) +Metadata-protocol: none + +- **zh form titles space a Latin object name.** `新建{{object}}`, `编辑{{object}}` and `查看{{object}}` (and the AI chat's record-write card titles) read `新建 Repair Ticket` when the object has no Chinese label, and still `新建联系人` when it has one. `createI18n` applies the spacing to those keys only, through an i18next post-processor; the packs keep the plain `{{object}}` spelling. +- **The lookup's "create the referenced record" dialog has a title.** A `{ objectName, mode: 'create' }` modal descriptor with no `title` now reads `form.createTitle` with the object's label, the title of the console's own New dialog. An authored title still wins. +- **The default success toast names the action.** An action with a `label` and no `successMessage` (and no matching `outcomeMessages` entry) toasts the new pack key `actions.completedNamed` (`Resolve completed`, zh `“解决”已完成`) instead of the generic `Action completed successfully`. An action with no label keeps the generic text. +- **Money metrics keep the currency's decimals.** A dataset metric over a currency measure with no `format`, and a static metric card with a `currency` and no `format`, show the currency's own minor-unit width (CNY `¥1,293.00`, JPY `¥1,293`), the width the list cell shows. Before, the dataset metric printed the shortest form (`¥1,293`, `¥1,280.5`) and the static card rounded to whole units. An authored `format` pattern still states its width. diff --git a/ui/packages/app-shell/src/hooks/__tests__/useActionModal.objectCreateTitle-30126.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useActionModal.objectCreateTitle-30126.test.tsx new file mode 100644 index 00000000000..140bf607f5f --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useActionModal.objectCreateTitle-30126.test.tsx @@ -0,0 +1,90 @@ +/** + * 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. + */ + +/** + * An object create form opened from a `{ objectName, mode: 'create' }` + * descriptor is titled by its object (#30126 item 2). + * + * The descriptor's only producer is the lookup field's inline "create the + * referenced record", which passes no title, so the dialog had no heading and + * opened straight onto the first section's name. It now reads + * `form.createTitle`, the console's own New dialog title. An authored title + * still wins, and an edit form is not given a create title. + */ + +import * as React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, cleanup, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { MetadataCtx } from '@object-ui/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { useActionModal } from '../useActionModal'; + +afterEach(cleanup); + +type Handler = (schema: unknown) => Promise; + +const REPAIR_TICKET = { name: 'repair_ticket', label: 'Repair Ticket', fields: { subject: { type: 'text', label: 'Subject' } } }; + +const dataSource = { + getObjectSchema: async () => REPAIR_TICKET, + find: async () => ({ data: [], total: 0 }), + findOne: async () => null, +}; + +const metadata: any = { + apps: [], objects: [REPAIR_TICKET], dashboards: [], reports: [], pages: [], + loading: false, error: null, + refresh: async () => {}, invalidate: () => {}, ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + getTypeStatus: () => 'ready', +}; + +function Harness({ onReady }: { onReady: (h: Handler) => void }) { + const { modalHandler, modalElement } = useActionModal(dataSource); + React.useEffect(() => onReady(modalHandler), [onReady, modalHandler]); + return <>{modalElement}; +} + +async function open(descriptor: Record, language?: string) { + let handler: Handler | null = null; + const harness = ( + + { handler = h; }} /> + + ); + render(language ? {harness} : harness); + await act(async () => { + void handler!(descriptor); + }); + return screen.findByRole('dialog'); +} + +describe('useActionModal: an object create form is titled by its object (#30126 item 2)', () => { + it('a create descriptor with no title reads form.createTitle', async () => { + await open({ objectName: 'repair_ticket', mode: 'create' }); + expect(await screen.findByRole('heading', { name: 'Create Repair Ticket' })).toBeInTheDocument(); + }); + + it('in a zh session it is the zh title, spaced from a Latin label', async () => { + await open({ objectName: 'repair_ticket', mode: 'create' }, 'zh'); + expect(await screen.findByRole('heading', { name: '新建 Repair Ticket' })).toBeInTheDocument(); + }); + + it('an authored title still wins', async () => { + await open({ objectName: 'repair_ticket', mode: 'create', title: 'Log a repair' }); + expect(await screen.findByRole('heading', { name: 'Log a repair' })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Create Repair Ticket' })).toBeNull(); + }); + + it('CONTROL: an edit form is not given a create title', async () => { + await open({ objectName: 'repair_ticket', mode: 'edit', recordId: 't1' }); + expect(screen.queryByRole('heading', { name: 'Create Repair Ticket' })).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDoneSuccessMessage-12274.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDoneSuccessMessage-12274.test.tsx index b4e2bfe2b36..fc3f79fa62e 100644 --- a/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDoneSuccessMessage-12274.test.tsx +++ b/ui/packages/app-shell/src/hooks/__tests__/useConsoleActionRuntime.flowDoneSuccessMessage-12274.test.tsx @@ -55,8 +55,8 @@ const OBJECT = 'service_case'; const FLOW = 'case_escalate'; const ACTION_MESSAGE = 'Case escalated'; const FLOW_MESSAGE = 'Escalation recorded'; -/** The runner's own default text, in the en pack. */ -const RUNNER_DEFAULT = 'Action completed successfully'; +/** The runner's own default text, in the en pack: it names the labelled action (#30126). */ +const RUNNER_DEFAULT = 'Escalate case completed'; /** The declared action, as the object metadata carries it. */ const DECLARED_WITHOUT_MESSAGE = { name: 'escalate_case', label: 'Escalate case', type: 'flow', target: FLOW }; const DECLARED = { ...DECLARED_WITHOUT_MESSAGE, successMessage: ACTION_MESSAGE }; diff --git a/ui/packages/app-shell/src/hooks/useActionModal.tsx b/ui/packages/app-shell/src/hooks/useActionModal.tsx index 1d3f7768462..f3d6b0f4cd5 100644 --- a/ui/packages/app-shell/src/hooks/useActionModal.tsx +++ b/ui/packages/app-shell/src/hooks/useActionModal.tsx @@ -50,6 +50,7 @@ import { cn, } from '@object-ui/components'; import { SchemaRenderer, useMetadata } from '@object-ui/react'; +import { useObjectLabel, useObjectTranslation } from '@object-ui/i18n'; import { ModalForm } from '@object-ui/plugin-form'; import { resolveFormViewLayout } from '../utils/recordFormNavigation.js'; import { modalTargetRefusalMessage } from '../utils/modalTargetDiagnostics.js'; @@ -165,6 +166,9 @@ export function useActionModal(dataSource?: any) { // layout needs, and an action is when it is needed. const metadata = useMetadata(); const { getItem, ensureType } = metadata; + // The object form's title when the descriptor names none (below). + const { t } = useObjectTranslation(); + const { objectLabel } = useObjectLabel(); const close = useCallback((r: ActionResult) => { setState((s) => { @@ -267,12 +271,21 @@ export function useActionModal(dataSource?: any) { // a create uses the object's `create` form view when it declares one // (objectui#13099), read from the same mode the form below opens in. const formMode = (d.mode as 'create' | 'view' | 'edit') || 'create'; + const objectDef = metadata.objects.find((o: any) => o?.name === d.objectName); const viewLayout = (d.fields || (d as any).sections) ? {} - : resolveFormViewLayout( - metadata.objects.find((o: any) => o?.name === d.objectName), - formMode === 'create' ? 'create' : 'edit', - ); + : resolveFormViewLayout(objectDef, formMode === 'create' ? 'create' : 'edit'); + // A create form is titled by its object, the way the console's own + // New dialog is (`form.createTitle`). The lookup field's inline "create + // the referenced record" hands a descriptor with no title, and its + // dialog opened straight onto the first section's heading. + const title = d.title + ?? (formMode === 'create' && objectDef + ? t('form.createTitle', { + defaultValue: 'Create {{object}}', + object: objectLabel({ name: objectDef.name, label: objectDef.label ?? objectDef.name }), + }) + : undefined); modalElement = ( { // the title is Chinese. No inline English `defaultValue` can satisfy this // assertion, so it fails loudly if the packs ever stop being consulted. renderPage('create', { language: 'zh' }); - expect(title()).toBe(String(builtInLocales.zh.form.createTitle).replace('{{object}}', 'Contacts')); - expect(title()).toBe('新建Contacts'); + // The pack's `新建{{object}}`, with the zh spacing between Han text and a + // Latin label that `createI18n` applies to this key. + expect(String(builtInLocales.zh.form.createTitle)).toBe('新建{{object}}'); + expect(title()).toBe('新建 Contacts'); }); }); diff --git a/ui/packages/core/src/actions/ActionRunner.ts b/ui/packages/core/src/actions/ActionRunner.ts index 76bfe04684f..a7933247c0c 100644 --- a/ui/packages/core/src/actions/ActionRunner.ts +++ b/ui/packages/core/src/actions/ActionRunner.ts @@ -643,6 +643,9 @@ export type ToastHandler = (message: string, options?: { * - `completedSuccessfully` — the success toast when the author supplied no * copy for it: no `outcomeMessages` entry for the answer's `outcome` and no * `successMessage` (objectui#10900, objectui#11344). + * - `completedNamed` — the same toast for an action that carries a label: it + * names the action (`{{action}}`), so the user reads what was done rather + * than that something was. * - `failed` — the error toast when the error that reached the toast carries * no readable message, and a parallel chain's result when its last action * rejected (objectui#10969). @@ -666,6 +669,10 @@ const RUNNER_TEXT = { key: 'actions.completedSuccessfully', defaultValue: 'Action completed successfully', }, + completedNamed: { + key: 'actions.completedNamed', + defaultValue: '{{action}} completed', + }, failed: { key: 'actions.failed', defaultValue: 'Action failed', @@ -682,6 +689,16 @@ const RUNNER_TEXT = { type RunnerText = { readonly key: string; readonly defaultValue: string }; +/** The one hole in `completedNamed`, the action's label. */ +const COMPLETED_NAMED_HOLE = '{{action}}'; + +/** + * What {@link ActionRunner.setTranslator} takes: an i18next-shaped `t`. The + * options carry `defaultValue` and, for a text with a hole, the hole's value + * (`completedNamed`'s `action`). + */ +type RunnerTranslate = (key: string, options: { defaultValue: string } & Record) => string; + /** * Modal handler — consumers provide to render modal dialogs. */ @@ -1372,7 +1389,7 @@ export class ActionRunner { private navigationHandler: NavigationHandler | null; private paramCollectionHandler: ParamCollectionHandler | null; private resultDialogHandler: ResultDialogHandler | null; - private translate: ((key: string, options: { defaultValue: string }) => string) | null; + private translate: RunnerTranslate | null; private displayLocale: (() => string | undefined) | null; private tenantCurrency: (() => string | undefined) | null; /** Who {@link ActionRunner.subscribeContext} tells of a context change. */ @@ -1433,7 +1450,7 @@ export class ActionRunner { * an early refusal that names its key (`ActionRunnerHandler`'s * `refuseBeforeInput`). With no translator the text stays English. */ - setTranslator(translate: (key: string, options: { defaultValue: string }) => string): void { + setTranslator(translate: RunnerTranslate): void { this.translate = translate; } @@ -1916,6 +1933,17 @@ export class ActionRunner { return this.translate?.(key, { defaultValue }) || defaultValue; } + /** + * `completedNamed` for `label`: the translator's answer with the label as + * its `action` hole, else the English source with the label in that one + * hole. The runner fills no other hole and interpolates no other text. + */ + private completedNamedText(label: string): string { + const { key, defaultValue } = RUNNER_TEXT.completedNamed; + return this.translate?.(key, { action: label, defaultValue }) + || defaultValue.replace(COMPLETED_NAMED_HOLE, () => label); + } + /** * The success toast's text, by the contract's three rungs * (`ActionSchema.outcomeMessages`, objectui#11344): @@ -1924,7 +1952,10 @@ export class ActionRunner { * of the handler's return value — the payload `{{ result.* }}` reads, so * it is the same fact an author writes as `{{ result.outcome }}`; * 2. `successMessage`; - * 3. the runner's own default text, in its translator's language. + * 3. the runner's own default text, in its translator's language: it names + * the action by its `label` when it has one (`completedNamed`; the host + * localizes the label before dispatch, like the copy above), else the + * generic `completedSuccessfully`. * * Rungs 1 and 2 are the author's copy. Both arrive already localized — the * host's localizer resolves the bundle entry or the inline `I18nLabel` map @@ -1986,7 +2017,10 @@ export class ActionRunner { ? fillTemplateHoles(successCopy, resultRoots, this.displayLocale?.(), this.tenantCurrency?.()) : successCopy; } - return this.runnerText(RUNNER_TEXT.completedSuccessfully); + const label = typeof action.label === 'string' ? action.label.trim() : ''; + return label + ? this.completedNamedText(label) + : this.runnerText(RUNNER_TEXT.completedSuccessfully); } /** diff --git a/ui/packages/core/src/actions/__tests__/ActionRunner.defaultSuccessToast-10900.test.ts b/ui/packages/core/src/actions/__tests__/ActionRunner.defaultSuccessToast-10900.test.ts index 8ec1dba306b..9b568348a18 100644 --- a/ui/packages/core/src/actions/__tests__/ActionRunner.defaultSuccessToast-10900.test.ts +++ b/ui/packages/core/src/actions/__tests__/ActionRunner.defaultSuccessToast-10900.test.ts @@ -87,3 +87,50 @@ describe('ActionRunner — the default success toast is translatable (objectui#1 expect(toast).toHaveBeenCalledWith('Action completed successfully', expect.objectContaining({ type: 'success' })); }); }); + +describe('ActionRunner — the default success toast names a labelled action (#30126 item 3)', () => { + let runner: ActionRunner; + let toast: Mock; + + beforeEach(() => { + runner = new ActionRunner({}); + toast = vi.fn(); + runner.setToastHandler(toast); + runner.registerHandler('script', SUCCEEDS); + }); + + it('with no translator installed, the toast is the English source with the label filled in', async () => { + await runner.execute({ type: 'script', name: 'resolve', label: 'Resolve' }); + expect(toast).toHaveBeenCalledWith('Resolve completed', expect.objectContaining({ type: 'success' })); + }); + + it('with a translator, it is asked for the named key with the label as its hole', async () => { + const translate = vi.fn((_key: string, options: { defaultValue: string } & Record) => + `“${options.action}”已完成`); + runner.setTranslator(translate); + + await runner.execute({ type: 'script', name: 'resolve', label: '解决' }); + + expect(translate).toHaveBeenCalledWith('actions.completedNamed', { + action: '解决', + defaultValue: '{{action}} completed', + }); + expect(toast).toHaveBeenCalledWith('“解决”已完成', expect.objectContaining({ type: 'success' })); + }); + + it('an empty answer from the translator falls back to the filled English source', async () => { + runner.setTranslator(() => ''); + await runner.execute({ type: 'script', name: 'resolve', label: 'Resolve' }); + expect(toast).toHaveBeenCalledWith('Resolve completed', expect.objectContaining({ type: 'success' })); + }); + + it('a blank label is no name: the generic text stays', async () => { + await runner.execute({ type: 'script', name: 'resolve', label: ' ' }); + expect(toast).toHaveBeenCalledWith('Action completed successfully', expect.objectContaining({ type: 'success' })); + }); + + it("an author's successMessage still wins over the label", async () => { + await runner.execute({ type: 'script', name: 'resolve', label: 'Resolve', successMessage: 'Ticket resolved' }); + expect(toast).toHaveBeenCalledWith('Ticket resolved', expect.objectContaining({ type: 'success' })); + }); +}); diff --git a/ui/packages/core/src/utils/__tests__/dataset-format.test.ts b/ui/packages/core/src/utils/__tests__/dataset-format.test.ts index 1b24134278d..9641280bd54 100644 --- a/ui/packages/core/src/utils/__tests__/dataset-format.test.ts +++ b/ui/packages/core/src/utils/__tests__/dataset-format.test.ts @@ -112,3 +112,22 @@ describe('buildDatasetFieldHelpers', () => { expect(measureField('nope')).toBeUndefined(); }); }); + +describe('formatMeasure — an unformatted money measure keeps its currency width (#30126 item 7)', () => { + it('a whole CNY amount keeps its cents, as the record shows it', () => { + expect(formatMeasure(1293, undefined, 'CNY', undefined, 'zh-CN')).toBe('¥1,293.00'); + }); + + it('a half-cent amount is not shortened', () => { + expect(formatMeasure(1280.5, undefined, 'CNY', undefined, 'zh-CN')).toBe('¥1,280.50'); + }); + + it('the width is the currency\'s own: JPY has none, KWD has three', () => { + expect(formatMeasure(1293, undefined, 'JPY', undefined, 'en-US')).toBe('¥1,293'); + expect(formatMeasure(1.5, undefined, 'KWD', undefined, 'en-US')).toBe('KWD\u00a01.500'); + }); + + it('an authored pattern still states the width', () => { + expect(formatMeasure(1293, '0,0', 'CNY', undefined, 'zh-CN')).toBe('¥1,293'); + }); +}); diff --git a/ui/packages/core/src/utils/dataset-format.ts b/ui/packages/core/src/utils/dataset-format.ts index d48a8b9da89..4bd62cc8db5 100644 --- a/ui/packages/core/src/utils/dataset-format.ts +++ b/ui/packages/core/src/utils/dataset-format.ts @@ -388,10 +388,18 @@ export function formatMeasure( // No `style: 'currency'` here: `formatDisplayNumber` derives that from the // presence of `currency` itself, which is also what keeps its "money // always groups" policy in one place instead of two. + // + // With no `format`, the amount shows at the CURRENCY's own width (CNY 2, + // JPY 0, KWD 3), the width the list cell shows the same field at: `Intl` + // applies it when no fraction bound is passed. A range here (0 to 2) let + // `Intl` print the shortest form, so `1293.00` read `¥1,293` and + // `1280.50` read `¥1,280.5` beside `¥1,280.50` on the record. An authored + // pattern still states its own width. return formatNumberInLocale(v, locale, { currency, - minimumFractionDigits: decimals ?? 0, - maximumFractionDigits: decimals ?? 2, + ...(decimals === undefined + ? {} + : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }), }); } catch { // Unknown currency code → fall through to plain number formatting. diff --git a/ui/packages/i18n/src/__tests__/i18n.test.ts b/ui/packages/i18n/src/__tests__/i18n.test.ts index b9deb68bea3..84f79d79967 100644 --- a/ui/packages/i18n/src/__tests__/i18n.test.ts +++ b/ui/packages/i18n/src/__tests__/i18n.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; -import { I18N_PROBE_FLAG } from '../i18n'; +import { I18N_PROBE_FLAG, CJK_LATIN_SPACED_KEYS, spaceLatinValueFromCjk } from '../i18n'; import { createI18n, getDirection, @@ -548,3 +548,41 @@ describe('@object-ui/i18n', () => { }); }); }); + +describe('zh titles space a Latin object name from the Han text around it (#30126 item 1)', () => { + const zh = () => createI18n({ defaultLanguage: 'zh', detectBrowserLanguage: false }); + + it('a Latin label is spaced from 新建 / 编辑 / 查看 / 修改', () => { + const i18n = zh(); + expect(i18n.t('form.createTitle', { object: 'Repair Ticket' })).toBe('新建 Repair Ticket'); + expect(i18n.t('form.editTitle', { object: 'Repair Ticket' })).toBe('编辑 Repair Ticket'); + expect(i18n.t('form.viewTitle', { object: 'Repair Ticket' })).toBe('查看 Repair Ticket'); + expect(i18n.t('console.ai.recordWriteCreateTitle', { object: 'Repair Ticket' })).toBe('新建 Repair Ticket'); + expect(i18n.t('console.ai.recordWriteUpdateTitle', { object: 'Repair Ticket' })).toBe('修改 Repair Ticket'); + }); + + it('a Chinese label keeps the pinned unspaced title', () => { + expect(zh().t('form.createTitle', { object: '维修工单' })).toBe('新建维修工单'); + }); + + it('is opt-in by key: a key outside the table renders as authored', () => { + expect(CJK_LATIN_SPACED_KEYS['form.createSuccess']).toBeUndefined(); + expect(zh().t('form.createSuccess', { object: 'Repair Ticket' })).toBe('Repair Ticket创建成功'); + }); + + it('touches no other language', () => { + const ja = createI18n({ defaultLanguage: 'ja', detectBrowserLanguage: false }); + expect(ja.t('form.createTitle', { object: 'Repair Ticket' })).toBe('Repair Ticketを作成'); + const en = createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false }); + expect(en.t('form.createTitle', { object: 'Repair Ticket' })).toBe('Create Repair Ticket'); + }); + + it('spaces each side by its own edge character', () => { + expect(spaceLatinValueFromCjk('新建Repair Ticket', 'Repair Ticket')).toBe('新建 Repair Ticket'); + expect(spaceLatinValueFromCjk('Repair Ticket创建成功', 'Repair Ticket')).toBe('Repair Ticket 创建成功'); + expect(spaceLatinValueFromCjk('新建2026预算', '2026预算')).toBe('新建 2026预算'); + expect(spaceLatinValueFromCjk('新建预算A', '预算A')).toBe('新建预算A'); + expect(spaceLatinValueFromCjk('新建 Repair Ticket', 'Repair Ticket')).toBe('新建 Repair Ticket'); + expect(spaceLatinValueFromCjk('新建“Repair Ticket”', 'Repair Ticket')).toBe('新建“Repair Ticket”'); + }); +}); diff --git a/ui/packages/i18n/src/i18n.ts b/ui/packages/i18n/src/i18n.ts index eae9daced63..735277506cc 100644 --- a/ui/packages/i18n/src/i18n.ts +++ b/ui/packages/i18n/src/i18n.ts @@ -175,6 +175,73 @@ export function pickInitialLanguage(config: I18nConfig = {}): string { return known ? browserLang : defaultLanguage; } +/** + * The keys whose interpolated object name is spaced from the Chinese text + * around it, and the option that carries the name. Opt-in by key: every other + * key, and every static string, renders exactly as authored. + * + * A Chinese title such as `新建{{object}}` reads `新建联系人` for a translated + * label, which is right, and `新建Repair Ticket` for a label with no Chinese + * translation, which is not: Chinese typesetting puts a space between Han text + * and a Latin word. The space is decided by the VALUE, at render time, because + * the pack cannot know which label it will meet. The pack keeps the plain + * `{{object}}` spelling (no format spec), the one spelling the provider-less + * fallback interpolator can also resolve. + */ +export const CJK_LATIN_SPACED_KEYS: Readonly> = { + 'form.createTitle': 'object', + 'form.editTitle': 'object', + 'form.viewTitle': 'object', + 'console.ai.recordWriteCreateTitle': 'object', + 'console.ai.recordWriteUpdateTitle': 'object', +}; + +/** The languages whose packs the spacing applies to. */ +const CJK_LATIN_SPACED_LANGUAGES: ReadonlySet = new Set(['zh']); + +const CJK_CHAR = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u; +const LATIN_OR_DIGIT = /[\p{Script=Latin}\p{Nd}]/u; + +/** + * Put one space between `value` and a CJK character it touches in `text`, on + * each side where `value`'s edge character is a Latin letter or a digit. + * `新建Repair Ticket` → `新建 Repair Ticket`; `新建联系人` is unchanged, and so + * is a side that already has a space or punctuation. + */ +export function spaceLatinValueFromCjk(text: string, value: string): string { + if (!value || !text.includes(value)) return text; + const chars = Array.from(value); + const padStart = LATIN_OR_DIGIT.test(chars[0]); + const padEnd = LATIN_OR_DIGIT.test(chars[chars.length - 1]); + if (!padStart && !padEnd) return text; + const parts = text.split(value); + let out = parts[0]; + for (let i = 1; i < parts.length; i += 1) { + const before = Array.from(out).pop() ?? ''; + const after = Array.from(parts[i])[0] ?? ''; + out += (padStart && CJK_CHAR.test(before) ? ' ' : '') + value + (padEnd && CJK_CHAR.test(after) ? ' ' : '') + parts[i]; + } + return out; +} + +/** The i18next post-processor that applies {@link CJK_LATIN_SPACED_KEYS}. */ +const CJK_LATIN_SPACING_PROCESSOR = 'objectui-cjk-latin-spacing'; + +const cjkLatinSpacingProcessor = { + type: 'postProcessor' as const, + name: CJK_LATIN_SPACING_PROCESSOR, + process(value: string, keys: string | string[], options: Record, translator: { language?: string }): string { + if (typeof value !== 'string') return value; + const key = Array.isArray(keys) ? keys[0] : keys; + const option = typeof key === 'string' ? CJK_LATIN_SPACED_KEYS[key] : undefined; + if (!option) return value; + const lng = typeof options?.lng === 'string' ? options.lng : translator?.language; + if (!lng || !CJK_LATIN_SPACED_LANGUAGES.has(lng.split('-')[0])) return value; + const name = options?.[option]; + return typeof name === 'string' ? spaceLatinValueFromCjk(value, name) : value; + }, +}; + /** * Create and initialize an i18next instance with Object UI defaults */ @@ -229,10 +296,11 @@ export function createI18n(config: I18nConfig = {}): I18nInstance { // technically still "initializing" on the very first render in StrictMode), // which unmounts the entire App subtree — including ConditionalAuthWrapper, // so the discovery fetch never runs and the splash never appears. - instance.use(initReactI18next).init({ + instance.use(initReactI18next).use(cjkLatinSpacingProcessor).init({ lng, fallbackLng: fallbackLanguage, resources: mergedResources, + postProcess: [CJK_LATIN_SPACING_PROCESSOR], interpolation: { escapeValue: false, // React already escapes ...interpolation, diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 4a5ddd00405..a73a9f870c9 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -162,6 +162,7 @@ const ar = { notAvailableHere: '"{{action}}" غير متاح في الصفحة الحالية.', notAvailableForRecord: 'غير متاح لهذا السجل', completedSuccessfully: 'اكتمل الإجراء بنجاح', + completedNamed: 'اكتمل الإجراء: {{action}}', failed: 'فشل الإجراء', parallelFailed: 'فشل إجراء متوازٍ واحد أو أكثر', selectExactlyOneRow: 'يُنفَّذ هذا الإجراء على سجل واحد — حدّد صفًا واحدًا فقط.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 767d5c6e4f4..6ae7431109e 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -148,6 +148,7 @@ const de = { notAvailableHere: '„{{action}}“ ist auf der aktuellen Seite nicht verfügbar.', notAvailableForRecord: 'Für diesen Datensatz nicht verfügbar', completedSuccessfully: 'Aktion erfolgreich abgeschlossen', + completedNamed: 'Aktion abgeschlossen: {{action}}', failed: 'Aktion fehlgeschlagen', parallelFailed: 'Eine oder mehrere parallele Aktionen sind fehlgeschlagen', selectExactlyOneRow: 'Diese Aktion gilt für einen einzelnen Datensatz – wählen Sie genau eine Zeile aus.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 7b0c30e7a19..a53d60f867b 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -177,6 +177,8 @@ const en = { // the server's message plays no part (objectui#11344). It is the one // success-toast text the runner writes itself (objectui#10900). completedSuccessfully: 'Action completed successfully', + // The same toast for an action that has a label: it names what was done. + completedNamed: '{{action}} completed', // The runner's other own text (objectui#10969): the error fallbacks when no // readable error message reached it, and the Undo label it hands the toast // handler for an undoable success toast. diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 1634040c682..241d808dd91 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -150,6 +150,7 @@ const es = { notAvailableHere: '«{{action}}» no está disponible en la página actual.', notAvailableForRecord: 'No disponible para este registro', completedSuccessfully: 'La acción se completó correctamente', + completedNamed: 'Acción completada: {{action}}', failed: 'La acción falló', parallelFailed: 'Una o más acciones paralelas fallaron', selectExactlyOneRow: 'Esta acción se ejecuta sobre un solo registro: seleccione exactamente una fila.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5b372551b78..8b9cf436f0e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -150,6 +150,7 @@ const fr = { notAvailableHere: '« {{action}} » n\'est pas disponible sur la page actuelle.', notAvailableForRecord: 'Non disponible pour cet enregistrement', completedSuccessfully: 'Action effectuée avec succès', + completedNamed: 'Action effectuée : {{action}}', failed: "Échec de l'action", parallelFailed: 'Une ou plusieurs actions parallèles ont échoué', selectExactlyOneRow: 'Cette action porte sur un seul enregistrement — sélectionnez exactement une ligne.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e7d4d57c413..ef47233e922 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -148,6 +148,7 @@ const ja = { notAvailableHere: '「{{action}}」は現在のページでは利用できません。', notAvailableForRecord: 'このレコードでは利用できません', completedSuccessfully: '操作が正常に完了しました', + completedNamed: '「{{action}}」が完了しました', failed: '操作に失敗しました', parallelFailed: '1 つ以上の並列操作が失敗しました', selectExactlyOneRow: 'この操作は 1 件のレコードに対して実行されます。行を 1 つだけ選択してください。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index d3a23a78f85..6beae7b1649 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -148,6 +148,7 @@ const ko = { notAvailableHere: '"{{action}}"은(는) 현재 페이지에서 사용할 수 없습니다.', notAvailableForRecord: '이 레코드에서는 사용할 수 없습니다', completedSuccessfully: '작업이 완료되었습니다', + completedNamed: '{{action}} 완료', failed: '작업 실패', parallelFailed: '하나 이상의 병렬 작업이 실패했습니다', selectExactlyOneRow: '이 작업은 단일 레코드에서 실행됩니다. 행을 하나만 선택하세요.', diff --git a/ui/packages/i18n/src/locales/pt.ts b/ui/packages/i18n/src/locales/pt.ts index 7acee1e94fb..665339cbbdd 100644 --- a/ui/packages/i18n/src/locales/pt.ts +++ b/ui/packages/i18n/src/locales/pt.ts @@ -150,6 +150,7 @@ const pt = { notAvailableHere: '"{{action}}" não está disponível na página atual.', notAvailableForRecord: 'Não disponível para este registro', completedSuccessfully: 'A ação foi concluída com sucesso', + completedNamed: 'Ação concluída: {{action}}', failed: 'A ação falhou', parallelFailed: 'Uma ou mais ações paralelas falharam', selectExactlyOneRow: 'Esta ação é executada em um único registro — selecione exatamente uma linha.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index adfac04129b..07519b37578 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -155,6 +155,7 @@ const ru = { notAvailableHere: '«{{action}}» недоступно на текущей странице.', notAvailableForRecord: 'Недоступно для этой записи', completedSuccessfully: 'Действие успешно выполнено', + completedNamed: 'Действие выполнено: {{action}}', failed: 'Действие не выполнено', parallelFailed: 'Одно или несколько параллельных действий не выполнены', selectExactlyOneRow: 'Это действие выполняется для одной записи — выберите ровно одну строку.', diff --git a/ui/packages/i18n/src/locales/zh.ts b/ui/packages/i18n/src/locales/zh.ts index 1309427f155..842f3ccba42 100644 --- a/ui/packages/i18n/src/locales/zh.ts +++ b/ui/packages/i18n/src/locales/zh.ts @@ -153,6 +153,7 @@ const zh = { notAvailableHere: '「{{action}}」在当前页面不可用。', notAvailableForRecord: '对此记录不可用', completedSuccessfully: '操作已成功完成', + completedNamed: '“{{action}}”已完成', failed: '操作失败', parallelFailed: '一个或多个并行操作失败', selectExactlyOneRow: '此操作针对单条记录,请只选择一行。', diff --git a/ui/packages/plugin-dashboard/src/MetricWidget.tsx b/ui/packages/plugin-dashboard/src/MetricWidget.tsx index 5b035158b64..a04ad3b8787 100644 --- a/ui/packages/plugin-dashboard/src/MetricWidget.tsx +++ b/ui/packages/plugin-dashboard/src/MetricWidget.tsx @@ -138,11 +138,16 @@ function formatMetricValue( if (isCurrency) { const code = currency || symbolMap[trimmed[0]] || 'USD'; try { + // With no pattern the amount keeps the CURRENCY's own width (CNY 2, + // JPY 0), which `Intl` applies when no fraction bound is passed: the + // width the list cell shows the same amount at. A pattern is the + // author's declaration and states its own (`'$0,0'` → 0). return formatDisplayNumber(value as number, { locale, currency: code, - minimumFractionDigits: decimals, - maximumFractionDigits: decimals, + ...(trimmed === '' + ? {} + : { minimumFractionDigits: decimals, maximumFractionDigits: decimals }), }); } catch { return `${code} ${(value as number).toFixed(decimals)}`; diff --git a/ui/packages/plugin-dashboard/src/__tests__/MetricWidget.numberFormat.test.tsx b/ui/packages/plugin-dashboard/src/__tests__/MetricWidget.numberFormat.test.tsx index a2332ae3bbe..f2e6ddb81b2 100644 --- a/ui/packages/plugin-dashboard/src/__tests__/MetricWidget.numberFormat.test.tsx +++ b/ui/packages/plugin-dashboard/src/__tests__/MetricWidget.numberFormat.test.tsx @@ -51,7 +51,8 @@ describe('MetricWidget — grouping stays load-bearing (objectui#4033 exception) it('keeps grouping for a currency metric', () => { renderMetric({ value: 1930000, currency: 'USD' }, 'en-US'); - expect(screen.getByText('$1,930,000')).toBeInTheDocument(); + // At the currency's own width (#30126 item 7): no pattern states another. + expect(screen.getByText('$1,930,000.00')).toBeInTheDocument(); }); }); @@ -68,8 +69,8 @@ describe('MetricWidget — active display locale (objectui#4033 fix 3)', () => { it('localizes a currency metric too', () => { renderMetric({ value: 1930000, currency: 'EUR' }, 'de-DE'); - // de-DE puts the symbol last; en-US would have produced "€1,930,000". - expect(screen.getByText(/^1\.930\.000\s*€$/)).toBeInTheDocument(); + // de-DE puts the symbol last; en-US would have produced "€1,930,000.00". + expect(screen.getByText(/^1\.930\.000,00\s*€$/)).toBeInTheDocument(); }); it('localizes the compact notation path', () => { @@ -79,3 +80,25 @@ describe('MetricWidget — active display locale (objectui#4033 fix 3)', () => { expect(screen.getByText(/Mio/)).toBeInTheDocument(); }); }); + +describe('MetricWidget — a currency card with no pattern keeps the currency width (#30126 item 7)', () => { + it('a whole CNY amount keeps its cents', () => { + renderMetric({ value: 1293, currency: 'CNY' }, 'zh-CN'); + expect(screen.getByText('¥1,293.00')).toBeInTheDocument(); + }); + + it('cents are not rounded away', () => { + renderMetric({ value: 1280.5, currency: 'CNY' }, 'zh-CN'); + expect(screen.getByText('¥1,280.50')).toBeInTheDocument(); + }); + + it('JPY has no minor unit, so none is drawn', () => { + renderMetric({ value: 1293, currency: 'JPY' }, 'en-US'); + expect(screen.getByText('¥1,293')).toBeInTheDocument(); + }); + + it("an authored pattern is the author's width", () => { + renderMetric({ value: 1280.5, currency: 'CNY', format: '0,0' }, 'zh-CN'); + expect(screen.getByText('¥1,281')).toBeInTheDocument(); + }); +});