Skip to content

Commit 82838e8

Browse files
fix(fields): a read-only record-mode amount with homeAmount shows the live home-amount preview in an editable form (#33296)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XGdQDG3Qbiw4wgeGVbMvF55)_ Fixes #32941 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:编辑表单里,一个声明了 `homeAmount` 的记录币种金额即使被画成只读(例如由 `expression` 计算的发票总额),金额下面也会显示「≈ 本位币金额 at 汇率 on 日期」的实时预览,改币种或单据日期时跟着变。只读表单(查看模式)和记录详情页不显示这一行。 - 为什么改:showcase 发票的 `amount` 是表达式计算字段,表单把它画成只读,而只读分支在挂载预览之前就返回了,所以编辑发票时完全看不到保存后会存多少本位币金额。测试清单 `records-forms.home-amount-preview-states` 和 `records-forms.multi-currency-invoice` acceptance[5] 都要求这一行。 - 风险与回滚:只改 `@object-ui/fields` 里 `CurrencyField` 只读分支的一个条件分支,复用已有的 `HomeAmountPreview` 和已有的 `fields.currencyHome.*` 文案;不改 spec、不改服务端、不加属性和文案。回滚即 revert。 - 先看:`ui/packages/fields/src/widgets/CurrencyField.tsx` 只读分支里新增的 `if (!props.disabled && … homeAmount)` 块;`ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx` 末尾新增的 `objectstack#32941` describe。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx packages/plugin-detail/src/__tests__/DetailSection.homeAmount-27196.test.tsx`,预期 3 个文件 21 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes - **`CurrencyField`'s read-only face** (`ui/packages/fields/src/widgets/CurrencyField.tsx`, `@object-ui/fields`). The read-only branch used to return the formatted amount and nothing else, so `HomeAmountPreview` was mounted on the editable face only. It now mounts the same `HomeAmountPreview` under the amount when the field is a `record`-mode amount declaring `homeAmount` (ADR-0144 D5) and the widget is not `disabled`. The amount span is unchanged; for such a field it sits in a `div.space-y-1` beside the preview line, the editable face's own wrapper. Every other read-only currency (no `homeAmount`, or not `record` mode) returns the same single span as before. - **How the read-only face tells an editable form from a read-only view (measured, as the order asked):** - The edit form reaches this branch for a computed amount through `readonly: true` (`ObjectForm`'s `isExpressionComputedField` stamp and `sectionFields.ts`'s, unchanged), with `disabled` false except while a submit is in flight. The form renderer (`renderFieldComponent` in `ui/packages/components/src/renderers/form/form.tsx`) hands the currency widget the live form record as `dependentValues` (`RECORD_CURRENCY_WIDGET_TYPES`), which is what the preview reads the currency and document date from, so a change in the form re-renders the line. - A read-only form (`mode: 'view'` or `readOnly`) stamps `disabled: true` on every field (`generateField` in `ObjectForm.tsx` and `fromObjectSchema` in `sectionFields.ts`), so `!disabled` keeps the preview off it. Its home field already shows "Converted at RATE on DATE". - The record detail page never mounts `CurrencyField`: `DetailSection` and the highlights strip draw `currency` through `getCellRenderer`, which is `CurrencyCellRenderer`, unchanged. So the detail page keeps exactly one line, the home field's hint. - **Changeset** `.changeset/32941-readonly-amount-home-preview.md`: `@object-ui/fields` patch, both declaration lines. ## Tests - `ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx`, new describe for objectstack#32941: - a `readonly` record-mode amount (EUR 450, 2026-11-12, home CNY) draws no input and the line "≈ CN¥500.00 at 0.9 on Nov 12, 2026" with `data-state="converted"`; re-rendered with JPY and 2026-01-15 it reads "≈ CN¥2.97 at 151.5 on Jan 15, 2026"; with the date cleared it reads the awaiting-date line with `data-state="awaitingDate"`. - CONTROL: a `readonly` and `disabled` face, and a `readonly` record-mode amount with no `homeAmount`, draw the amount alone and read no rate. - `ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx`, new describe, through a rendered `ObjectForm` whose `amount` carries an `expression` (the showcase invoice's shape): - edit mode: the amount row has no input and its preview reads "≈ $500.00 at 0.9 on Nov 12, 2026", `data-state="converted"`. Typing 01/15/2026 into the form's own date box and leaving it moves the line to "≈ $489.13 at 0.92 on Jan 15, 2026"; picking JPY in the form's own currency select moves it to "≈ $2.97 at 151.5 on Jan 15, 2026". - CONTROL: the same object in view mode draws the amount (`€450.00`) with no preview, and the home field keeps "Converted at 0.9 on Nov 12, 2026". - `ui/packages/plugin-detail/src/__tests__/DetailSection.homeAmount-27196.test.tsx`, new describe: CONTROL, the record page with the expression-computed amount shows one "Converted at" line (on the home row) and no preview. - Ablations through `scripts/ablation-replace.mjs`, each restored to the HEAD blob with `git diff HEAD` empty. `@object-ui/fields` resolves to `packages/fields/src` through `ui/vitest.config.mts`'s alias, so no build sat between mutation and run. - The new branch's condition replaced with `false as boolean` (anchor 1 to 0, blob `9f82c708` to `3aea6a75`): 2 failed, 16 passed (18). Red: the widget's read-face preview case and the edit-form case. Every CONTROL green. - The `!props.disabled &&` gate dropped (blob `9f82c708` to `5d03c47f`): 2 failed, 16 passed (18). Red: the widget's disabled CONTROL and the view-mode form CONTROL. ## Acceptance notes - **The preview leaves the read-only face while a save is in flight.** The form renderer sets `disabled` on every field during `isSubmitting`, and the widget cannot tell that window from a read-only form, so the line under a read-only amount disappears for that moment and returns if the save fails. The editable face keeps its line during submit. No new prop was added to tell the two apart: a host-produced form-context key would be a widget-contract change for a transient. - **Pre-existing, unchanged:** the editable face already mounts the preview under a `disabled` input, so on a view-mode form a record-mode amount that is not computed still shows the line. This PR does not touch the editable face (the order keeps it unchanged); named here, not filed. - **Live console check not run.** The reproduction on the showcase invoice INV-1004 was not driven in a browser; the rendered `ObjectForm` test above drives the same field shape through the real form renderer, date box and currency select. - **Declaration lines measured on the diff:** no prop, export, schema key or translation key is added or removed; the preview's `fields.currencyHome.*` strings already exist. `Clause-②: no`, `Metadata-protocol: none`, as the claim opened. ## Verification Run on head `fc89ce51` (base `origin/main` `d4fbb4db`). `origin/main` moved to `9f736f2e` before this PR opened; its 42 files touch nothing under `ui/` (spec, lint, mcp, runtime, services, docs), so the branch was not merged and CI's merge ref carries the combination. <details><summary>Build, tests and lint</summary> - Build under the verify lock: `pnpm --workspace-concurrency=2 --filter '@objectstack/spec...' --filter '@objectstack/formula...' --filter '@objectstack/client...' --filter '@objectstack/lint...' --filter '@objectstack/sdui-parser...' build`: VERDICT command-exit 0. - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/fields/` plus the four related files (`CurrencyConfigField.recordMode-27188`, `DetailSection.homeAmount-27196`, `sectionFormHomeAmount-27196`, `objectFormExpressionComputed-31759`) under the lock: VERDICT command-exit 0, Test Files 309 passed, 1 skipped (310), Tests 4645 passed, 7 skipped (4652). - eslint on the four changed source and test files: exit 0 (0 errors). `pnpm --dir ui run check:new-line-citations`: 0 new citations, exit 0. - `@object-ui/fields` `type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`) after `pnpm --filter '@object-ui/fields^...' build`, under the lock: VERDICT command-exit 0. </details> <details><summary>Derived gates (36)</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 36 families on this diff. On head `fc89ce51` all 36 exited 0, among them `pnpm --dir ui exec vitest run scripts/`, `pnpm check:test-source-alias` and `pnpm check:type-check-debt`. `--ran` reconciliation with exit codes recorded: 36 derived, 36 run, 0 NOT-MEASURED (a derived zero), 0 UNRUN. Changed lines: 154 (+152 / -2, 5 files), under the 3,000 threshold. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5mWLGqDtxv15E7gTTF --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5mWLGqDtxv15E7gTTF)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 4c9104e commit 82838e8

5 files changed

Lines changed: 152 additions & 2 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): a read-only record-mode amount that declares `homeAmount` shows the live home-amount preview in an editable form
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A `record`-mode amount that declares `homeAmount` (ADR-0144 D5) draws the "≈ AMOUNT at RATE on DATE" line under it while the record is edited. The line was mounted on the widget's editable face only, so an amount the form draws read-only lost it. The showcase invoice's `amount` is computed by an `expression`, and the form draws such a field read-only, so its edit form had no preview at all, whatever the currency or document date.
11+
12+
`CurrencyField`'s read-only face now mounts the same preview when the field is not `disabled`, so it follows a changed currency or document date before save. A read-only form (`mode: 'view'` or `readOnly`) disables every field and shows no preview: it has no save, and its home field already says the rate and date the engine used. The record page draws the amount with the cell renderer, which is unchanged, so it still shows the stored conversion once, under the home field. No new prop, no new translation key: the preview and its `fields.currencyHome.*` strings are the ones the editable face already uses.

