From a1ec7a5c44c7c130072773799067e94ee7cfb28a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:49:05 +0000 Subject: [PATCH 1/4] test(fields): premise probe for the line-item grid follow-ups Claude-Session: https://claude.ai/code/session_01ADHkmNmMEXS4EzeVz9RjvD Co-authored-by: Claude --- ...GridField.lineItemFollowups-36552.test.tsx | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx diff --git a/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx b/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx new file mode 100644 index 00000000000..f3662cd719f --- /dev/null +++ b/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx @@ -0,0 +1,88 @@ +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor, act, fireEvent, within } from '@testing-library/react'; +import { SchemaRendererContext } from '@object-ui/react'; +import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; + +afterEach(cleanup); + +const PRODUCTS = [ + { id: 'p1', name: 'Widget' }, + { id: 'p2', name: 'Gadget' }, +]; +const USERS = Array.from({ length: 20 }, (_, i) => ({ id: `u${i + 1}`, name: `Person ${i + 1}` })); + +function makeSource() { + const tables: Record[]> = { product: PRODUCTS, sys_user: USERS }; + return { + find: vi.fn(async (object: string, params?: { $filter?: Record }) => { + const rows = tables[object] ?? []; + const wanted = params?.$filter?.id?.$in as unknown[] | undefined; + const picked = wanted ? rows.filter((r) => wanted.includes(r.id)) : rows; + return { data: picked.map((r) => ({ ...r })), total: picked.length }; + }), + findOne: vi.fn(async (object: string, id: string) => { + const row = (tables[object] ?? []).find((r) => r.id === id); + return row ? { ...row } : null; + }), + }; +} + +function Host({ ds, initial, columns, onChange, displayMode }: { ds: ReturnType; initial: any[]; columns: any[]; onChange?: (v: any[]) => void; displayMode?: 'list' }) { + const [rows, setRows] = React.useState(initial); + return ( + + { + setRows(v); + onChange?.(v); + }} + field={{ columns } as never} + displayMode={displayMode} + /> + + ); +} + +const readsOf = (ds: ReturnType, object: string) => ({ + findOne: ds.findOne.mock.calls.filter((c) => c[0] === object).length, + find: ds.find.mock.calls.filter((c) => c[0] === object).length, +}); + +describe('PROBE (premise) — objectstack#36552', () => { + it('a cleared multi-record lookup cell', async () => { + const ds = makeSource(); + const onChange = vi.fn(); + render(); + await act(async () => { + fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]); + }); + const option = await waitFor(() => { + const el = screen.getAllByRole('option').find((o) => (o.textContent ?? '').includes('Widget')); + if (!el) throw new Error('Widget not offered'); + return el; + }); + await act(async () => { + fireEvent.click(option); + }); + console.log('PROBE item1 written:', JSON.stringify(onChange.mock.calls.at(-1)?.[0])); + }); + + it('reads per line', async () => { + const ds = makeSource(); + render( + ({ owner: u.id, product: PRODUCTS[i % 2].id }))} + columns={[ + { name: 'owner', label: 'Owner', type: 'user' }, + { name: 'product', label: 'Product', type: 'lookup', reference: 'product' }, + ]} + />, + ); + await waitFor(() => expect(screen.getAllByText(/Person/).length).toBeGreaterThan(0)); + await new Promise((r) => setTimeout(r, 50)); + console.log('PROBE item2 sys_user:', JSON.stringify(readsOf(ds, 'sys_user')), 'product:', JSON.stringify(readsOf(ds, 'product'))); + }); +}); From 2431b1b9ba416de287ea4be4a4a8848945360cfd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 02:52:51 +0000 Subject: [PATCH 2/4] =?UTF-8?q?fix(fields):=20line-item=20grid=20follow-up?= =?UTF-8?q?s=20=E2=80=94=20null=20on=20an=20emptied=20multi-lookup=20cell,?= =?UTF-8?q?=20one=20name=20read=20per=20column,=20muted=20empty=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_01ADHkmNmMEXS4EzeVz9RjvD Co-authored-by: Claude --- ...GridField.lineItemFollowups-36552.test.tsx | 143 ++++++++++++++---- .../widgets/grid-field/GridFieldWidget.tsx | 31 +++- .../widgets/grid-field/lineReferenceReads.ts | 128 ++++++++++++++++ 3 files changed, 266 insertions(+), 36 deletions(-) create mode 100644 ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts diff --git a/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx b/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx index f3662cd719f..a0d0058adc8 100644 --- a/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx @@ -1,3 +1,15 @@ +/** + * objectstack#36552 — the line-item grid's follow-ups to objectstack#36043: + * + * - every emptied multi-value cell writes `null`: the multi-record lookup + * cell (it wrote `[]`) and the multi-person cell (right by reading, unpinned); + * - a people or lookup column draws its names with one read per referenced + * object, not one `findOne` per line; + * - in list mode a stored empty list reads as the muted em dash. + * + * In a file of its own rather than `GridField.test.tsx`, which another open + * change edits; the harness is this file's. + */ import * as React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, waitFor, act, fireEvent, within } from '@testing-library/react'; @@ -27,34 +39,56 @@ function makeSource() { }), }; } +type Source = ReturnType; -function Host({ ds, initial, columns, onChange, displayMode }: { ds: ReturnType; initial: any[]; columns: any[]; onChange?: (v: any[]) => void; displayMode?: 'list' }) { +function Host({ + ds, + initial, + columns, + onChange, + displayMode, + readonly, +}: { + ds?: Source; + initial: any[]; + columns: any[]; + onChange?: (v: any[]) => void; + displayMode?: 'list'; + readonly?: boolean; +}) { const [rows, setRows] = React.useState(initial); - return ( - - { - setRows(v); - onChange?.(v); - }} - field={{ columns } as never} - displayMode={displayMode} - /> - + const grid = ( + { + setRows(v); + onChange?.(v); + }} + field={{ columns } as never} + displayMode={displayMode} + readonly={readonly} + /> ); + return ds ? {grid} : grid; } -const readsOf = (ds: ReturnType, object: string) => ({ +/** The reads of `object` that reached the page's data source. */ +const readsOf = (ds: Source, object: string) => ({ findOne: ds.findOne.mock.calls.filter((c) => c[0] === object).length, - find: ds.find.mock.calls.filter((c) => c[0] === object).length, + find: ds.find.mock.calls.filter((c) => c[0] === object), }); -describe('PROBE (premise) — objectstack#36552', () => { - it('a cleared multi-record lookup cell', async () => { - const ds = makeSource(); +describe('an emptied multi-value cell writes null (objectstack#36552)', () => { + it('a multi-record lookup cell: un-picking its last record writes null, not []', async () => { const onChange = vi.fn(); - render(); + render( + , + ); await act(async () => { fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]); }); @@ -66,23 +100,74 @@ describe('PROBE (premise) — objectstack#36552', () => { await act(async () => { fireEvent.click(option); }); - console.log('PROBE item1 written:', JSON.stringify(onChange.mock.calls.at(-1)?.[0])); + expect(onChange).toHaveBeenCalled(); + expect(onChange.mock.calls.at(-1)![0][0].products).toBeNull(); + }); + + it("a multi-person cell: the picker's Clear writes null, not []", async () => { + const onChange = vi.fn(); + render( + , + ); + fireEvent.click(screen.getByRole('button', { name: 'Owners' })); + const panel = await screen.findByTestId('line-items-user-panel'); + fireEvent.click(within(panel).getByTestId('lookup-in-cell-clear')); + await waitFor(() => expect(screen.queryByTestId('line-items-user-panel')).toBeNull()); + expect(onChange).toHaveBeenCalled(); + expect(onChange.mock.calls.at(-1)![0][0].owners).toBeNull(); }); +}); + +describe('a people or lookup column reads its names once, not once per line (objectstack#36552)', () => { + const columns = [ + { name: 'owner', label: 'Owner', type: 'user' }, + { name: 'product', label: 'Product', type: 'lookup', reference: 'product' }, + ]; + // Twenty lines: twenty people, and two products named ten times each. + const lines = USERS.map((u, i) => ({ owner: u.id, product: PRODUCTS[i % 2].id })); + + for (const mode of ['editable', 'read-only', 'list'] as const) { + it(`${mode}: one $in read of sys_user and one of the product, no read per line, every name drawn`, async () => { + const ds = makeSource(); + render( + , + ); + for (const u of USERS) expect(await screen.findByText(u.name)).toBeTruthy(); + await waitFor(() => expect(screen.getAllByText('Gadget')).toHaveLength(10)); + expect(screen.getAllByText('Widget')).toHaveLength(10); + + const people = readsOf(ds, 'sys_user'); + expect(people.findOne).toBe(0); + expect(people.find).toHaveLength(1); + expect(people.find[0][1]).toMatchObject({ $filter: { id: { $in: USERS.map((u) => u.id) } } }); + + const products = readsOf(ds, 'product'); + expect(products.findOne).toBe(0); + expect(products.find).toHaveLength(1); + expect(products.find[0][1]).toMatchObject({ $filter: { id: { $in: ['p1', 'p2'] } } }); + }); + } +}); - it('reads per line', async () => { - const ds = makeSource(); +describe('list mode: a stored empty list reads as the muted em dash (objectstack#36552)', () => { + it('a multi-select and a tags cell holding [] draw — in the muted colour, as null does', () => { render( ({ owner: u.id, product: PRODUCTS[i % 2].id }))} + displayMode="list" + initial={[{ colors: [], labels: [], note: null }]} columns={[ - { name: 'owner', label: 'Owner', type: 'user' }, - { name: 'product', label: 'Product', type: 'lookup', reference: 'product' }, + { name: 'colors', label: 'Colors', type: 'multiselect', options: [{ label: 'Red', value: 'red' }] }, + { name: 'labels', label: 'Labels', type: 'tags' }, + { name: 'note', label: 'Note', type: 'text' }, ]} />, ); - await waitFor(() => expect(screen.getAllByText(/Person/).length).toBeGreaterThan(0)); - await new Promise((r) => setTimeout(r, 50)); - console.log('PROBE item2 sys_user:', JSON.stringify(readsOf(ds, 'sys_user')), 'product:', JSON.stringify(readsOf(ds, 'product'))); + const dashes = screen.getAllByText('—'); + expect(dashes).toHaveLength(3); + for (const dash of dashes) expect(dash.className).toContain('text-muted-foreground'); }); }); diff --git a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx index f5f47110c5a..44d5c73e698 100644 --- a/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx +++ b/ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx @@ -42,6 +42,8 @@ import { RatingField } from '../RatingField.js'; import { useBooleanValueLabel } from '../booleanValueLabel.js'; import { isImeKey } from '../imeKey.js'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; +import { SchemaRendererContext } from '@object-ui/react'; +import { lineReferenceSource } from './lineReferenceReads.js'; // The grid's pure half: the column type, the computed-cell evaluator, the // lookup-pick patch and the row marks. They live beside the public face in // `../GridField.ts`, in the eager chunk, because `@object-ui/fields` exports @@ -138,7 +140,8 @@ const isEmptyCell = (value: unknown) => /** The star count of a `rating` column: its `max`, else `Field.rating`'s own 5 (objectstack#36043). */ const ratingMax = (c: GridColumn) => c.max ?? 5; -/** A list cell emptied by the user writes `null`, not `[]` (objectstack#36043): +/** A list cell emptied by the user writes `null`, not `[]` (objectstack#36043; + * the multi-record lookup cell too since objectstack#36552): * the field contract stores a cleared multi-value field as `null`, and the * save path's blank-line check (`isBlankRow`) reads only `null` / `''` as * empty, so a `[]` would send a line the user emptied as a child record. */ @@ -351,7 +354,6 @@ function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: Ce } // A multi-select cell names each value by its option's label (objectstack#36043). if (c.type === 'multiselect' && Array.isArray(value)) { - if (value.length === 0) return '—'; return value.map((v) => c.options?.find((o) => String(o.value) === String(v))?.label ?? String(v)).join(', '); } // A check cell reads as its option's word (the session's, from the derive), @@ -757,6 +759,14 @@ function GridFieldBody({ }; const displayText = (c: GridColumn, value: any, locale: string, cellCurrency?: string) => cellDisplayText(c, value, locale, fileText, cellCurrency); + // The data source every people and lookup cell reads its records through + // (objectstack#36552): the page's, with the by-id read each cell makes to + // draw a name gathered into one `$in` read per referenced object, so a grid + // draws its names with one read per column instead of one per line. + // `undefined` without a page data source: the cells then resolve their own, + // as before. The same object on every render (`lineReferenceSource` keeps + // one per page source), so no cell sees a new source it would re-read for. + const cellSource = lineReferenceSource(React.useContext(SchemaRendererContext)?.dataSource); /** * The read-only face of a cell that is not text (objectstack#36043): people * by name, a rating as its stars; `null` for every other cell, which reads @@ -765,7 +775,7 @@ function GridFieldBody({ const readOnlyFace = (c: GridColumn, value: any): React.ReactNode | null => { if (isEmptyCell(value)) return null; if (c.type === 'user') { - return {}} readonly field={{ type: 'user', multiple: c.multiple } as any} />; + return {}} readonly field={{ type: 'user', multiple: c.multiple } as any} dataSource={cellSource} />; } if (c.type === 'rating') { return {}} readonly field={{ type: 'rating', max: ratingMax(c) } as any} />; @@ -1246,6 +1256,7 @@ function GridFieldBody({ onChange={() => {}} readonly field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any} + dataSource={cellSource} /> ) : ( // Every other cell reads through `displayText`, as the @@ -1353,13 +1364,16 @@ function GridFieldBody({ if (c.type === 'lookup' && val != null && val !== '') { return ( {}} readonly - field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any} /> + field={{ reference: c.reference, displayField: c.displayField, idField: c.idField } as any} + dataSource={cellSource} /> ); } const face = readOnlyFace(c, val); if (face) return face; return ( - + // Muted exactly when the text is the em dash an empty cell reads as, + // a stored empty list included (objectstack#36552). + {displayText(c, val, displayLocale, currencyOf(c))} ); @@ -1380,7 +1394,10 @@ function GridFieldBody({ return ( setCellValue(rowIdx, c.name, v)} + // A multi-record lookup emptied by the user writes `null`, as the + // multi-select, tags and people cells do (objectstack#36552). + onChange={(v: any) => setCellValue(rowIdx, c.name, emptyListAsNull(v))} + dataSource={cellSource} onSelectRecord={(rec: any, picked?: { sourceFields?: Readonly> | null }) => applyLookupSelection(rowIdx, c, rec, picked)} compact field={{ reference: c.reference, displayField: c.displayField, idField: c.idField, multiple: c.multiple, options: c.options, placeholder: '—' } as any} @@ -1475,7 +1492,7 @@ function GridFieldBody({ panelTestId="line-items-user-panel" > {({ draft, setDraft, commit }) => ( - setDraft(next)} onCommit={commit} field={field} /> + setDraft(next)} onCommit={commit} field={field} dataSource={cellSource} /> )} ); diff --git a/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts b/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts new file mode 100644 index 00000000000..cd57377b4b2 --- /dev/null +++ b/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts @@ -0,0 +1,128 @@ +/** + * 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. + */ + +import { extractRecords } from '@object-ui/core'; + +/** + * The line-item grid's record reads, one per referenced object (objectstack#36552). + * + * Every people and lookup cell of the grid is its own `LookupField`, and each + * one that holds a bare id reads that record to draw its name: one + * `findOne(object, id)` per line, so a grid of twenty lines with a people + * column made twenty reads of `sys_user`, and a lookup column twenty more of + * its target, however few distinct records the lines named. + * + * The grid hands its cells this data source instead of the page's. It answers + * the plain by-id read (`findOne(object, id)`, no options) from ONE + * `find(object, { $filter: { id: { $in: ids } } })` per object, gathering the + * reads that every cell makes in the same tick (the cells' mount effects all + * run in one flush). The ids are de-duplicated, so twenty lines naming two + * products ask for two rows. Every other member, and a by-id read that carries + * options, goes to the page's data source untouched. + * + * Why here and not an `$expand` on the read of the lines (AGENTS.md, Prime + * Directive 5, SQL first): the grid does not make that read. Its rows reach it + * as a value — from the master-detail form's or the line-items panel's read of + * the child object, or stored inline on the record as the `grid` field's JSON, + * which no `$expand` can reach — and an expanded reference held in a row is + * also what the save path and the blank-line check would then read and write + * back. One `$in` read per object is one SQL query with an `IN` list, at the + * one place every host's rows pass through. + * + * At most {@link CHUNK} ids go in one read, the page size `LookupField` caps + * its own `$in` reads at, so no read asks for more rows than a server may + * return; a grid naming more distinct records than that makes one read per + * chunk. + */ + +/** `LookupField`'s `LOOKUP_PAGE_SIZE`: the most ids one `$in` read names. */ +const CHUNK = 50; + +type ReadSource = { + find: (object: string, params?: Record) => Promise; + findOne?: (object: string, id: string | number, params?: unknown) => Promise; +}; + +type Waiter = { id: string | number; resolve: (row: unknown) => void; reject: (error: unknown) => void }; + +const isReadSource = (source: unknown): source is ReadSource => + source != null && typeof source === 'object' && typeof (source as ReadSource).find === 'function'; + +/** One wrapper per page data source, so every grid on the page shares its batches and each cell sees one stable source. */ +const wrappers = new WeakMap(); + +/** + * The data source the grid hands its people and lookup cells: `source`, with + * its by-id read gathered into one read per object (see the module note). + * `undefined` when there is no data source to read through, so the cells + * resolve theirs as they do without the grid. + */ +export function lineReferenceSource(source: unknown): unknown { + if (!isReadSource(source) || typeof source.findOne !== 'function') return undefined; + const held = wrappers.get(source); + if (held) return held; + + const waiting = new Map(); + + const flush = (object: string) => { + const waiters = waiting.get(object) ?? []; + waiting.delete(object); + const ids = new Map(); + for (const w of waiters) if (!ids.has(String(w.id))) ids.set(String(w.id), w.id); + const all = [...ids.values()]; + for (let i = 0; i < all.length; i += CHUNK) { + const chunk = all.slice(i, i + CHUNK); + const keys = new Set(chunk.map(String)); + const mine = waiters.filter((w) => keys.has(String(w.id))); + source + .find(object, { $filter: { id: { $in: chunk } }, $top: chunk.length }) + .then((result) => { + const byId = new Map(); + for (const row of extractRecords(result)) { + if (row && typeof row === 'object' && row.id != null) byId.set(String(row.id), row); + } + // `findOne`'s own answer for a record it cannot find: `null`. + for (const w of mine) w.resolve(byId.get(String(w.id)) ?? null); + }) + .catch((error: unknown) => { + for (const w of mine) w.reject(error); + }); + } + }; + + const findOne = (object: string, id: string | number, params?: unknown): Promise => { + if (params !== undefined || (typeof id !== 'string' && typeof id !== 'number') || id === '') { + return source.findOne!(object, id, params); + } + return new Promise((resolve, reject) => { + const queue = waiting.get(object); + if (queue) { + queue.push({ id, resolve, reject }); + return; + } + waiting.set(object, [{ id, resolve, reject }]); + queueMicrotask(() => flush(object)); + }); + }; + + // Every other member is the page source's own, bound to it, so a method + // that reads its instance state runs exactly as it does unwrapped. Bound + // once per member, so a member reads as the same function on every access. + const bound = new WeakMap<(...args: unknown[]) => unknown, unknown>(); + const wrapper = new Proxy(source as object, { + get(target, prop) { + if (prop === 'findOne') return findOne; + const value = Reflect.get(target, prop, target); + if (typeof value !== 'function') return value; + if (!bound.has(value)) bound.set(value, value.bind(target)); + return bound.get(value); + }, + }); + wrappers.set(source, wrapper); + return wrapper; +} From fa891aa580fdbadc51e6ab3d45e8d749361eb8e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:03:15 +0000 Subject: [PATCH 3/4] chore(changeset): line-item grid follow-ups Claude-Session: https://claude.ai/code/session_01ADHkmNmMEXS4EzeVz9RjvD Co-authored-by: Claude --- .changeset/36552-line-item-grid-followups.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .changeset/36552-line-item-grid-followups.md diff --git a/.changeset/36552-line-item-grid-followups.md b/.changeset/36552-line-item-grid-followups.md new file mode 100644 index 00000000000..85d0728a9b8 --- /dev/null +++ b/.changeset/36552-line-item-grid-followups.md @@ -0,0 +1,14 @@ +--- +'@object-ui/fields': patch +--- + +fix(fields): the line-item grid stores an emptied multi-record lookup cell as `null`, draws a people or lookup column's names with one read, and mutes an empty list in list mode + +Clause-②: no +Metadata-protocol: none + +- **An emptied multi-record lookup cell writes `null`.** Un-picking the last record of a `lookup` column with `multiple: true` wrote an empty list (`[]`) into the line, while an emptied multi-select, tags or people cell writes `null`, the value the field contract stores for a cleared multi-value field. It now writes `null` too, so every emptied multi-value cell in the grid stores the same value and the save's blank-line check reads it as empty. +- **Names are read once per referenced object, not once per line.** Each people cell and lookup cell holding a bare record id read that record on its own to draw its name, so a grid of twenty lines with a people column made twenty reads of `sys_user`, and a lookup column twenty more of its target. The grid now gathers those reads into one read per referenced object (an `$in` on the record ids, up to 50 ids per read), with each id asked for once, in editable, read-only and list mode alike. What each cell draws is unchanged. +- **A stored empty list reads muted in list mode.** A multi-select or tags cell holding `[]` drew the em dash in the normal text colour; it now takes the muted colour, as an empty value already did. + +No metadata key, value or default changes. From fbdfc7d4f0ce8ac6aac77be49663b78c608d9a0f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 03:46:52 +0000 Subject: [PATCH 4/4] test(fields): line-item grid follow-up pins move into GridField.test.tsx; batched name rows keyed by id or _id Claude-Session: https://claude.ai/code/session_01ADHkmNmMEXS4EzeVz9RjvD Co-authored-by: Claude --- ...GridField.lineItemFollowups-36552.test.tsx | 173 ----------------- .../fields/src/widgets/GridField.test.tsx | 182 +++++++++++++++++- .../widgets/grid-field/lineReferenceReads.ts | 6 +- 3 files changed, 186 insertions(+), 175 deletions(-) delete mode 100644 ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx diff --git a/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx b/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx deleted file mode 100644 index a0d0058adc8..00000000000 --- a/ui/packages/fields/src/widgets/GridField.lineItemFollowups-36552.test.tsx +++ /dev/null @@ -1,173 +0,0 @@ -/** - * objectstack#36552 — the line-item grid's follow-ups to objectstack#36043: - * - * - every emptied multi-value cell writes `null`: the multi-record lookup - * cell (it wrote `[]`) and the multi-person cell (right by reading, unpinned); - * - a people or lookup column draws its names with one read per referenced - * object, not one `findOne` per line; - * - in list mode a stored empty list reads as the muted em dash. - * - * In a file of its own rather than `GridField.test.tsx`, which another open - * change edits; the harness is this file's. - */ -import * as React from 'react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor, act, fireEvent, within } from '@testing-library/react'; -import { SchemaRendererContext } from '@object-ui/react'; -import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; - -afterEach(cleanup); - -const PRODUCTS = [ - { id: 'p1', name: 'Widget' }, - { id: 'p2', name: 'Gadget' }, -]; -const USERS = Array.from({ length: 20 }, (_, i) => ({ id: `u${i + 1}`, name: `Person ${i + 1}` })); - -function makeSource() { - const tables: Record[]> = { product: PRODUCTS, sys_user: USERS }; - return { - find: vi.fn(async (object: string, params?: { $filter?: Record }) => { - const rows = tables[object] ?? []; - const wanted = params?.$filter?.id?.$in as unknown[] | undefined; - const picked = wanted ? rows.filter((r) => wanted.includes(r.id)) : rows; - return { data: picked.map((r) => ({ ...r })), total: picked.length }; - }), - findOne: vi.fn(async (object: string, id: string) => { - const row = (tables[object] ?? []).find((r) => r.id === id); - return row ? { ...row } : null; - }), - }; -} -type Source = ReturnType; - -function Host({ - ds, - initial, - columns, - onChange, - displayMode, - readonly, -}: { - ds?: Source; - initial: any[]; - columns: any[]; - onChange?: (v: any[]) => void; - displayMode?: 'list'; - readonly?: boolean; -}) { - const [rows, setRows] = React.useState(initial); - const grid = ( - { - setRows(v); - onChange?.(v); - }} - field={{ columns } as never} - displayMode={displayMode} - readonly={readonly} - /> - ); - return ds ? {grid} : grid; -} - -/** The reads of `object` that reached the page's data source. */ -const readsOf = (ds: Source, object: string) => ({ - findOne: ds.findOne.mock.calls.filter((c) => c[0] === object).length, - find: ds.find.mock.calls.filter((c) => c[0] === object), -}); - -describe('an emptied multi-value cell writes null (objectstack#36552)', () => { - it('a multi-record lookup cell: un-picking its last record writes null, not []', async () => { - const onChange = vi.fn(); - render( - , - ); - await act(async () => { - fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]); - }); - const option = await waitFor(() => { - const el = screen.getAllByRole('option').find((o) => (o.textContent ?? '').includes('Widget')); - if (!el) throw new Error('Widget not offered'); - return el; - }); - await act(async () => { - fireEvent.click(option); - }); - expect(onChange).toHaveBeenCalled(); - expect(onChange.mock.calls.at(-1)![0][0].products).toBeNull(); - }); - - it("a multi-person cell: the picker's Clear writes null, not []", async () => { - const onChange = vi.fn(); - render( - , - ); - fireEvent.click(screen.getByRole('button', { name: 'Owners' })); - const panel = await screen.findByTestId('line-items-user-panel'); - fireEvent.click(within(panel).getByTestId('lookup-in-cell-clear')); - await waitFor(() => expect(screen.queryByTestId('line-items-user-panel')).toBeNull()); - expect(onChange).toHaveBeenCalled(); - expect(onChange.mock.calls.at(-1)![0][0].owners).toBeNull(); - }); -}); - -describe('a people or lookup column reads its names once, not once per line (objectstack#36552)', () => { - const columns = [ - { name: 'owner', label: 'Owner', type: 'user' }, - { name: 'product', label: 'Product', type: 'lookup', reference: 'product' }, - ]; - // Twenty lines: twenty people, and two products named ten times each. - const lines = USERS.map((u, i) => ({ owner: u.id, product: PRODUCTS[i % 2].id })); - - for (const mode of ['editable', 'read-only', 'list'] as const) { - it(`${mode}: one $in read of sys_user and one of the product, no read per line, every name drawn`, async () => { - const ds = makeSource(); - render( - , - ); - for (const u of USERS) expect(await screen.findByText(u.name)).toBeTruthy(); - await waitFor(() => expect(screen.getAllByText('Gadget')).toHaveLength(10)); - expect(screen.getAllByText('Widget')).toHaveLength(10); - - const people = readsOf(ds, 'sys_user'); - expect(people.findOne).toBe(0); - expect(people.find).toHaveLength(1); - expect(people.find[0][1]).toMatchObject({ $filter: { id: { $in: USERS.map((u) => u.id) } } }); - - const products = readsOf(ds, 'product'); - expect(products.findOne).toBe(0); - expect(products.find).toHaveLength(1); - expect(products.find[0][1]).toMatchObject({ $filter: { id: { $in: ['p1', 'p2'] } } }); - }); - } -}); - -describe('list mode: a stored empty list reads as the muted em dash (objectstack#36552)', () => { - it('a multi-select and a tags cell holding [] draw — in the muted colour, as null does', () => { - render( - , - ); - const dashes = screen.getAllByText('—'); - expect(dashes).toHaveLength(3); - for (const dash of dashes) expect(dash.className).toContain('text-muted-foreground'); - }); -}); diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index e136d201b74..b0a97a848e1 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -1,11 +1,12 @@ import { describe, it, expect, vi } from 'vitest'; -import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; +import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react'; import React from 'react'; import { UploadProvider } from './UploadProvider'; import { Dialog, DialogContent, DialogTitle } from '@object-ui/components'; import { formatDate, formatDateTime } from '@object-ui/core'; import { I18nProvider } from '@object-ui/i18n'; import { en, zh } from '@object-ui/i18n/locales'; +import { SchemaRendererContext } from '@object-ui/react'; import { GridFieldWidget as GridField } from './grid-field/GridFieldWidget'; import { GridField as GridFieldFace, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './GridField'; @@ -1640,3 +1641,182 @@ describe('GridField — the lazy face the package exports (objectstack#36102)', }); }); }); + +/** + * objectstack#36552 — the line-item grid's follow-ups to objectstack#36043: + * + * - every emptied multi-value cell writes `null`: the multi-record lookup + * cell (it wrote `[]`) and the multi-person cell (right by reading, unpinned); + * - a people or lookup column draws its names with one read per referenced + * object, not one `findOne` per line; + * - in list mode a stored empty list reads as the muted em dash. + */ +describe('line-item grid follow-ups: null on an emptied multi-value cell, one name read per object, a muted empty list (objectstack#36552)', () => { + const PRODUCTS = [ + { id: 'p1', name: 'Widget' }, + { id: 'p2', name: 'Gadget' }, + ]; + const USERS = Array.from({ length: 20 }, (_, i) => ({ id: `u${i + 1}`, name: `Person ${i + 1}` })); + + function makeSource() { + const tables: Record[]> = { product: PRODUCTS, sys_user: USERS }; + return { + find: vi.fn(async (object: string, params?: { $filter?: Record }) => { + const rows = tables[object] ?? []; + const wanted = params?.$filter?.id?.$in as unknown[] | undefined; + const picked = wanted ? rows.filter((r) => wanted.includes(r.id)) : rows; + return { data: picked.map((r) => ({ ...r })), total: picked.length }; + }), + findOne: vi.fn(async (object: string, id: string) => { + const row = (tables[object] ?? []).find((r) => r.id === id); + return row ? { ...row } : null; + }), + }; + } + type Source = ReturnType; + + function Host({ + ds, + initial, + columns, + onChange, + displayMode, + readonly, + }: { + ds?: Source; + initial: any[]; + columns: any[]; + onChange?: (v: any[]) => void; + displayMode?: 'list'; + readonly?: boolean; + }) { + const [rows, setRows] = React.useState(initial); + const grid = ( + { + setRows(v); + onChange?.(v); + }} + field={{ columns } as never} + displayMode={displayMode} + readonly={readonly} + /> + ); + return ds ? {grid} : grid; + } + + /** The reads of `object` that reached the page's data source. */ + const readsOf = (ds: Source, object: string) => ({ + findOne: ds.findOne.mock.calls.filter((c) => c[0] === object).length, + find: ds.find.mock.calls.filter((c) => c[0] === object), + }); + + describe('an emptied multi-value cell writes null (objectstack#36552)', () => { + it('a multi-record lookup cell: un-picking its last record writes null, not []', async () => { + const onChange = vi.fn(); + render( + , + ); + await act(async () => { + fireEvent.click(screen.getAllByTestId('lookup-trigger')[0]); + }); + const option = await waitFor(() => { + const el = screen.getAllByRole('option').find((o) => (o.textContent ?? '').includes('Widget')); + if (!el) throw new Error('Widget not offered'); + return el; + }); + await act(async () => { + fireEvent.click(option); + }); + expect(onChange).toHaveBeenCalled(); + expect(onChange.mock.calls.at(-1)![0][0].products).toBeNull(); + }); + + it("a multi-person cell: the picker's Clear writes null, not []", async () => { + const onChange = vi.fn(); + render( + , + ); + fireEvent.click(screen.getByRole('button', { name: 'Owners' })); + const panel = await screen.findByTestId('line-items-user-panel'); + fireEvent.click(within(panel).getByTestId('lookup-in-cell-clear')); + await waitFor(() => expect(screen.queryByTestId('line-items-user-panel')).toBeNull()); + expect(onChange).toHaveBeenCalled(); + expect(onChange.mock.calls.at(-1)![0][0].owners).toBeNull(); + }); + }); + + describe('a people or lookup column reads its names once, not once per line (objectstack#36552)', () => { + const columns = [ + { name: 'owner', label: 'Owner', type: 'user' }, + { name: 'product', label: 'Product', type: 'lookup', reference: 'product' }, + ]; + // Twenty lines: twenty people, and two products named ten times each. + const lines = USERS.map((u, i) => ({ owner: u.id, product: PRODUCTS[i % 2].id })); + + for (const mode of ['editable', 'read-only', 'list'] as const) { + it(`${mode}: one $in read of sys_user and one of the product, no read per line, every name drawn`, async () => { + const ds = makeSource(); + render( + , + ); + for (const u of USERS) expect(await screen.findByText(u.name)).toBeTruthy(); + await waitFor(() => expect(screen.getAllByText('Gadget')).toHaveLength(10)); + expect(screen.getAllByText('Widget')).toHaveLength(10); + + const people = readsOf(ds, 'sys_user'); + expect(people.findOne).toBe(0); + expect(people.find).toHaveLength(1); + expect(people.find[0][1]).toMatchObject({ $filter: { id: { $in: USERS.map((u) => u.id) } } }); + + const products = readsOf(ds, 'product'); + expect(products.findOne).toBe(0); + expect(products.find).toHaveLength(1); + expect(products.find[0][1]).toMatchObject({ $filter: { id: { $in: ['p1', 'p2'] } } }); + }); + } + + it('a backend that answers with `_id` only: each line still draws its name from the one read', async () => { + const ds = makeSource(); + ds.find.mockImplementation(async (object: string, params?: { $filter?: Record }) => { + const wanted = (params?.$filter?.id?.$in ?? []) as unknown[]; + const rows = object === 'product' ? PRODUCTS.filter((r) => wanted.includes(r.id)) : []; + return { data: rows.map(({ id, ...rest }) => ({ _id: id, ...rest })), total: rows.length }; + }); + render( ({ product }))} columns={[columns[1]]} readonly />); + await waitFor(() => expect(screen.getAllByText('Widget')).toHaveLength(2)); + expect(screen.getAllByText('Gadget')).toHaveLength(2); + expect(readsOf(ds, 'product').findOne).toBe(0); + expect(readsOf(ds, 'product').find).toHaveLength(1); + }); + }); + + describe('list mode: a stored empty list reads as the muted em dash (objectstack#36552)', () => { + it('a multi-select and a tags cell holding [] draw — in the muted colour, as null does', () => { + render( + , + ); + const dashes = screen.getAllByText('—'); + expect(dashes).toHaveLength(3); + for (const dash of dashes) expect(dash.className).toContain('text-muted-foreground'); + }); + }); +}); diff --git a/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts b/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts index cd57377b4b2..353de8d2594 100644 --- a/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts +++ b/ui/packages/fields/src/widgets/grid-field/lineReferenceReads.ts @@ -83,8 +83,12 @@ export function lineReferenceSource(source: unknown): unknown { .find(object, { $filter: { id: { $in: chunk } }, $top: chunk.length }) .then((result) => { const byId = new Map(); + // Keyed by `id`, else `_id`, as `LookupField` keys the rows of its + // own `$in` read (`recordValue`): a backend that answers with `_id` + // only still names the record each by-id read asked for. for (const row of extractRecords(result)) { - if (row && typeof row === 'object' && row.id != null) byId.set(String(row.id), row); + const key = row && typeof row === 'object' ? (row.id ?? row._id) : undefined; + if (key != null) byId.set(String(key), row); } // `findOne`'s own answer for a record it cannot find: `null`. for (const w of mine) w.resolve(byId.get(String(w.id)) ?? null);