Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/36552-line-item-grid-followups.md
Original file line number Diff line number Diff line change
@@ -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.
182 changes: 181 additions & 1 deletion ui/packages/fields/src/widgets/GridField.test.tsx
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<string, Record<string, unknown>[]> = { product: PRODUCTS, sys_user: USERS };
return {
find: vi.fn(async (object: string, params?: { $filter?: Record<string, any> }) => {
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<typeof makeSource>;

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 = (
<GridField
value={rows}
onChange={(v: any[]) => {
setRows(v);
onChange?.(v);
}}
field={{ columns } as never}
displayMode={displayMode}
readonly={readonly}
/>
);
return ds ? <SchemaRendererContext.Provider value={{ dataSource: ds } as never}>{grid}</SchemaRendererContext.Provider> : 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(
<Host
ds={makeSource()}
initial={[{ products: ['p1'] }]}
columns={[{ name: 'products', label: 'Products', type: 'lookup', reference: 'product', multiple: true }]}
onChange={onChange}
/>,
);
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(
<Host
initial={[{ owners: ['u1', 'u2'] }]}
columns={[{ name: 'owners', label: 'Owners', type: 'user', multiple: true }]}
onChange={onChange}
/>,
);
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(
<Host ds={ds} initial={lines} columns={columns} readonly={mode === 'read-only'} displayMode={mode === 'list' ? 'list' : undefined} />,
);
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<string, any> }) => {
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(<Host ds={ds} initial={lines.slice(0, 4).map(({ product }) => ({ 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(
<Host
displayMode="list"
initial={[{ colors: [], labels: [], note: null }]}
columns={[
{ name: 'colors', label: 'Colors', type: 'multiselect', options: [{ label: 'Red', value: 'red' }] },
{ name: 'labels', label: 'Labels', type: 'tags' },
{ name: 'note', label: 'Note', type: 'text' },
]}
/>,
);
const dashes = screen.getAllByText('—');
expect(dashes).toHaveLength(3);
for (const dash of dashes) expect(dash.className).toContain('text-muted-foreground');
});
});
});
31 changes: 24 additions & 7 deletions ui/packages/fields/src/widgets/grid-field/GridFieldWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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
Expand All @@ -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 <UserField value={value} onChange={() => {}} readonly field={{ type: 'user', multiple: c.multiple } as any} />;
return <UserField value={value} onChange={() => {}} readonly field={{ type: 'user', multiple: c.multiple } as any} dataSource={cellSource} />;
}
if (c.type === 'rating') {
return <RatingField value={Number(value)} onChange={() => {}} readonly field={{ type: 'rating', max: ratingMax(c) } as any} />;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -1353,13 +1364,16 @@ function GridFieldBody({
if (c.type === 'lookup' && val != null && val !== '') {
return (
<LookupField value={val} onChange={() => {}} 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 (
<span className={cn('px-2 text-sm text-foreground', isNumeric(c.type) && 'tabular-nums', (val == null || val === '') && 'text-muted-foreground')}>
// Muted exactly when the text is the em dash an empty cell reads as,
// a stored empty list included (objectstack#36552).
<span className={cn('px-2 text-sm text-foreground', isNumeric(c.type) && 'tabular-nums', isEmptyCell(val) && 'text-muted-foreground')}>
{displayText(c, val, displayLocale, currencyOf(c))}
</span>
);
Expand All @@ -1380,7 +1394,10 @@ function GridFieldBody({
return (
<LookupField
value={val}
onChange={(v: any) => 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<Record<string, unknown>> | 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}
Expand Down Expand Up @@ -1475,7 +1492,7 @@ function GridFieldBody({
panelTestId="line-items-user-panel"
>
{({ draft, setDraft, commit }) => (
<UserField inCell value={draft} onChange={(next: any) => setDraft(next)} onCommit={commit} field={field} />
<UserField inCell value={draft} onChange={(next: any) => setDraft(next)} onCommit={commit} field={field} dataSource={cellSource} />
)}
</GridPanelCell>
);
Expand Down
Loading
Loading