Skip to content
Merged
16 changes: 16 additions & 0 deletions .changeset/30126-console-copy-titles-toast-money.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<unknown>;

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<string, unknown>, language?: string) {
let handler: Handler | null = null;
const harness = (
<MetadataCtx.Provider value={metadata}>
<Harness onReady={(h) => { handler = h; }} />
</MetadataCtx.Provider>
);
render(language ? <I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }}>{harness}</I18nProvider> : 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();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
23 changes: 18 additions & 5 deletions ui/packages/app-shell/src/hooks/useActionModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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 = (
<ModalForm
schema={{
Expand All @@ -281,7 +294,7 @@ export function useActionModal(dataSource?: any) {
objectName: d.objectName,
mode: formMode,
recordId: d.recordId,
title: d.title,
title,
description: d.description,
fields: d.fields,
...viewLayout,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,8 @@ describe('objectui#12331 — a record-scoped script action at list_toolbar, with
await tickRows(1);
await launchFromHeader();

expect(await screen.findByText('Action completed successfully', undefined, { timeout: 5000 })).toBeInTheDocument();
// The runner's default line names the labelled action (#30126).
expect(await screen.findByText('Add to Campaign completed', undefined, { timeout: 5000 })).toBeInTheDocument();
expect(actionCalls()).toHaveLength(1);
});
});
Expand All @@ -296,7 +297,8 @@ describe('objectui#12331 — the refusal follows the `locations` declaration', (
await tickRows(0);
await launchFromHeader();

expect(await screen.findByText('Action completed successfully', undefined, { timeout: 5000 })).toBeInTheDocument();
// The runner's default line names the labelled action (#30126).
expect(await screen.findByText('Add to Campaign completed', undefined, { timeout: 5000 })).toBeInTheDocument();
expect(actionCalls()).toHaveLength(1);
expect(postedBody(0)).toEqual({ params: { campaign: 'cmp_webinar' } });
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ const RECORD_ID = 'case-41';
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 };
Expand Down
6 changes: 4 additions & 2 deletions ui/packages/app-shell/src/views/RecordFormPage.i18n.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,10 @@ describe('RecordFormPage title resolves from the locale packs (#3469)', () => {
// 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');
});
});

Expand Down
42 changes: 38 additions & 4 deletions ui/packages/core/src/actions/ActionRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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',
Expand All @@ -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, string>) => string;

/**
* Modal handler — consumers provide to render modal dialogs.
*/
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -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);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ToastHandler>;

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<string, string>) =>
`“${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' }));
});
});
19 changes: 19 additions & 0 deletions ui/packages/core/src/utils/__tests__/dataset-format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
Loading
Loading