Skip to content

Commit 18a7f60

Browse files
fix(fields): an untyped repeater edits its stored rows as JSON in the record form (#29269)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTEnFfLftKLAV7Uqry9LwhD)_ Fixes #29177 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:对象上的 `repeater` 字段(无类型 JSON 数组)在记录编辑表单里改用 JSON 编辑器显示和编辑,与旁边的 `composite`、`record` 一致;原来走的是明细行网格,没有列,只画出编号行。 - 为什么改:网格只画声明过的列,而 spec 规定 repeater 没有列,所以已存的 `[{label:'one',qty:1},…]` 在表单里看不到、也改不了。另一条路(按行的键推导列)实测会把 `qty` 存成字符串 `"5"`、把嵌套对象显示为 `[object Object]`,会丢数据,所以没选。 - 风险与回滚:只改别名表一行;repeater 在记录表单和 Studio 表单画布上不再占满整行(JSON 编辑器是普通宽度,与 composite 相同)。声明了列的明细行网格不变;行内编辑本来就排除 repeater,仍然排除。回滚即 revert 本 PR。 - 先看:`ui/packages/fields/src/field-type-alias.ts`(`repeater` 那一行),`ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx`,`ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.test.tsx`(宽度用例改指向)。 - 两分钟验证:`cd ui && pnpm exec vitest run packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx`,预期 4 个用例全绿;或在 showcase 的 Field Zoo「Specimen — Full」点 Edit,看到 "Repeater (embedded array)" 显示两行 JSON。 - 需要你做的:无,席位落地。 ## What changes `@objectstack/spec` declares `repeater` an untyped array of embedded JSON objects: `FieldSchema` has no sub-field or column member, the strict field schema refuses `columns` on it by name, and the `field/embedded-sub-fields` lint reports one. The form's alias table (`mapFieldTypeToFormType` in `ui/packages/fields/src/field-type-alias.ts`) still sent it to the line-items grid (`field:grid`). `GridField` draws only declared columns (`allColumns = cfg.columns || []`), so a stored repeater showed numbered rows with Duplicate and Remove and no cell, and Add line appended an empty object. The one table row changes: `repeater: 'field:grid'` becomes `repeater: 'field:object'`, the JSON editor (`ObjectField`) that `composite`, `record` and `json` already use. The edit form now shows the stored array as pretty-printed JSON, an edit saves an array of objects (never a string), and unparsable text is refused before the save. `GridField.tsx` is not touched. **Why the JSON editor and not derived columns.** The card offered both, and both were measured. Driving `GridField` with columns derived from the row keys (the shape a derived-columns fix would hand it) on rows `{label:'one',qty:1,meta:{color:'red'}}` and `{label:'two',qty:2,extra:true}`: the `meta` cell read `[object Object]`, the `extra` cell read the text `true`, and changing the `qty` cell to 5 emitted `qty: "5"`, a string. A derived grid therefore loses edits (type drift on every touched cell) or has to be read-only, and either way cannot show nested values. The JSON editor round-trips any value the spec allows, and it is the face the other two untyped containers already have, so the three behave alike. **What else moves, by consequence.** - Layout: `field:grid` is in the form's `WIDE_FIELD_TYPES`, `field:object` is not. A repeater is now laid out at normal width in the record form and on the Studio form canvas, like `composite`. The canvas resolves width through the same alias table, so the two still agree. `ObjectFormDesigner.test.tsx` case "spans a repeater field full-row" pinned the old width; it is repointed to assert the canvas matches the runtime resolution (`field:object`, not full-row). The seat accepted this file before it was edited. - Inline editing: unchanged. `repeater` stays excluded (`object` and `grid` are both in `INLINE_EXCLUDED_FIELD_TYPES`); `FieldEditWidget.test.ts` "the structured/computed spec spellings are closed corruption paths" is green unchanged. - Read side: unchanged. Record detail and the list cell (`RepeaterCellRenderer`, the row count) do not read the form alias. - A comment in `autoLayout.wideSpelling.test.ts` that described the repeater/grid width asymmetry as open is updated; that asymmetry no longer exists. **Repeaters that declare columns.** None exist to lose their grid: `git grep` for `type: 'repeater'` across the repo (examples, showcase, apps, tests, docs) and `objectstack-ai/hotcrm` found no object field that declares `columns`. The only hit carrying `columns` is the lint test that proves such a field is refused. The metadata-form `repeater` rows in `packages/spec/src/**/*.form.ts` are a different surface (Studio's `SchemaForm` `RepeaterField`), which does not read this alias table. ## Tests - New `ui/packages/plugin-form/src/ModalForm.untypedRepeater.test.tsx`, driven through the record Edit dialog (`ModalForm`, real registered widgets, a click on the real Update button), with the card's value `[{label:'one',qty:1},{label:'two',qty:2}]` and no columns: 1. the field shows "one", "two", 1 and 2, and no line-items grid; 2. an edit saves `f_repeater` as an array of objects with numeric `qty`, never a string; 3. an untouched save never writes the field as text; 4. control: a line-items grid that declares its columns still draws one input per column and writes a typed cell (`qty: 4`). - `ObjectFormDesigner.test.tsx`: the repeater width case is repointed as above. ## Acceptance notes - **Ablation.** Restoring `repeater: 'field:grid'` through `scripts/ablation-replace.mjs` (anchor 1 -> 0) turned cases 1-3 red; the control stayed green. Restored: blob == HEAD, `git diff HEAD` empty. - **Real browser, showcase field zoo: MEASURED.** Fresh showcase backend (`objectstack dev --seed-admin --fresh`) plus the Console Vite dev server on source, "Specimen — Full", Edit. With the alias row reverted: a full-width grid with header "#", rows 1 and 2 with Duplicate and Remove, a ghost row 3, Add line, no cell content. With this change: the field shows the two rows as JSON beside the composite and record editors; replacing the text with `[{"label":"one","qty":5},{"label":"three","qty":3}]` and clicking Update stored exactly that array of objects (read back through `GET /api/v1/data/showcase_field_zoo/ID`). Screenshots are kept with the card thread. - **No spec change.** The untyped shape stands as ruled on #25681. ## Verification Gate and suite readings at head `92297c74`; main `74a19dd8` was then merged (head `7393c5a0`). The merged commits touch `ui/packages/plugin-form` section fields and `packages/spec` record-page schemas, nothing this diff reads, and the scoped files below were re-run on `7393c5a0`. <details><summary>fields suite: 293 files green</summary> `cd ui && pnpm exec vitest run --maxWorkers=2 FILES`, under `os-verify-lock`, in three parts of `packages/fields`' 293 test files: 95 passed 1 skipped (1729 tests), 102 passed (1750 tests), 95 passed (920 tests); each VERDICT command-exit 0. </details> <details><summary>consumers and final-head re-run</summary> - The new test, `ModalForm.jsonField-11448`, the designer, autoLayout and inline-edit coverage tests, `form-field-widget-namespace`, the data-list, detail and `widget-dom-leak-sweep` files that type a field `repeater`: 15 files, 500 tests passed. - On `7393c5a0` after the merge: 10 files, 278 tests passed. </details> <details><summary>type-check and lint</summary> - `pnpm exec turbo run type-check --concurrency=2 --filter=@object-ui/fields --filter=@object-ui/plugin-form --filter=@object-ui/plugin-detail`: Tasks 50 successful, 50 total (each runs `tsc -p tsconfig.test.json` too). - `pnpm exec eslint` on the four touched source/test files: exit 0, 0 errors (6 `no-explicit-any` warnings on test casts, the sibling JSON-field test's shape). - `pnpm check:new-line-citations` (from `ui/`): 0 new citations. </details> <details><summary>derived gates: 34 of 34 exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 34 commands (the same list on the merged head); each ran and exited 0, including `node scripts/check-sdui-manifest.mjs`, the changeset gates, `pnpm check:type-check-debt` (0 raw tsc errors above ledger) and `pnpm --dir ui exec vitest run scripts/` (168 files passed; `check-hand-rolled-comment-mask.test.ts` timed out once at 15 s beside a locked run and passed alone, 22 of 22). `--ran` reconciliation: 34 derived, 34 run, 0 NOT-MEASURED, 0 UNRUN. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jQsK1ggWoa95TqasGU)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9e6df40 commit 18a7f60

5 files changed

Lines changed: 211 additions & 14 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): an untyped `repeater` field edits its stored rows as JSON in the record form
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A `repeater` field is an untyped array of embedded JSON objects: `@objectstack/spec` declares no sub-field or column member on it. The form's type table sent it to the line-items grid (`field:grid`), which draws only declared columns, so a stored `[{ label: 'one', qty: 1 }, …]` showed numbered rows with Duplicate and Remove buttons and no cell. The content could not be read or changed, and Add line appended an empty object.
11+
12+
`repeater` now resolves to the JSON editor (`field:object`) that `composite`, `record` and `json` already use. The record form shows the stored array as pretty-printed JSON, an edit saves an array of objects (never a string), and unparsable text is refused before the save. Inline editing stays excluded, as before. A line-items grid that declares its columns is unchanged.
13+
14+
The field is no longer laid out full-row in the record form and on the Studio form canvas: the JSON editor is a normal-width widget, like `composite` beside it. The read side (record detail, the list cell's row count) is unchanged. A list that needs typed columns is a child object whose `master_detail` field sets `inlineEdit: 'grid'`.

‎ui/packages/app-shell/src/views/studio-design/ObjectFormDesigner.test.tsx‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -280,12 +280,15 @@ describe('ObjectFormDesigner — emits the one legal `FormField.type` spelling (
280280
expect(toFormFieldType('field:markdown')).not.toBe('field:text');
281281
});
282282