‎ui/packages/fields/src/__tests__/homeAmountPreview-27196.test.tsx‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,45 @@ describe('the live home-amount preview (ADR-0144 D5)', () => {
151151
expect(ds.calls).toHaveLength(0);
152152
});
153153
});
154+
155+
describe('the read-only face of a record-mode amount carries the same preview (objectstack#32941)', () => {
156+
// An `expression`-computed amount reaches the widget `readonly` in an edit
157+
// form; the save still re-stores its home amount at the form's currency and
158+
// document date, so the line is owed there too.
159+
function readonlyPreview(record: Record<string, unknown>, ds: unknown, extra: { disabled?: boolean } = {}) {
160+
return (
161+
<LocalizationProvider value={{ locale: 'en-US', currency: 'CNY' }}>
162+
<CurrencyField value={record.amount as number} onChange={() => {}} field={AMOUNT} readonly {...extra} dependentValues={record} dataSource={ds} />
163+
</LocalizationProvider>
164+
);
165+
}
166+
167+
it('draws the amount as text, no input, with the converted line, and follows a changed currency and date', async () => {
168+
const ds = rates({ EUR: [['2025-01-01', 0.92], ['2026-10-01', 0.9]], JPY: [['2025-01-01', 151.5]] });
169+
const record = { amount: 450, currency_code: 'EUR', invoice_date: '2026-11-12' };
170+
const view = render(readonlyPreview(record, ds));
171+
expect(screen.queryByRole('spinbutton')).toBeNull();
172+
await waitFor(() => expect(line()).toBe('≈ CN¥500.00 at 0.9 on Nov 12, 2026'));
173+
expect(screen.getByTestId('home-amount-preview')).toHaveAttribute('data-state', 'converted');
174+
view.rerender(readonlyPreview({ ...record, currency_code: 'JPY', invoice_date: '2026-01-15' }, ds));
175+
await waitFor(() => expect(line()).toBe('≈ CN¥2.97 at 151.5 on Jan 15, 2026'));
176+
view.rerender(readonlyPreview({ ...record, invoice_date: '' }, ds));
177+
expect(line()).toBe('Set the document date to see the home amount');
178+
expect(screen.getByTestId('home-amount-preview')).toHaveAttribute('data-state', 'awaitingDate');
179+
});
180+
181+
it('CONTROL: a disabled read-only face (a view-mode form) and a read-only amount with no homeAmount draw the amount alone and read nothing', async () => {
182+
const ds = rates({ EUR: [['2025-01-01', 0.92]] });
183+
const record = { amount: 450, currency_code: 'EUR', invoice_date: '2026-11-12' };
184+
render(readonlyPreview(record, ds, { disabled: true }));
185+
render(
186+
<LocalizationProvider value={{ locale: 'en-US', currency: 'CNY' }}>
187+
<CurrencyField value={450} onChange={() => {}} field={{ ...AMOUNT, currencyConfig: { currencyMode: 'record', currencyField: 'currency_code' } }} readonly dependentValues={record} dataSource={ds} />
188+
</LocalizationProvider>,
189+
);
190+
await new Promise((r) => setTimeout(r, 0));
191+
expect(screen.queryAllByTestId('home-amount-preview')).toHaveLength(0);
192+
expect(ds.calls).toHaveLength(0);
193+
expect(document.body.textContent?.replace(/\u00a0/g, ' ')).toContain('€450.00€450.00');
194+
});
195+
});