283-
it('spans a `repeater` field full-row — the drift the raw pass hid', () => {
284-
// `repeater` is a spec `FieldType` that resolves to the WIDE `field:grid`
285-
// widget, but bare `repeater` is not one of `WIDE_FIELD_TYPES`' bare
286-
// members. Passing the raw object type in therefore matched nothing: the
287-
// canvas laid a repeater out at normal width while the runtime form —
288-
// which reaches the set through `mapFieldTypeToFormType` — spanned it.
283+
it('lays a `repeater` field out the way the runtime form resolves it', () => {
284+
// The canvas asks the width question through `mapFieldTypeToFormType`, the
285+
// runtime form's own resolution, so the two cannot drift. `repeater` is an
286+
// untyped JSON array in the spec and resolves to the JSON editor
287+
// (`field:object`) beside `composite` and `record`; that widget is not
288+
// wide, so the canvas lays it out at normal width, as the form does. (It
289+
// resolved to the WIDE line-items grid until that grid was found drawing
290+
// bare rows for a column-less repeater.)
291+
expect(toFormFieldType('repeater')).toBe('field:object');
289292
render(
290293
<ObjectFormDesigner
291294
draft={{ fields: [...textFields(15), { name: 'line_items', type: 'repeater', label: 'Line Items' }] }}
@@ -296,7 +299,7 @@ describe('ObjectFormDesigner — emits the one legal `FormField.type` spelling (
296299
);
297300
const card = screen.getByText('Line Items').closest('.cursor-grab') as HTMLElement;
298301
expect(card).toBeTruthy();
299-
expect(card.className).toContain('col-span-full');
302+
expect(card.className).not.toContain('col-span-full');
300303
});
301304

302305
it('keeps a bare rich-text field wide, and never shows the admin the widget id', () => {

‎ui/packages/fields/src/field-type-alias.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,19 +170,25 @@ export function mapFieldTypeToFormType(
170170
color: 'field:color',
171171
code: 'field:code',
172172
// A JSON value is edited as JSON — shown with `JSON.stringify`, saved
173-
// with `JSON.parse` — by the editor `object`, `composite` and `record`
174-
// below use (objectui#11448). It used to alias `field:code`, the raw-text
173+
// with `JSON.parse` — by the editor `object`, `composite`, `record` and
174+
// `repeater` below use (objectui#11448). It used to alias `field:code`, the raw-text
175175
// editor, which showed a stored object as `[object Object]` and saved an
176176
// edit as a string. `code` keeps the raw-text editor.
177177
json: 'field:object',
178178
qrcode: 'field:qrcode',
179179
vector: 'field:vector',
180180

181-
// Embedded structured values (stored as JSON on the row)
181+
// Embedded structured values (stored as JSON on the row). The spec
182+
// declares `composite`, `record` and `repeater` UNTYPED: no sub-field or
183+
// column member exists for a widget to read, so all three take the JSON
184+
// editor. `repeater` used to alias the line-items grid, which draws only
185+
// declared columns and so showed a stored array as bare numbered rows,
186+
// its content neither visible nor editable. A list that needs typed
187+
// columns is a child object edited with `inlineEdit: 'grid'`.
182188
object: 'field:object',
183189
composite: 'field:object', // embedded object
184190
record: 'field:object', // name-keyed map
185-
repeater: 'field:grid', // embedded array of rows
191+
repeater: 'field:object', // embedded array of objects
186192

187193
// Auto-generated/computed fields (typically read-only)
188194
formula: 'field:formula',

‎ui/packages/plugin-detail/src/__tests__/autoLayout.wideSpelling.test.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,8 @@ describe('detail WIDE_FIELD_TYPES — keyed on the spec vocabulary (#4250)', ()
100100
// `grid` is absent from this assertion by construction: it is not a spec
101101
// FieldType but a sanctioned objectui-local key (`GridFieldMetadata` in
102102
// `@object-ui/types`), so it is not part of the spec-facing surface.
103-
// `repeater` — the spec type whose widget IS `field:grid` — is deliberately
104-
// NOT wide here; that asymmetry is filed separately rather than fixed under
105-
// this card.
103+
// `repeater` is not wide either: it resolves to the JSON editor
104+
// (`field:object`), not to the line-items grid, so no surface spans it.
106105
const wideSpecTypes = SPEC_TYPES.filter((t) => isWideFieldType(t));
107106
expect([...wideSpecTypes].sort()).toEqual([...WIDE_SPEC_TYPES].sort());
108107
});
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* An untyped `repeater` field shows and edits its stored rows in the record
11+
* Edit dialog.
12+
*
13+
* `@objectstack/spec` declares `repeater` an untyped array of embedded JSON
14+
* objects: `FieldSchema` has no sub-field or column member, so nothing a widget
15+
* could read names the keys of a row. The alias table used to send it to the
16+
* line-items grid (`field:grid`), which draws only declared columns, so a
17+
* stored `[{label:'one',qty:1},…]` drew numbered rows with Duplicate and
18+
* Remove and no cell: the content could be neither read nor changed. It now
19+
* takes the JSON editor `composite` and `record` beside it use.
20+
*
21+
* Driven through the dialog the console mounts for Edit — the global
22+
* `ModalForm`, whose body is a real `SchemaRenderer` form — with the real
23+
* registered widgets and a click on the real submit button.
24+
*
25+
* The control: a line-items grid that DECLARES its columns still draws one
26+
* input per declared column and writes typed cells.
27+
*/
28+
import { describe, it, expect, vi } from 'vitest';
29+
import { render, waitFor, fireEvent, screen, act } from '@testing-library/react';
30+
import React from 'react';
31+
32+
import { registerAllFields, GridField, resolveFormWidgetType } from '@object-ui/fields';
33+
import { ModalForm } from './ModalForm';
34+
35+
registerAllFields();
36+
37+
const ROWS = [
38+
{ label: 'one', qty: 1 },
39+
{ label: 'two', qty: 2 },
40+
];
41+
42+
const STORED = {
43+
id: 'z1',
44+
name: 'Specimen — Full',
45+
f_repeater: ROWS,
46+
};
47+
48+
function makeDS() {
49+
return {
50+
getObjectSchema: vi.fn().mockResolvedValue({
51+
name: 'field_zoo',
52+
fields: {
53+
name: { type: 'text', label: 'Name' },
54+
f_repeater: { type: 'repeater', label: 'Repeater (embedded array)' },
55+
},
56+
}),
57+
findOne: vi.fn().mockResolvedValue(structuredClone(STORED)),
58+
find: vi.fn().mockResolvedValue({ data: [] }),
59+
create: vi.fn(async (_o: string, d: any) => ({ id: 'n1', ...d })),
60+
update: vi.fn(async (_o: string, _id: string, d: any) => ({ ...STORED, ...d })),
61+
};
62+
}
63+
64+
function openEditDialog() {
65+
const ds = makeDS();
66+
render(
67+
<ModalForm
68+
schema={{
69+
type: 'object-form',
70+
formType: 'modal',
71+
objectName: 'field_zoo',
72+
mode: 'edit',
73+
recordId: 'z1',
74+
open: true,
75+
} as any}
76+
dataSource={ds as any}
77+
/>,
78+
);
79+
return ds;
80+
}
81+
82+
const repeaterBox = () =>
83+
waitFor(() => {
84+
const el = document.querySelector('textarea[name="f_repeater"]') as HTMLTextAreaElement | null;
85+
if (!el) throw new Error('f_repeater not ready');
86+
return el;
87+
});
88+
89+
const type = async (el: HTMLElement, text: string) => {
90+
await act(async () => {
91+
fireEvent.change(el, { target: { value: text } });
92+
});
93+
};
94+
95+
const clickUpdate = async () => {
96+
await act(async () => {
97+
fireEvent.click(screen.getByRole('button', { name: 'Update' }));
98+
});
99+
await act(async () => {
100+
await new Promise((resolve) => setTimeout(resolve, 30));
101+
});
102+
};
103+
104+
const row = (name: string) => document.querySelector(`[data-field="${name}"]`) as HTMLElement | null;
105+
106+
const payloads = (ds: ReturnType<typeof makeDS>) => ds.update.mock.calls.map((call) => call[2]);
107+
108+
describe('an untyped repeater field in the record Edit dialog', () => {
109+
it('shows the stored rows: "one", "two", 1 and 2 are on screen', async () => {
110+
openEditDialog();
111+
const box = await repeaterBox();
112+
await waitFor(() => expect(box.value).toBe(JSON.stringify(ROWS, null, 2)));
113+
for (const shown of ['"one"', '"two"', '"qty": 1', '"qty": 2']) {
114+
expect(box.value).toContain(shown);
115+
}
116+
// Not the bare line-items grid it used to draw.
117+
expect(row('f_repeater')?.querySelector('[data-testid="line-items"]')).toBeNull();
118+
});
119+
120+
it('saves an edit as an array of objects, never a string', async () => {
121+
const ds = openEditDialog();
122+
const box = await repeaterBox();
123+
await waitFor(() => expect(box.value).toContain('"one"'));
124+
const next = [
125+
{ label: 'one', qty: 5 },
126+
{ label: 'three', qty: 3 },
127+
];
128+
await type(box, JSON.stringify(next));
129+
await clickUpdate();
130+
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1));
131+
const sent = payloads(ds)[0].f_repeater;
132+
expect(Array.isArray(sent)).toBe(true);
133+
expect(sent).toEqual(next);
134+
expect(typeof sent[0].qty).toBe('number');
135+
});
136+
137+
it('an untouched save never writes the field as text', async () => {
138+
const ds = openEditDialog();
139+
await repeaterBox();
140+
await clickUpdate();
141+
await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1));
142+
const sent = payloads(ds)[0];
143+
// Present or absent are both safe; a string in this slot is the defect.
144+
if ('f_repeater' in sent) expect(sent.f_repeater).toEqual(ROWS);
145+
expect(typeof sent.f_repeater === 'string').toBe(false);
146+
});
147+
148+
it('CONTROL — a grid that declares columns still draws the line-items grid', async () => {
149+
// `grid` is objectui's own line-items key (`GridFieldMetadata`), not a spec
150+
// field type, so it is driven at the widget the form resolves for it.
151+
expect(resolveFormWidgetType('grid')).toBe('grid');
152+
const onChange = vi.fn();
153+
render(
154+
<GridField
155+
field={{
156+
name: 'f_lines',
157+
columns: [
158+
{ name: 'item', label: 'Item', type: 'text' },
159+
{ name: 'qty', label: 'Qty', type: 'number' },
160+
],
161+
} as any}
162+
value={[{ item: 'bolt', qty: 3 }]}
163+
onChange={onChange}
164+
/>,
165+
);
166+
const grid = screen.getByTestId('line-items');
167+
expect((grid.querySelector('input[aria-label="Item"]') as HTMLInputElement).value).toBe('bolt');
168+
const qty = grid.querySelector('input[aria-label="Qty"]') as HTMLInputElement;
169+
expect(qty.value).toBe('3');
170+
await act(async () => {
171+
fireEvent.change(qty, { target: { value: '4' } });
172+
});
173+
expect(onChange).toHaveBeenLastCalledWith([{ item: 'bolt', qty: 4 }]);
174+
});
175+
});

0 commit comments

Comments
 (0)