‎ui/packages/fields/src/widgets/CurrencyField.tsx‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,27 @@ export function CurrencyField({ value, onChange, field, readonly, error, classNa
7777
// apart on a whole amount (`$3,456.00` here, `$3,456` in the cell) until
7878
// triage ruled the declared width the protocol's convention and the cell's
7979
// whole-amount trimming retired.
80-
return (
80+
const amount = (
8181
<span className="text-sm font-medium tabular-nums">
8282
{formatCurrency(Number(value), currency, locale)}
8383
</span>
8484
);
85+
// A read-only record-mode amount declaring `homeAmount` (ADR-0144 D5), an
86+
// `expression`-computed one included, still has its home amount re-stored
87+
// when the form's currency or document date changes, so it carries the
88+
// same live preview as the editable face. Only while the field is not
89+
// `disabled`: a read-only form (`mode: 'view'`, `readOnly`) disables every
90+
// field, has no save to preview, and its home field already says what the
91+
// engine stored. The record page draws the cell renderer, not this widget.
92+
if (!props.disabled && currencyField?.currencyConfig?.currencyMode === 'record' && currencyField.currencyConfig.homeAmount) {
93+
return (
94+
<div className="space-y-1">
95+
{amount}
96+
<HomeAmountPreview field={currencyField} amount={value} record={record} dataSource={dataSource} />
97+
</div>
98+
);
99+
}
100+
return amount;
85101
}
86102

87103
/**

‎ui/packages/plugin-detail/src/__tests__/DetailSection.homeAmount-27196.test.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,16 @@ describe('DetailSection: the home field (ADR-0144 D5)', () => {
5454
expect(hints(page({ currency_code: 'CNY', amount: 500, amount_home: 500, amount_rate: 1, total: 3 }))).toEqual(['In the home currency (rate 1)']);
5555
});
5656
});
57+
58+
describe('DetailSection: no live preview under an expression-computed amount (objectstack#32941)', () => {
59+
it('CONTROL: the record page draws the stored conversion once, on the home row; the amount grows no "≈" line', () => {
60+
const computed = { ...objectSchema, fields: { ...objectSchema.fields, amount: { ...objectSchema.fields.amount, expression: 'record.total * 1.1' } } };
61+
const c = render(
62+
<LocalizationProvider value={{ locale: 'en-US', currency: 'CNY' }}>
63+
<DetailSection section={section} data={{ currency_code: 'EUR', invoice_date: '2026-11-01', amount: 10000, amount_home: 71994.24, amount_rate: 0.1389, total: 3 }} objectSchema={computed as any} onEnterInlineEdit={vi.fn()} />
64+
</LocalizationProvider>,
65+
).container;
66+
expect(hints(c)).toEqual(['Converted at 0.1389 on Nov 1, 2026']);
67+
expect(c.querySelector('[data-testid="home-amount-preview"]')).toBeNull();
68+
});
69+
});

‎ui/packages/plugin-form/src/__tests__/sectionFormHomeAmount-27196.test.tsx‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
* fields, the home field included (`filterSystemFields`), unchanged.
1717
*/
1818
import { describe, it, expect } from 'vitest';
19-
import { render, waitFor, cleanup } from '@testing-library/react';
19+
import { render, waitFor, cleanup, fireEvent } from '@testing-library/react';
20+
import '@testing-library/jest-dom';
2021
import { afterEach } from 'vitest';
2122
import React from 'react';
2223
import { LocalizationProvider } from '@object-ui/i18n';
@@ -101,3 +102,69 @@ describe('the live preview under the amount, through the form (ADR-0144 D5)', ()
101102
expect(finds).toEqual(['sys_exchange_rate']);
102103
});
103104
});
105+
106+
describe('an expression-computed record-mode amount keeps the live preview on its read face (objectstack#32941)', () => {
107+
// The showcase invoice's `amount`: an `expression` makes the form draw it
108+
// read-only (objectstack#31759), and the save still re-stores its home
109+
// amount at the currency and document date the form holds.
110+
const COMPUTED = { ...OBJ, fields: { ...OBJ.fields, amount: { ...OBJ.fields.amount, expression: 'record.subtotal * 1.1' }, subtotal: { type: 'number', label: 'Subtotal' } } };
111+
const EUR_ROW = { ...ROW, currency_code: 'EUR', invoice_date: '2026-11-12', amount: 450, subtotal: 409.09, amount_home: 500, amount_rate: 0.9 };
112+
const RATES: Record<string, Array<[string, number]>> = { EUR: [['2025-01-01', 0.92], ['2026-10-01', 0.9]], JPY: [['2025-01-01', 151.5]] };
113+
114+
function open(mode: 'edit' | 'view') {
115+
const ds = {
116+
getObjectSchema: async () => COMPUTED, findOne: async () => EUR_ROW, create: async () => EUR_ROW, update: async () => EUR_ROW,
117+
find: async (_resource: string, params: any) => {
118+
const { currency, effective_date } = params.$filter;
119+
const row = (RATES[currency] ?? []).filter(([d]) => d <= effective_date.$lte).sort(([a], [b]) => (a < b ? 1 : -1))[0];
120+
return { data: row ? [{ effective_date: row[0], rate: row[1] }] : [] };
121+
},
122+
};
123+
render(
124+
<SchemaRendererProvider dataSource={ds as any}>
125+
<LocalizationProvider value={{ locale: 'en-US', currency: 'USD' }}>
126+
<ObjectForm schema={{ type: 'object-form', objectName: 'fx_invoice', mode, recordId: 'r1', sections: [{ label: 'S', fields: ['currency_code', 'invoice_date', 'subtotal', 'amount', 'amount_home'] }] } as any} dataSource={ds as any} />
127+
</LocalizationProvider>
128+
</SchemaRendererProvider>,
129+
);
130+
}
131+
const amountRow = () => document.querySelector('[data-field="amount"]');
132+
const preview = () => amountRow()?.querySelector('[data-testid="home-amount-preview"]');
133+
134+
it('edit form: the amount draws read-only (no input) with the converted line, and follows a changed document date and currency', async () => {
135+
open('edit');
136+
await waitFor(() => {
137+
expect(preview()?.textContent?.replace(/\u00a0/g, ' ')).toBe('≈ $500.00 at 0.9 on Nov 12, 2026');
138+
}, { timeout: 5000 });
139+
expect(preview()).toHaveAttribute('data-state', 'converted');
140+
expect(amountRow()!.querySelector('input')).toBeNull();
141+
// The document date, typed into the form's own date box and committed.
142+
const date = document.querySelector('[data-field="invoice_date"] input') as HTMLInputElement;
143+
fireEvent.change(date, { target: { value: '01/15/2026' } });
144+
fireEvent.blur(date);
145+
await waitFor(() => {
146+
expect(preview()?.textContent?.replace(/\u00a0/g, ' ')).toBe('≈ $489.13 at 0.92 on Jan 15, 2026');
147+
}, { timeout: 5000 });
148+
// The currency, picked in the form's own currency select.
149+
fireEvent.click(document.querySelector('[data-field="currency_code"] [role="combobox"]')!);
150+
const jpy = await waitFor(() => {
151+
const option = Array.from(document.querySelectorAll('[role="option"]')).find((o) => o.textContent?.startsWith('JPY'));
152+
if (!option) throw new Error('no JPY option');
153+
return option as HTMLElement;
154+
}, { timeout: 5000 });
155+
fireEvent.click(jpy);
156+
await waitFor(() => {
157+
expect(preview()?.textContent?.replace(/\u00a0/g, ' ')).toBe('≈ $2.97 at 151.5 on Jan 15, 2026');
158+
}, { timeout: 5000 });
159+
});
160+
161+
it('CONTROL: the view-mode form draws the amount with no preview; the home field keeps its "Converted at" line', async () => {
162+
open('view');
163+
await waitFor(() => {
164+
expect(document.querySelector('[data-field="amount_home"] [data-testid="home-amount-hint"]')?.textContent).toBe('Converted at 0.9 on Nov 12, 2026');
165+
}, { timeout: 5000 });
166+
expect(amountRow()?.textContent?.replace(/\u00a0/g, ' ')).toContain('€450.00');
167+
await new Promise((r) => setTimeout(r, 20));
168+
expect(preview()).toBeFalsy();
169+
});
170+
});

0 commit comments

Comments
 (0)