diff --git a/.changeset/35507-grid-entry-row-header-help.md b/.changeset/35507-grid-entry-row-header-help.md new file mode 100644 index 00000000000..ab34cb26d5a --- /dev/null +++ b/.changeset/35507-grid-entry-row-header-help.md @@ -0,0 +1,15 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-form': patch +--- + +fix(fields): the inline line grid draws no blank entry row beside "Add line", and each column header shows its field's help + +Clause-②: no +Metadata-protocol: none + +The inline line grid of a master-detail form always drew an empty line under the lines, directly above the "Add line" button. It had no copy or remove action and was never saved, so users read it as a broken line they could not delete. The grid no longer draws it: a grid with lines shows exactly its lines, and an empty grid says "No items yet — click "Add line" to begin." The keyboard path that line carried stays: "Add line" moves focus into the line it adds, and Enter in the last line adds a line and moves to the same column in it. An empty required grid that the form refused still draws one entry line, so the field's failure stays on the cells a user types into. + +Each column header now shows its field's help as an info icon beside the label. The help appears on hover and on keyboard focus, and it is the icon's accessible name. The text is what the record form shows under the same field: `inlineHelpText`, else `description`, from the child object's definition as the server serves it, so help written by another package's `objectExtensions.fieldPatches` and the reader's language both apply. `GridField` takes the texts as a new `columnHelp` prop, and `columnHelpByField` builds them from a child object's fields. The master-detail form, the line-items panel and the record-body table editor pass them. + +What does not change: what a save sends, the `allowAdd` / `allowDelete` / `maxRows` behaviour, and every metadata key, value and default. A master-detail entry whose relationship and every column type are authored loads no child schema, so its headers show no help, as it has no lookup autofill. diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 30c5e306c32..e3ad941f671 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -3004,6 +3004,8 @@ describe('RecordDetailView.recordEditState-35599', () => { const lines = editor(container, 'showcase_line.quote')!; fireEvent.change(cells(lines, 'Quantity')[0], { target: { value: '5' } }); fireEvent.click(lines.querySelectorAll('button[aria-label="Remove row"]')[1] as HTMLElement); + // The new line comes from Add: the grid draws no blank entry line beside it (objectstack#35507). + fireEvent.click(lines.querySelector('[data-testid="line-items-add"]') as HTMLElement); const products = cells(lines, 'Product'); fireEvent.change(products[products.length - 1], { target: { value: 'Crate' } }); const tasks = editor(container, 'showcase_task.quote')!; diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index a5a0cbc06b1..d22e39a39f8 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -5417,8 +5417,8 @@ export * from './widgets/AutoNumberField.js'; export * from './widgets/UserField.js'; export * from './widgets/ObjectField.js'; export * from './widgets/VectorField.js'; -export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, UNTOUCHED_NEW_ROW, isUntouchedNewRow } from './widgets/GridField.js'; -export type { ColumnCurrencies } from './widgets/GridField.js'; +export { evalArith, lookupAutofillPatch, computeRow, GridField, LineItemsField, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './widgets/GridField.js'; +export type { ColumnCurrencies, ColumnHelp } from './widgets/GridField.js'; export type { GridColumn } from './widgets/GridField.js'; export * from './widgets/lookupAutofill.js'; // objectstack#32770 (ADR-0150 D8 R1) — the grant's set-name column and the diff --git a/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx b/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx index 729ca26b26d..4e715017f0c 100644 --- a/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.sortFieldCellEdit-12286.test.tsx @@ -57,12 +57,17 @@ describe('GridField: a cell edit renumbers no row (objectui#12286)', () => { expect(next).toEqual([rows[0], { ...rows[1], description: 'B2' }]); }); - it('CONTROL: typing into the trailing entry row ADDS a line, and an add renumbers every row', () => { - const next = typeInto([{ description: 'A', position: 0 }, { description: 'B', position: 0 }], 2, 'C'); + it('CONTROL: Add appends a line, and an add renumbers every row', () => { + // The trailing entry line this used to type into is gone (objectstack#35507); + // Add is the add, and it renumbers as the entry line did. + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByTestId('line-items-add')); + const next: Row[] = onChange.mock.calls[0][0]; expect(next.map((r) => [r.description, r.position])).toEqual([ ['A', 0], ['B', 1], - ['C', 2], + [null, 2], ]); }); }); diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 355116ad4aa..a73d6c11628 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -3,7 +3,7 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import React from 'react'; import { UploadProvider } from './UploadProvider'; import { formatDate, formatDateTime } from '@object-ui/core'; -import { GridField, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow } from './GridField'; +import { GridField, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './GridField'; const columns = [ { name: 'description', label: 'Description', type: 'text' as const }, @@ -102,7 +102,7 @@ describe('GridField / LineItemsField — editable line items', () => { it('editing a text cell emits the raw string', () => { const onChange = vi.fn(); render(); - // [0] = the data row ([1] would be the always-present trailing ghost row). + // [0] = the data row. fireEvent.change(screen.getAllByLabelText('Description')[0], { target: { value: 'Taxi' } }); expect(onChange).toHaveBeenCalledWith([{ description: 'Taxi', amount: null }]); }); @@ -369,24 +369,23 @@ describe('GridField / LineItemsField — editable line items', () => { }); }); - describe('trailing ghost row (start-with-one + auto-append)', () => { - it('renders a trailing empty row so an empty grid still has one input line', () => { - render( {}} field={field} />); - // No "No items" empty-state in grid mode — the ghost row IS the first line. - expect(screen.getByText('Description')).toBeTruthy(); - expect(screen.getAllByLabelText('Description')).toHaveLength(1); // just the ghost + // objectstack#35507 — the always-present trailing entry line is gone (see + // the top-level `no trailing entry row beside Add` pins). It is drawn only + // for an empty grid the form refused (objectui#3318), and there typing + // into it still materialises the line. + describe('the entry line of an empty grid the form refused', () => { + it('is drawn only once the form reports the failure', () => { + const { rerender } = render( {}} field={field} />); + expect(screen.queryAllByLabelText('Description')).toHaveLength(0); + rerender( {}} field={field} error="Lines is required" />); + expect(screen.getAllByLabelText('Description')).toHaveLength(1); }); - it('typing in the ghost row materialises a new row (no Add click needed)', () => { + it('typing into it materialises a new line', () => { const onChange = vi.fn(); - render(); - const inputs = screen.getAllByLabelText('Description'); - expect(inputs).toHaveLength(2); // data row + ghost - fireEvent.change(inputs[1], { target: { value: 'B' } }); // type in the ghost - expect(onChange).toHaveBeenCalledWith([ - { description: 'A', amount: 1 }, - { description: 'B', amount: null }, - ]); + render(); + fireEvent.change(screen.getByLabelText('Description'), { target: { value: 'B' } }); + expect(onChange).toHaveBeenCalledWith([{ description: 'B', amount: null }]); }); }); @@ -508,12 +507,12 @@ describe('GridField / LineItemsField — editable line items', () => { ]); }); - it('flags a required, empty cell on a real row (not the ghost row)', () => { + it('flags a required, empty cell on a real row', () => { const reqField = { columns: [{ name: 'description', label: 'Description', type: 'text' as const, required: true }] } as any; render( {}} field={reqField} />); // The data row's required-empty cell is flagged... expect(screen.getByTestId('line-items-invalid-0-description')).toBeTruthy(); - // ...but the trailing ghost row (index 1) is not. + // ...and no line below it is drawn to flag (objectstack#35507). expect(screen.queryByTestId('line-items-invalid-1-description')).toBeNull(); }); }); @@ -528,7 +527,7 @@ describe('GridField / LineItemsField — editable line items', () => { it('renders a real upload control in the cell, not a text input', () => { render( {}} field={fileField} />); - // One upload button per row (data row + ghost), backed by a native file input. + // One upload button per row, backed by a native file input. expect(screen.getAllByRole('button', { name: 'Receipt' }).length).toBeGreaterThan(0); expect(document.querySelector('input[type="file"]')).toBeTruthy(); expect(screen.queryByRole('textbox', { name: 'Receipt' })).toBeNull(); @@ -591,14 +590,14 @@ describe('GridField / LineItemsField — editable line items', () => { expect(cell.getAttribute('aria-invalid')).toBeNull(); }); - it('does not announce invalid on an optional empty file cell or on the ghost row', () => { + it('does not announce invalid on an optional empty file cell', () => { const optFileField = { columns: [{ name: 'receipt', label: 'Receipt', type: 'file' as const }], } as any; const { container } = render( {}} field={optFileField} />, ); - // Data row and ghost row each render a picker; none may announce invalid. + // The data row renders a picker; it may not announce invalid. expect(container.querySelector('[aria-invalid="true"]')).toBeNull(); }); @@ -621,7 +620,7 @@ describe('GridField / LineItemsField — editable line items', () => { const withAccept = { columns: [{ name: 'receipt', label: 'Receipt', type: 'file' as const, accept: ['image/*', '.pdf'] }], } as any; - render( {}} field={withAccept} />); + render( {}} field={withAccept} />); const input = document.querySelector('input[type="file"]') as HTMLInputElement; expect(input.getAttribute('accept')).toBe('image/*,.pdf'); }); @@ -791,8 +790,10 @@ describe('GridField — a new line starts on its defaults and waits to read red it('Add and the entry line both start a line on the host\'s values', () => { const onChange = vi.fn(); + // The entry line is drawn for an empty grid the form refused + // (objectstack#35507), so the failure is handed in. const { container } = render( - , + , ); fireEvent.click(screen.getByRole('button', { name: /Add line/i })); expect(onChange).toHaveBeenLastCalledWith([{ name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true }]); @@ -845,3 +846,114 @@ describe('GridField — a new line starts on its defaults and waits to read red expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy(); }); }); + +/** + * objectstack#35507 — no blank entry row beside "Add line". The grid used to + * append an always-present empty "ghost" line under the data rows; it carried + * no actions, produced no write, and sat directly above the Add button that + * does the same job, so users read it as a broken line they could not delete. + * It was drawn only when Add was drawn (both follow `allowAdd`), so dropping it + * leaves no grid without a way to add a line. The keyboard path it carried + * (Tab or Enter into an empty line and type) is kept by Add moving focus into + * the new line and by Enter on the last line appending one. + */ +describe('no trailing entry row beside Add (objectstack#35507)', () => { + function Stateful({ initial, f = field }: { initial: Record[]; f?: any }) { + const [rows, setRows] = React.useState(initial); + return ; + } + + it('a grid with lines draws exactly its lines, and the Add button', () => { + render( {}} field={field} />); + expect(screen.getAllByLabelText('Description')).toHaveLength(1); + expect(screen.getByTestId('line-items-add')).toBeTruthy(); + }); + + it('an empty grid draws no entry row, and names the Add button in its empty state', () => { + render( {}} field={field} />); + expect(screen.queryAllByLabelText('Description')).toHaveLength(0); + expect(screen.getByText('No items yet — click “Add line” to begin.')).toBeTruthy(); + }); + + it('CONTROL: with `allowAdd: false` there is neither an Add button nor an entry row, as before', () => { + render( {}} field={{ ...field, allowAdd: false }} />); + expect(screen.queryByTestId('line-items-add')).toBeNull(); + expect(screen.getAllByLabelText('Description')).toHaveLength(1); + }); + + it('CONTROL: an edit emits exactly the lines, with no blank line appended, as before', () => { + const onChange = vi.fn(); + render(); + // `[0]`: the data line's cell, whatever else the grid draws below it. + fireEvent.change(screen.getAllByLabelText('Description')[0], { target: { value: 'B' } }); + expect(onChange).toHaveBeenLastCalledWith([{ description: 'B', amount: 1 }]); + }); + + it('Add moves focus into the new line, so the keyboard keeps typing', async () => { + render(); + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(screen.getAllByLabelText('Description')).toHaveLength(2)); + await waitFor(() => expect(document.activeElement).toBe(screen.getAllByLabelText('Description')[1])); + }); + + it('Enter in the last line appends a line and moves to the same column in it', async () => { + render(); + fireEvent.keyDown(screen.getByLabelText('Amount'), { key: 'Enter' }); + await waitFor(() => expect(screen.getAllByLabelText('Amount')).toHaveLength(2)); + await waitFor(() => expect(document.activeElement).toBe(screen.getAllByLabelText('Amount')[1])); + }); + + it('CONTROL: Enter in the last line appends nothing when adding is off', () => { + const onChange = vi.fn(); + render(); + fireEvent.keyDown(screen.getByLabelText('Amount'), { key: 'Enter' }); + expect(onChange).not.toHaveBeenCalled(); + }); +}); + +/** + * objectstack#35804 — each column header shows its field's help. A grid column + * carries no field definition, so the host that holds the child object's + * served definition (the one the record form reads, with other packages' + * `fieldPatches` applied and the help in the reader's language) hands the + * texts over through `columnHelpByField`, which reads each field through the + * form's own `fieldHelpText`. + */ +describe('column header help (objectstack#35804)', () => { + const help = { amount: 'Enter the tax-inclusive amount.' }; + + it('a column with help draws an info button whose accessible name is the help', () => { + render( {}} field={field} columnHelp={help} />); + const button = screen.getByRole('button', { name: 'Enter the tax-inclusive amount.' }); + expect(button.closest('th')!.textContent).toContain('Amount'); + }); + + it('focusing the info button shows the help', async () => { + render( {}} field={field} columnHelp={help} />); + fireEvent.focus(screen.getByRole('button', { name: 'Enter the tax-inclusive amount.' })); + expect((await screen.findByRole('tooltip')).textContent).toBe('Enter the tax-inclusive amount.'); + }); + + it('the read-only table draws the same help', () => { + render( {}} field={field} readonly columnHelp={help} />); + expect(screen.getByRole('button', { name: 'Enter the tax-inclusive amount.' })).toBeTruthy(); + }); + + it('CONTROL: a column without help draws no info button', () => { + render( {}} field={field} columnHelp={help} />); + const descriptionHeader = screen.getByText('Description').closest('th')!; + expect(descriptionHeader.querySelector('button')).toBeNull(); + }); + + it('columnHelpByField reads each field the way the record form does', () => { + expect( + columnHelpByField({ + unit_price: { inlineHelpText: 'Inline help wins.', description: 'Not this.' }, + quantity: { description: 'The served description.' }, + notes: { inlineHelpText: '' }, + bad: null, + }), + ).toEqual({ unit_price: 'Inline help wins.', quantity: 'The served description.' }); + expect(columnHelpByField(undefined)).toEqual({}); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index f5bae9ceecd..1a5224d841f 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -14,8 +14,12 @@ import { PopoverContent, Checkbox, Label, + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, } from '@object-ui/components'; -import { Plus, Trash2, SlidersHorizontal, Maximize2, Copy, GripVertical } from 'lucide-react'; +import { Plus, Trash2, SlidersHorizontal, Maximize2, Copy, GripVertical, Info } from 'lucide-react'; import { formatDate, formatDateTime, resolveFieldRuleState, toDisplayDate } from '@object-ui/core'; import { useDisplayLocale, useLocalization, formatDisplayNumber } from '@object-ui/i18n'; import { resolveFieldCurrency, currencyFractionDigits, currencySymbol } from '../currency.js'; @@ -27,6 +31,7 @@ import { useFieldTranslation } from './useFieldTranslation.js'; import { toDomProps } from './toDomProps.js'; import { PHONE_TOUCH_HEIGHT, PHONE_TOUCH_SQUARE } from './touchTarget.js'; import { toHostGroupProps } from './toHostGroupProps.js'; +import { fieldHelpText } from '../fieldHelpText.js'; import type { InlineGridColumn } from '@objectstack/spec/data'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; @@ -688,8 +693,9 @@ type GridFieldProps = FieldWidgetComponentProps & { * object's static field defaults, by field name. A grid column carries no * default (the spec's inline column refuses `defaultValue`), so the host * that holds the child schema hands them over. Every new line takes them: - * the trailing entry line, "Add", and a line typed into the entry line. A - * line already in the value keeps what it holds. Absent: a new line starts + * "Add", Enter on the last line, and a line typed into the entry line an + * empty grid draws after the form refused it (`hostFailedEmpty`). A line + * already in the value keeps what it holds. Absent: a new line starts * blank, as before. */ newRowValues?: Row; /** When the host sets it, an empty required cell on a NEW line (one with @@ -698,8 +704,68 @@ type GridFieldProps = FieldWidgetComponentProps & { * it, and does once a save was refused. A stored line is flagged as * before. Absent: every line is flagged at once, as before. */ newRowRequiredShown?: boolean; + /** The help text of each column's child field, by column name + * ({@link ColumnHelp}, objectstack#35804): drawn as an info button beside + * the column's header label. A grid column carries no field definition (the + * spec's inline column declares no help key), so the host that holds the + * child object's served definition hands it over through + * {@link columnHelpByField}. A column it does not name draws no button. */ + columnHelp?: ColumnHelp; }; +/** + * The help text of a grid's columns, by column name (objectstack#35804). + * Each value is what the record form draws under the same field. + */ +export type ColumnHelp = Readonly>; + +/** + * The {@link ColumnHelp} of a child object's fields: each field's help read + * through {@link fieldHelpText}, the ONE read the record form's help line uses + * (objectui#12213), so a grid header and the form show the same text. Hand it + * the child object's definition as the server serves it, the one the record + * form reads: another package's `objectExtensions.fieldPatches` are already + * applied there, and the help is in the reader's language. A field with no + * help is left out. + */ +export function columnHelpByField(fields: Readonly> | null | undefined): Record { + const out: Record = {}; + if (!fields || typeof fields !== 'object') return out; + for (const [name, def] of Object.entries(fields)) { + if (!def || typeof def !== 'object') continue; + const help = fieldHelpText(def as Parameters[0]); + if (help) out[name] = help; + } + return out; +} + +/** + * The info button beside a column's header label (objectstack#35804): the + * column's help on hover and on keyboard focus, and the button's accessible + * name is the help itself, so a screen reader hears it on reaching the button. + * Its own provider, so the grid draws it under any host. + */ +function ColumnHeaderHelp({ help }: { help: string | undefined }) { + if (!help) return null; + return ( + + + + + + {help} + + + ); +} + /** * The retired snake_case field-level keys a grid field's metadata carries, in * {@link GRID_FIELD_RETIRED_KEYS} order (objectui#11610). A key holding @@ -821,6 +887,7 @@ function GridFieldBody({ columnCurrencies, newRowValues, newRowRequiredShown, + columnHelp, ...props }: GridFieldProps) { // The field-level keys, read as `GridFieldMetadata` declares them and as @@ -983,9 +1050,9 @@ function GridFieldBody({ /** * Merge a field patch into a row. `rowIdx === rows.length` targets the - * trailing "ghost" row (always-present empty line) — editing it materialises - * a new real row, so the user never has to click "Add line" to keep entering. - * Computed columns are recomputed for the touched row on every change. + * entry line an empty grid draws once the form refused it (`hasGhost`) — + * editing it materialises a new real row. Computed columns are recomputed + * for the touched row on every change. */ const applyPatch = useCallback( (rowIdx: number, patch: Row) => { @@ -1048,29 +1115,53 @@ function GridFieldBody({ [applyCell], ); - const addRow = useCallback(() => { + // Keyboard navigation across cells (spreadsheet-style): the table is a focus + // grid. Enter / ArrowUp / ArrowDown move between rows in the same column; + // Tab / Shift-Tab fall through to the browser's natural row-major order. + // Cells carry data-cell="row-col" so we can target neighbours. + // + // objectstack#35507 — the grid no longer draws an empty entry line under + // its lines, so the two keyboard paths that line carried are kept here: Add + // moves focus into the line it appends (Tab reaches Add after the last + // line), and Enter on the last line appends a line and moves to the same + // column in it. The line exists only once the host hands it back in + // `value`, so the focus waits for it (`pendingFocus`). + const gridRef = useRef(null); + const focusCell = useCallback((rowIdx: number, colIdx: number): boolean => { + const el = gridRef.current?.querySelector(`[data-cell="${rowIdx}-${colIdx}"]`); + if (!el) return false; + el.focus(); + if (el instanceof HTMLInputElement) el.select(); + return true; + }, []); + /** The line and column to focus once the host hands an appended line back; `null` column = its first focusable cell. */ + const pendingFocus = useRef<{ rowIdx: number; colIdx: number | null } | null>(null); + React.useEffect(() => { + const pending = pendingFocus.current; + if (!pending || rows.length <= pending.rowIdx) return; + pendingFocus.current = null; + if (pending.colIdx != null && focusCell(pending.rowIdx, pending.colIdx)) return; + const first = gridRef.current?.querySelector(`[data-cell^="${pending.rowIdx}-"]`); + if (first) { + first.focus(); + if (first instanceof HTMLInputElement) first.select(); + } + }, [rows.length, focusCell]); + + const addRow = useCallback((focusColIdx: number | null = null) => { if (maxRows != null && rows.length >= maxRows) return; + pendingFocus.current = { rowIdx: rows.length, colIdx: focusColIdx }; // objectstack#35816 — a line Add starts on the host's defaults is marked // untouched until its first edit (`UNTOUCHED_NEW_ROW`). emit([...rows, newRowValues ? { ...blankRow(), [UNTOUCHED_NEW_ROW]: true } : blankRow()]); }, [rows, blankRow, maxRows, emit, newRowValues]); - // Keyboard navigation across cells (spreadsheet-style): the table is a focus - // grid. Enter / ArrowUp / ArrowDown move between rows in the same column; - // Tab / Shift-Tab fall through to the browser's natural row-major order - // (and into the ever-present ghost row, so tabbing past the last cell starts - // a new line). Cells carry data-cell="row-col" so we can target neighbours. - const gridRef = useRef(null); - const focusCell = useCallback((rowIdx: number, colIdx: number) => { - const el = gridRef.current?.querySelector(`[data-cell="${rowIdx}-${colIdx}"]`); - if (el) { - el.focus(); - if (el instanceof HTMLInputElement) el.select(); - } - }, []); const onCellKeyDown = useCallback( (e: React.KeyboardEvent, rowIdx: number, colIdx: number) => { - if (e.key === 'ArrowDown' || e.key === 'Enter') { + if (e.key === 'Enter' && rowIdx === rows.length - 1 && allowAdd && !isList) { + e.preventDefault(); + addRow(colIdx); + } else if (e.key === 'ArrowDown' || e.key === 'Enter') { e.preventDefault(); focusCell(rowIdx + 1, colIdx); } else if (e.key === 'ArrowUp') { @@ -1078,7 +1169,7 @@ function GridFieldBody({ if (rowIdx > 0) focusCell(rowIdx - 1, colIdx); } }, - [focusCell], + [focusCell, rows.length, allowAdd, isList, addRow], ); const removeRow = useCallback( @@ -1202,6 +1293,7 @@ function GridFieldBody({ )} > {c.label || c.name} + ))} @@ -1272,12 +1364,24 @@ function GridFieldBody({ } // ── Editable rendering ────────────────────────────────────────────────────── - // A trailing "ghost" empty row is always present in grid mode (start-with-one - // + auto-append): editing it materialises a real row, so the user keeps - // entering lines without clicking "Add". Index-based keys keep the input - // mounted across materialisation, so focus/caret survive the transition. - const hasGhost = !isList && allowAdd && (maxRows == null || rows.length < maxRows); + // objectstack#35507 — no empty entry line is drawn under the lines. It used + // to be, always ("start-with-one + auto-append"), directly above the Add + // button, which does the same job: it had no actions, produced no write, and + // users read it as a broken line they could not delete. Both followed + // `allowAdd`, so no grid loses its way to add a line; Add and Enter on the + // last line carry its keyboard path (see `pendingFocus`). An empty grid says + // so and names the Add button instead. + // + // One state still draws the entry line: a REQUIRED grid the form refused + // while EMPTY (`hostFailedEmpty`, below). There the line is what the + // failure is about: its required cells carry the field's failure to + // assistive tech on the controls a user types into to fix it (objectui#3318), + // and the Add button, the only other control, is an action, not what is + // invalid. Typing into it materialises a real line, as before. + const hostFailedEmpty = !!error && rows.length === 0; + const hasGhost = !isList && allowAdd && hostFailedEmpty && (maxRows == null || maxRows > 0); const displayRows: Row[] = hasGhost ? [...rows, blankRow()] : rows; + const addLabel = cfg.addLabel || t('fields.grid.addLine', { defaultValue: 'Add line' }); /** * FORM-level failure driving the per-CELL channel (objectui#3318). @@ -1296,8 +1400,11 @@ function GridFieldBody({ * a POPULATED grid already marks its own empty required cells inline, so * this changes nothing there, and an empty grid that has NOT failed stays * unmarked (no premature alarm before validation runs). + * + * Since objectstack#35507 that entry line is drawn ONLY in this state: an + * empty grid that has not failed draws its empty-state hint instead. + * (`hostFailedEmpty` itself is computed above, beside `hasGhost`.) */ - const hostFailedEmpty = !!error && rows.length === 0; /** Cell content: read-only display (list mode / computed columns) or an * editable borderless control (spreadsheet feel). @@ -1509,13 +1616,29 @@ function GridFieldBody({ > {c.label || c.name} {c.required && !c.computed && *} + ))} {hasRowActions && } - {isList && rows.length === 0 ? ( + {!isList && displayRows.length === 0 ? ( + + + {allowAdd + ? t('fields.grid.noItemsAddHint', { + label: addLabel, + defaultValue: 'No items yet — click “{{label}}” to begin.', + }) + : t('fields.grid.noItems', { defaultValue: 'No items' })} + + + ) : isList && rows.length === 0 ? ( addRow()} disabled={maxRows != null && rows.length >= maxRows} data-testid="line-items-add" > - {cfg.addLabel || t('fields.grid.addLine', { defaultValue: 'Add line' })} + {addLabel} )} diff --git a/ui/packages/plugin-form/src/LineItemsPanel.childObjectDecline.test.tsx b/ui/packages/plugin-form/src/LineItemsPanel.childObjectDecline.test.tsx index 24e1a548c15..bd34c53c7a5 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.childObjectDecline.test.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.childObjectDecline.test.tsx @@ -247,8 +247,9 @@ describe('record:line_items — an unresolvable panel offers no editable grid (o // assertion so a failure names which affordance came back. expect(view.container.querySelector('[data-testid="line-items"]')).toBeNull(); expect(view.container.querySelector('[data-testid="line-items-add"]')).toBeNull(); - // No cell to type in — the ghost row is what made the save path reachable in - // ONE keystroke, without the Add button being touched at all. + // No cell to type in — the always-present entry row the grid drew then + // (objectstack#35507 removed it) made the save path reachable in ONE + // keystroke, without the Add button being touched at all. expect(view.container.querySelector('input[aria-label="Qty"]')).toBeNull(); // ⛔ And NOT a spinner that never ends: hiding a permanent authoring error @@ -276,7 +277,7 @@ describe('record:line_items — an unresolvable panel offers no editable grid (o expect(view.container.querySelector('[data-testid="line-items-no-child-object"]')).toBeNull(); expect(view.container.querySelector('[data-testid="line-items"]')).not.toBeNull(); - expect(view.container.querySelector('input[aria-label="Qty"]')).not.toBeNull(); + expect(view.container.querySelector('[data-testid="line-items-add"]')).not.toBeNull(); }); it('refuses to save when the child object is dropped from a panel with dirty rows', async () => { @@ -295,6 +296,10 @@ describe('record:line_items — an unresolvable panel offers no editable grid (o ); await settle(); + // A line to dirty (the grid draws no trailing entry row, objectstack#35507). + await act(async () => { + fireEvent.click(view.container.querySelector('[data-testid="line-items-add"]') as HTMLButtonElement); + }); const cell = view.container.querySelector('input[aria-label="Qty"]') as HTMLInputElement; expect(cell).not.toBeNull(); await act(async () => { diff --git a/ui/packages/plugin-form/src/LineItemsPanel.fieldWriteGate-10163.test.tsx b/ui/packages/plugin-form/src/LineItemsPanel.fieldWriteGate-10163.test.tsx index f72052318ab..facc8f52ec6 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.fieldWriteGate-10163.test.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.fieldWriteGate-10163.test.tsx @@ -116,12 +116,11 @@ function mount(perms: any | null, schema: any = SCHEMA) { ); } -/** Every rendered cell of one column — the two loaded rows plus the entry row. */ +/** Every rendered cell of one column — the two loaded rows (no entry row follows them, objectstack#35507). */ async function cells(label: string): Promise { return waitFor(() => { const els = screen.getAllByLabelText(label) as HTMLInputElement[]; - // Two loaded rows and the grid's always-present entry row. - if (els.length < ROWS.length + 1) throw new Error(`${label} cells not rendered yet`); + if (els.length < ROWS.length) throw new Error(`${label} cells not rendered yet`); return els; }); } diff --git a/ui/packages/plugin-form/src/LineItemsPanel.heldForAnotherParent-10740.test.tsx b/ui/packages/plugin-form/src/LineItemsPanel.heldForAnotherParent-10740.test.tsx index 41dda5b81c8..25093fabeaf 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.heldForAnotherParent-10740.test.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.heldForAnotherParent-10740.test.tsx @@ -147,11 +147,22 @@ const answerLines = (read: LinesRead, ...lines: Array<{ id: string; label: strin settle(() => read.resolve({ data: lines })); const fail = (read: Deferred, message: string) => settle(() => read.reject(new Error(message))); -/** The grid's line inputs; the grid always trails one blank entry row. */ +/** The grid's line inputs (it draws no trailing entry row, objectstack#35507). */ const lineInputs = () => Array.from(document.body.querySelectorAll('input[aria-label="Line"]')) as HTMLInputElement[]; -/** The lines the grid draws (its trailing blank row is not a line). */ +/** The lines the grid draws (a blank one is not counted). */ const shownLines = () => lineInputs().map((input) => input.value).filter((value) => value !== ''); +/** Press the grid's Add once it is drawn, and wait for the new line. */ +const addLine = async () => { + const add = await waitFor(() => { + const el = document.body.querySelector('[data-testid="line-items-add"]') as HTMLButtonElement | null; + if (!el) throw new Error('grid not drawn yet'); + return el; + }); + const before = lineInputs().length; + await settle(() => { fireEvent.click(add); }); + await waitFor(() => expect(lineInputs().length).toBeGreaterThan(before)); +}; const saveButton = () => Array.from(document.body.querySelectorAll('button')).find((b) => /^(Save|Saving…)$/.test(b.textContent ?? '')) as | HTMLButtonElement @@ -247,9 +258,9 @@ describe('LineItemsPanel refuses the lines it holds for another parent (objectui const view = mount(dataSource, linesBlock()); await fail(await nth(lineReads, 1), 'p1 load failed'); await waitFor(() => expect(bannerShows('p1 load failed')).toBe(true)); - // The first failure leaves the empty grid on screen (its entry row is - // there), as before this card. A line typed into it is p1's. - await waitFor(() => expect(lineInputs().length).toBeGreaterThan(0)); + // The first failure leaves the empty grid on screen, as before this card. + // A line added and typed into it is p1's. + await addLine(); await editFirstLine('new p1 line'); await waitFor(() => expect(shownLines()).toEqual(['new p1 line'])); expect(saveButton()?.disabled).toBe(false); @@ -274,9 +285,9 @@ describe('LineItemsPanel refuses the lines it holds for another parent (objectui ); // No adapter: the load declines before any fetch and the panel offers its - // empty grid (its entry row) for p1. A line typed there is p1's. + // empty grid for p1. A line added there is p1's. const view = render(tree(linesBlock(), null)); - await waitFor(() => expect(lineInputs().length).toBeGreaterThan(0)); + await addLine(); await editFirstLine('typed under p1'); await waitFor(() => expect(shownLines()).toEqual(['typed under p1'])); expect(dataSource.find).not.toHaveBeenCalled(); @@ -392,8 +403,9 @@ describe('what the rule leaves alone (objectui#10740 controls)', () => { await waitFor(() => expect(bannerShows('p1 load failed')).toBe(true)); expect(placeholder()).toBeNull(); - // The grid is on screen: its entry row is drawn, no line is. - await waitFor(() => expect(lineInputs().length).toBeGreaterThan(0)); + // The grid is on screen (its Add button), and no line is. + await waitFor(() => expect(document.body.querySelector('[data-testid="line-items-add"]')).not.toBeNull()); + expect(lineInputs()).toHaveLength(0); expect(shownLines()).toEqual([]); expect(saveButton()?.disabled, 'a clean panel offered Save').toBe(true); }); diff --git a/ui/packages/plugin-form/src/LineItemsPanel.tsx b/ui/packages/plugin-form/src/LineItemsPanel.tsx index a26b5445f23..cd0e3330d84 100644 --- a/ui/packages/plugin-form/src/LineItemsPanel.tsx +++ b/ui/packages/plugin-form/src/LineItemsPanel.tsx @@ -26,7 +26,7 @@ import { CardTitle, cn, } from '@object-ui/components'; -import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import type { GridFieldMetadata } from '@object-ui/types'; import { createSafeTranslation, useLocalization } from '@object-ui/i18n'; import { useSchemaContext, useRecordContext, useFilterScope, useResolvedFilter, useDataInvalidation, usePrintPage, NonGridRowCeilingNote } from '@object-ui/react'; @@ -765,6 +765,12 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch () => lookupAutofillByField(childSchema?.fields as Record | undefined), [childSchema], ); + // Each child field's help, on its column header (objectstack#35804), read + // from the same served definition the record form reads. + const lineColumnHelp = useMemo( + () => columnHelpByField(childSchema?.fields as Record | undefined), + [childSchema], + ); const gridField = useMemo( () => @@ -912,6 +918,7 @@ export const LineItemsPanel: React.FC<{ schema: LineItemsPanelSchema }> = ({ sch // targets in the row. Empty until that schema arrives. lookupAutofill={lineLookupAutofill} columnCurrencies={lineColumnCurrencies} + columnHelp={lineColumnHelp} readonly={schema.readonly} // No input while the save is in flight (objectui#10631): `save` // reloads the rows once the batch lands, so a line edited in the diff --git a/ui/packages/plugin-form/src/MasterDetailForm.detailEntryIdentity.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.detailEntryIdentity.test.tsx index 8c9250ae5ae..f0177bc033d 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.detailEntryIdentity.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.detailEntryIdentity.test.tsx @@ -97,6 +97,8 @@ function formSchema(details: any[]) { /** Type an amount into the (single) resolved collection's grid. */ async function enterLineTotal(value: string) { + // The grid draws no trailing entry row (objectstack#35507): Add the line first. + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const cell = await waitFor(() => screen.getAllByLabelText('Line Total')[0] as HTMLInputElement); fireEvent.change(cell, { target: { value } }); return cell; diff --git a/ui/packages/plugin-form/src/MasterDetailForm.editBaselineAdvance.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.editBaselineAdvance.test.tsx index 6edafab30dc..a274a492b60 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.editBaselineAdvance.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.editBaselineAdvance.test.tsx @@ -105,7 +105,13 @@ function renderForm(opts: { } const saveButton = () => screen.getByTestId('md-form-submit') as HTMLButtonElement; -const qtyInputs = () => screen.getAllByLabelText('Qty') as HTMLInputElement[]; +const qtyInputs = () => screen.queryAllByLabelText('Qty') as HTMLInputElement[]; +/** Press the grid's Add: the grid draws no trailing entry row (objectstack#35507). */ +const addLine = async () => { + await act(async () => { + fireEvent.click(screen.getByTestId('line-items-add')); + }); +}; /** The parent form has its values and the stored lines have landed. */ async function ready(container: HTMLElement, mode: 'create' | 'edit', storedLines: number) { @@ -114,8 +120,9 @@ async function ready(container: HTMLElement, mode: 'create' | 'edit', storedLine if (!ref) throw new Error('parent form not ready'); if (mode === 'edit' && ref.value !== 'PO-1') throw new Error('parent record not loaded'); }); - // Every stored line plus the grid's trailing ghost row. - await waitFor(() => expect(qtyInputs()).toHaveLength(storedLines + 1)); + // The grid is drawn, with every stored line (and no entry row below them). + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); + await waitFor(() => expect(qtyInputs()).toHaveLength(storedLines)); await waitFor(() => expect(saveButton().disabled).toBe(false)); } @@ -144,7 +151,8 @@ describe('a mounted master-detail edit form: the next save diffs against what th const { container, onSuccess } = renderForm({ batchTransaction: batch }); await ready(container, 'edit', 0); - await change(qtyInputs()[0], '5'); // type into the ghost row + await addLine(); + await change(qtyInputs()[0], '5'); await save(() => batch.mock.calls.length); expect(onSuccess).toHaveBeenCalledTimes(1); expect(childOps(batch, 0)).toEqual([ @@ -154,7 +162,7 @@ describe('a mounted master-detail edit form: the next save diffs against what th // Nothing changed: no child operation at all — not a second create. await save(() => batch.mock.calls.length); expect(childOps(batch, 1)).toEqual([]); - expect(qtyInputs()).toHaveLength(2); // the one line, and the ghost row + expect(qtyInputs()).toHaveLength(1); // the one line // The created row carries the server's id now: editing it is an update. await change(qtyInputs()[0], '6'); @@ -196,6 +204,7 @@ describe('a mounted master-detail edit form: the next save diffs against what th const { container, onSuccess } = renderForm({ batchTransaction: batch }); await ready(container, 'edit', 0); + await addLine(); await change(qtyInputs()[0], '5'); await act(async () => { fireEvent.click(saveButton()); @@ -252,7 +261,8 @@ describe('a FAILED save advances neither baseline: the retry carries every opera await change(container.querySelector('input[name="ref"]') as HTMLElement, 'PO-2'); await change(qtyInputs()[0], '2'); - await change(qtyInputs()[1], '7'); // the ghost row + await addLine(); + await change(qtyInputs()[1], '7'); await save(() => batch.mock.calls.length); expect(onError).toHaveBeenCalledTimes(1); expect(onSuccess).not.toHaveBeenCalled(); @@ -294,6 +304,7 @@ describe('a FAILED save advances neither baseline: the retry carries every opera await change(container.querySelector('input[name="ref"]') as HTMLElement, 'PO-2'); await change(qtyInputs()[0], '2'); + await addLine(); await change(qtyInputs()[1], '7'); await save(() => create.mock.calls.length); expect(onError).toHaveBeenCalledTimes(1); @@ -316,6 +327,7 @@ describe('create mode is unchanged (control)', () => { const batch = echoBatch(); const { container, onSuccess } = renderForm({ mode: 'create', batchTransaction: batch }); await ready(container, 'create', 0); + await addLine(); await change(container.querySelector('input[name="ref"]') as HTMLElement, 'PO-9'); await change(qtyInputs()[0], '5'); @@ -326,9 +338,8 @@ describe('create mode is unchanged (control)', () => { { object: 'po_line', action: 'create', data: { qty: 5, po: { $ref: 0 } } }, ]); - // Lines back to the lone ghost row, header cleared. - await waitFor(() => expect(qtyInputs()).toHaveLength(1)); - expect(qtyInputs()[0].value).toBe(''); + // Lines back to none, header cleared. + await waitFor(() => expect(qtyInputs()).toHaveLength(0)); await waitFor(() => expect((container.querySelector('input[name="ref"]') as HTMLInputElement).value).toBe(''), ); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.elementDataSource.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.elementDataSource.test.tsx index 1f1c1125ea4..ed0e6d6871e 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.elementDataSource.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.elementDataSource.test.tsx @@ -289,6 +289,8 @@ describe('object-master-detail-form — dataSource: { object } (objectstack#7121 return el; }); fireEvent.change(number, { target: { value: 'INV-9' } }); + // A line (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const qty = await waitFor(() => screen.getAllByLabelText('Qty')[0] as HTMLInputElement); fireEvent.change(qty, { target: { value: '5' } }); fireEvent.click(screen.getByRole('button', { name: /^create$/i })); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.headerKeystrokePendingWork-28471.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.headerKeystrokePendingWork-28471.test.tsx index 633cd31c9fa..b70c58f2293 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.headerKeystrokePendingWork-28471.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.headerKeystrokePendingWork-28471.test.tsx @@ -26,7 +26,7 @@ * pending work is a page re-render scheduled just before the keystroke. */ import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, screen, waitFor, act } from '@testing-library/react'; +import { render, screen, waitFor, act, fireEvent } from '@testing-library/react'; import React from 'react'; import { flushSync } from 'react-dom'; import { registerAllFields } from '@object-ui/fields'; @@ -120,6 +120,8 @@ describe('MasterDetailForm — a header keystroke is never dropped (objectstack# return el; }); const qty = () => screen.getAllByLabelText('Qty')[0] as HTMLInputElement; + // A line (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); await waitFor(() => expect(qty().disabled).toBe(false)); // The element right under the React root container: above the form host, diff --git a/ui/packages/plugin-form/src/MasterDetailForm.inlineColumnsSortAmount-11144.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.inlineColumnsSortAmount-11144.test.tsx index 1ad90534017..e709a1808dc 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.inlineColumnsSortAmount-11144.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.inlineColumnsSortAmount-11144.test.tsx @@ -99,7 +99,7 @@ function dataSource(child: ReturnType) { }; } -/** Type into the given row's cell (the trailing ghost row materializes a new line). */ +/** Type into the given row's cell. */ function typeCell(label: string, row: number, value: string) { const cell = screen.getAllByLabelText(label)[row] as HTMLInputElement; fireEvent.change(cell, { target: { value } }); @@ -129,14 +129,16 @@ async function enterReorderAndSave(detail: Record, child = line expect(el).not.toBeNull(); return el!; }); + // The grid draws no trailing entry row (objectstack#35507): each line is Added. + const add = await waitFor(() => screen.getByTestId('line-items-add')); + fireEvent.click(add); await waitFor(() => expect(screen.getAllByLabelText('Description')).toHaveLength(1)); - typeCell('Description', 0, 'A'); - await waitFor(() => expect(screen.getAllByLabelText('Description')).toHaveLength(2)); typeCell('Qty', 0, '2'); typeCell('Unit Price', 0, '5'); + fireEvent.click(add); + await waitFor(() => expect(screen.getAllByLabelText('Description')).toHaveLength(2)); typeCell('Description', 1, 'B'); - await waitFor(() => expect(screen.getAllByLabelText('Description')).toHaveLength(3)); typeCell('Qty', 1, '1'); typeCell('Unit Price', 1, '3'); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.lateHeaderRecord-13062.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.lateHeaderRecord-13062.test.tsx index 328edd05e1f..d3999d8e4d0 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.lateHeaderRecord-13062.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.lateHeaderRecord-13062.test.tsx @@ -146,6 +146,8 @@ describe('MasterDetailForm — a late header record still drives parent-scoped l />, ); const status = await statusInput(container, ''); + // A line (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); await waitFor(() => expect(qty().disabled).toBe(false)); // A create form reads no record. expect(ds.findOne).not.toHaveBeenCalled(); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.lineGrant-12082.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.lineGrant-12082.test.tsx index f22a844e741..2d4ca174731 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.lineGrant-12082.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.lineGrant-12082.test.tsx @@ -108,11 +108,12 @@ async function lineLoaded() { await waitFor(() => expect(screen.getByDisplayValue('3')).toBeTruthy()); } -/** A create form: wait for the grid, then type into the entry row so it becomes a line. */ +/** A create form: wait for the grid, press Add and type into the new line (the grid draws no trailing entry row, objectstack#35507). */ async function addLineViaEntryRow(value: string) { + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const cells = await waitFor(() => { const els = screen.getAllByLabelText('Qty') as HTMLInputElement[]; - if (els.length === 0) throw new Error('grid not drawn yet'); + if (els.length === 0) throw new Error('line not drawn yet'); return els; }); fireEvent.change(cells[cells.length - 1], { target: { value } }); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.saveInFlight.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.saveInFlight.test.tsx index 71b28737791..8483004003e 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.saveInFlight.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.saveInFlight.test.tsx @@ -138,7 +138,7 @@ function renderForm(opts: { } const saveButton = () => screen.getByTestId('md-form-submit') as HTMLButtonElement; -const qtyInputs = () => screen.getAllByLabelText('Qty') as HTMLInputElement[]; +const qtyInputs = () => screen.queryAllByLabelText('Qty') as HTMLInputElement[]; const refInput = (container: HTMLElement) => container.querySelector('input[name="ref"]') as HTMLInputElement; /** The parent form has its values and the stored lines have landed. */ @@ -148,8 +148,9 @@ async function ready(container: HTMLElement, mode: 'create' | 'edit', storedLine if (!ref) throw new Error('parent form not ready'); if (mode === 'edit' && ref.value !== 'PO-1') throw new Error('parent record not loaded'); }); - // Every stored line plus the grid's trailing ghost row. - await waitFor(() => expect(qtyInputs()).toHaveLength(storedLines + 1)); + // The grid is drawn, with every stored line (and no entry row below them). + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); + await waitFor(() => expect(qtyInputs()).toHaveLength(storedLines)); await waitFor(() => expect(saveButton().disabled).toBe(false)); } @@ -165,6 +166,9 @@ const click = async (el: HTMLElement) => { }); }; +/** Press the grid's Add: the grid draws no trailing entry row (objectstack#35507). */ +const addLine = () => click(screen.getByTestId('line-items-add')); + /** Let real time run past the 1.5 s the old guard re-armed Save after. */ const pastTheOldGuard = () => act(async () => { @@ -188,7 +192,7 @@ async function save(calls: () => number) { /** The child operations of the batch sent on save number `n` (0-based). */ const childOps = (batch: any, n: number): Op[] => (batch.mock.calls[n][0] as Op[]).slice(1); -/** No line of the grid takes input: every cell is disabled, and there is no ghost row, add or remove. */ +/** No line of the grid takes input: every cell is disabled, and there is no add or remove. */ function expectGridInert(lines: number) { expect(qtyInputs()).toHaveLength(lines); for (const input of qtyInputs()) expect(input.disabled).toBe(true); @@ -202,6 +206,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { const { container, onSuccess } = renderForm({ batchTransaction: batch }); await ready(container, 'edit', 0); + await addLine(); await change(qtyInputs()[0], '5'); await click(saveButton()); await waitFor(() => expect(batch).toHaveBeenCalledTimes(1)); @@ -230,6 +235,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { const { container, onSuccess, onError } = renderForm({ batchTransaction: batch }); await ready(container, 'edit', 0); + await addLine(); await change(qtyInputs()[0], '5'); await click(saveButton()); await waitFor(() => expect(batch).toHaveBeenCalledTimes(1)); @@ -244,7 +250,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { expect(onSuccess).not.toHaveBeenCalled(); expect(await screen.findByText('The server refused the batch')).toBeTruthy(); // The grid takes input again after a failure, too. - expect(qtyInputs()).toHaveLength(2); + expect(qtyInputs()).toHaveLength(1); expect(qtyInputs()[0].disabled).toBe(false); await save(() => batch.mock.calls.length); @@ -261,6 +267,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { }); await ready(container, 'create', 0); + await addLine(); await change(qtyInputs()[0], '5'); // the required header field stays empty await click(saveButton()); expect(saveButton().disabled).toBe(true); @@ -279,6 +286,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { await ready(container, 'create', 0); await change(refInput(container), 'PO-9'); + await addLine(); await change(qtyInputs()[0], '5'); await click(saveButton()); await waitFor(() => expect(batch).toHaveBeenCalledTimes(1)); @@ -296,7 +304,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); await waitFor(() => expect(saveButton().disabled).toBe(false)); // Cleared for the next entry, and still exactly one create. - await waitFor(() => expect(qtyInputs()).toHaveLength(1)); + await waitFor(() => expect(qtyInputs()).toHaveLength(0)); await waitFor(() => expect(refInput(container).value).toBe('')); expect(batch).toHaveBeenCalledTimes(1); }); @@ -306,6 +314,7 @@ describe('the Save guard holds until the batch settles, not for 1.5 s', () => { const { container, onSuccess, onError } = renderForm({ batchTransaction: batch }); await ready(container, 'edit', 0); + await addLine(); await change(qtyInputs()[0], '5'); // The header form is the first
: an implicit submission (Enter in a // header that has a single text input) reaches it without the Save button. @@ -340,8 +349,10 @@ describe('the lines take no input while the save is in flight, so the created li const held = heldBatch(); const view = renderForm({ batchTransaction: held.batch, detail, lineSchema }); await ready(view.container, 'edit', 0); + await addLine(); await change(qtyInputs()[0], '5'); - await change(qtyInputs()[1], '7'); // the new ghost row + await addLine(); + await change(qtyInputs()[1], '7'); await click(saveButton()); await waitFor(() => expect(held.batch).toHaveBeenCalledTimes(1)); return { ...held, ...view }; @@ -369,7 +380,7 @@ describe('the lines take no input while the save is in flight, so the created li }); await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); await waitFor(() => expect(saveButton().disabled).toBe(false)); - await waitFor(() => expect(qtyInputs()).toHaveLength(3)); // the ghost row is back + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); // Add is back expect(qtyInputs()[1].disabled).toBe(false); await save(() => batch.mock.calls.length); @@ -400,7 +411,7 @@ describe('the lines take no input while the save is in flight, so the created li }); await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); await waitFor(() => expect(saveButton().disabled).toBe(false)); - await waitFor(() => expect(qtyInputs()).toHaveLength(3)); + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); await save(() => batch.mock.calls.length); expect(childOps(batch, 1)).toEqual([]); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.storedLineOrder-12286.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.storedLineOrder-12286.test.tsx index 36dcba5825b..674bdbf874b 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.storedLineOrder-12286.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.storedLineOrder-12286.test.tsx @@ -141,12 +141,12 @@ async function ready(container: HTMLElement, ds: FakeServer, lines: number) { }); await waitFor(() => expect(lineReads(ds).length).toBeGreaterThanOrEqual(2)); await act(async () => {}); - await waitFor(() => expect(descriptions()).toHaveLength(lines + 1)); + await waitFor(() => expect(descriptions()).toHaveLength(lines)); await waitFor(() => expect(saveButton().disabled).toBe(false)); } -/** The order the grid draws: each stored line's description, the entry row left off. */ -const drawn = () => descriptions().slice(0, -1).map((el) => el.value); +/** The order the grid draws: each stored line's description (no entry row follows them, objectstack#35507). */ +const drawn = () => descriptions().map((el) => el.value); /** Save, and return the batch's child operations. */ async function saveChildOps(batch: ReturnType['batch']): Promise { @@ -271,7 +271,7 @@ describe('the line read orders by the line-position field the spec names, and by const ref = container.querySelector('input[name="ref"]') as HTMLInputElement | null; expect(ref?.value).toBe('INV-1'); }); - await waitFor(() => expect(descriptions()).toHaveLength(3)); + await waitFor(() => expect(descriptions()).toHaveLength(2)); await act(async () => {}); expect(drawn()).toEqual(['Widget A units', 'Consulting hours']); const reads = lineReads(ds); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx index 2e58ea8d86b..dbcc112782a 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -187,7 +187,9 @@ describe('MasterDetailForm — non-atomic fallback (emulation via runBatchTransa return el; }); fireEvent.change(input, { target: { value: 'PO-1' } }); - // Fill the first (ghost) line so it persists as a real child row. + // Add and fill a first line so it persists as a real child row (the grid + // draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const qty = await waitFor(() => screen.getAllByLabelText('Qty')[0] as HTMLInputElement); fireEvent.change(qty, { target: { value: '5' } }); } @@ -274,6 +276,8 @@ describe('MasterDetailForm — parent-scoped line rules ("paid invoice → lock return el; }); const qty = () => screen.getAllByLabelText('Qty')[0] as HTMLInputElement; + // A line to lock: the grid draws no trailing entry row (objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); // Header not paid → the Qty cell is editable. await waitFor(() => expect(qty().disabled).toBe(false)); @@ -298,6 +302,8 @@ describe('MasterDetailForm — parent-scoped line rules ("paid invoice → lock return el; }); + // A line to lock: the grid draws no trailing entry row (objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); fireEvent.change(status, { target: { value: 'paid' } }); // The scrape-driven lock must NOT wipe the value the user just typed. await waitFor(() => expect((screen.getAllByLabelText('Qty')[0] as HTMLInputElement).disabled).toBe(true)); @@ -345,3 +351,50 @@ describe('MasterDetailForm — showSubmit gate (Studio screen preview)', () => { expect(cancelBtn).toHaveTextContent('取消'); }); }); + +/** + * objectstack#35804 — the line grid's column headers show each child field's + * help, read from the child object's definition as `getObjectSchema` serves + * it: the definition the record form reads too, so a help another package + * wrote through `objectExtensions.fieldPatches` (applied by the server before + * it serves the object) and the reader's language both arrive here. + */ +describe('MasterDetailForm — line column headers show the child fields\' help (objectstack#35804)', () => { + const lineSchema = { + name: 'po_line', + fields: { + po: { type: 'lookup', label: 'PO', reference: 'po' }, + // The served definition: `description` carries what a patch or a + // translation put there, and `inlineHelpText` wins over it. + qty: { type: 'number', label: 'Qty', description: 'Whole units only.' }, + price: { type: 'number', label: 'Price', inlineHelpText: 'Tax-inclusive.', description: 'Not this.' }, + note: { type: 'text', label: 'Note' }, + }, + }; + const ds = () => + makeDataSource({ + getObjectSchema: vi.fn(async (name: string) => (name === 'po_line' ? lineSchema : parentSchema)), + }); + const schema = (detail: Record) => + ({ objectName: 'po', mode: 'create', fields: ['ref'], details: [detail] }) as any; + + it.each([ + ['derived columns', { childObject: 'po_line' }], + // The console's shape for a child field's `inlineColumns`: names the + // form hydrates from the child schema (a column declaring its `type` + // opts out of that hydration, and an entry whose every column does loads + // no child schema, so it has no help to show, as it has no lookup + // autofill pairs). + [ + 'authored columns', + { childObject: 'po_line', relationshipField: 'po', columns: [{ name: 'qty' }, { name: 'price' }, { name: 'note' }] }, + ], + ])('%s: each header carries its field\'s help, the form\'s own read of it', async (_label, detail) => { + render(); + const qtyHelp = await screen.findByRole('button', { name: 'Whole units only.' }); + expect(qtyHelp.closest('th')!.textContent).toContain('Qty'); + expect(screen.getByRole('button', { name: 'Tax-inclusive.' }).closest('th')!.textContent).toContain('Price'); + // CONTROL: a field with no help draws no info button on its header. + expect(screen.getByRole('columnheader', { name: 'Note' }).querySelector('button')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-form/src/MasterDetailForm.totalsCurrency-11132.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.totalsCurrency-11132.test.tsx index 9d8ef658d37..5149a4ce3fa 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.totalsCurrency-11132.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.totalsCurrency-11132.test.tsx @@ -110,6 +110,8 @@ async function renderStack(opts: { , ); + // The grid draws no trailing entry row (objectstack#35507): Add the line first. + fireEvent.click(await waitFor(() => screen.getAllByTestId('line-items-add')[0])); const cell = await waitFor(() => screen.getAllByLabelText('Line Total')[0] as HTMLInputElement); fireEvent.change(cell, { target: { value: '1234.5' } }); const rate = await waitFor(() => { diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 292f17ff7a3..657734d901c 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -33,7 +33,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type BooleanValueLabel, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; +import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -436,6 +436,14 @@ interface DetailEntry { * configured entry skips the fetch). Internal state, never authored. */ lookupAutofill?: LookupAutofillByField; + /** + * The child fields' help text, by field name (`columnHelpByField`), read + * from the schema the resolve effect loaded, the definition the record form + * reads too, and handed to the line grid's column headers (`GridField`'s + * `columnHelp`, objectstack#35804). Absent when no schema was loaded for + * this entry. Internal state, never authored. + */ + columnHelp?: ColumnHelp; /** * The child fields whose currency follows the header through this entry's * relationship (ADR-0144 D2 as amended), by name, read from the schema the @@ -1109,7 +1117,7 @@ const MasterDetailLines: React.FC = ({ setRows(entry.id, rows)} - // The grid's own `disabled`: cells locked, and no ghost row, add, + // The grid's own `disabled`: cells locked, and no add, // duplicate, remove or reorder while the save is in flight // (objectui#10631). Its row "expand" control stays; the editor it // opens is held by the same state in . @@ -1121,6 +1129,8 @@ const MasterDetailLines: React.FC = ({ // The child fields' declared `lookupAutofill` pairs: a lookup // cell's pick fills their targets in the row. lookupAutofill={entry.lookupAutofill} + // Each child field's help, on its column header (objectstack#35804). + columnHelp={entry.columnHelp} // The columns whose amount follows this header's currency // (ADR-0144 D2 as amended), in the header's live code. columnCurrencies={followedColumnCurrencies(entry.parentCurrencyFields, parentRecord, tenantCurrency)} @@ -1152,8 +1162,8 @@ const MasterDetailLines: React.FC = ({ sortField: entry.sortField, minRows: d.minRows, maxRows: d.maxRows, - // The map rows above: the grid's Add, entry row and Duplicate - // follow `allowAdd`, its per-row Remove `allowDelete`. + // The map rows above: the grid's Add and Duplicate follow + // `allowAdd`, its per-row Remove `allowDelete`. allowAdd: lineAddGranted, allowDelete: lineRemoveGranted, addLabel: d.inlineMode === 'form' ? (d.addLabel || t('detail.add')) : d.addLabel, @@ -1393,6 +1403,7 @@ export const MasterDetailForm: React.FC = ({ amountFieldDef: childFieldDef(childSchema, amountField), columnsWith, lookupAutofill: lookupAutofillByField(childSchema?.fields as Record | undefined), + columnHelp: columnHelpByField(childSchema?.fields as Record | undefined), parentCurrencyFields: parentCurrencyFieldsOf(childSchema?.fields as Record | undefined, d.relationshipField), }; } @@ -1411,6 +1422,7 @@ export const MasterDetailForm: React.FC = ({ amountFieldDef: childFieldDef(childSchema, amountField), columnsWith, lookupAutofill: lookupAutofillByField(childSchema?.fields as Record | undefined), + columnHelp: columnHelpByField(childSchema?.fields as Record | undefined), parentCurrencyFields: parentCurrencyFieldsOf(childSchema?.fields as Record | undefined, derived.relationshipField), }; } catch (err) { diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index 64851f4000c..cfd6caa7381 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -37,7 +37,7 @@ import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/types'; import { resolveAffordance, type SchemaLike } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import { cn } from '@object-ui/components'; import { usePermissions } from '@object-ui/permissions'; import { @@ -328,6 +328,8 @@ export const RecordBodyTableEditor: React.FC = ({ ob disabled={session.saving} contextRecord={record?.data as Record | undefined} lookupAutofill={lookupAutofillByField(childSchema?.fields as Record | undefined)} + // Each child field's help, on its column header (objectstack#35804). + columnHelp={columnHelpByField(childSchema?.fields as Record | undefined)} newRowValues={newRowValues} // objectstack#35816 — a new line's empty required cell reads red // once a save was refused, not the moment the line appears; the diff --git a/ui/packages/plugin-form/src/__tests__/lineItemsDeclaredInputs-11536.test.tsx b/ui/packages/plugin-form/src/__tests__/lineItemsDeclaredInputs-11536.test.tsx index 9c7a7400775..3e15c5af13a 100644 --- a/ui/packages/plugin-form/src/__tests__/lineItemsDeclaredInputs-11536.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/lineItemsDeclaredInputs-11536.test.tsx @@ -159,6 +159,13 @@ describe('record:line_items: each of the ten declared keys moves the panel (obje it('parentId saves a new line under that parent', async () => { const adapter = makeAdapter([]); mount(adapter, node({ parentId: 'p1' })); + // The grid draws no trailing entry row (objectstack#35507): Add the line. + const add = await waitFor(() => { + const el = document.body.querySelector('[data-testid="line-items-add"]') as HTMLButtonElement | null; + if (!el) throw new Error('grid not drawn yet'); + return el; + }); + fireEvent.click(add); const ops = await editAndSave(adapter); expect(ops).toEqual([{ object: 'po_line', action: 'create', data: { label: 'edited', amount: null, po: 'p1' } }]); }); @@ -268,17 +275,17 @@ describe('record:line_items: each of the ten declared keys moves the panel (obje mount(floored, node({ parentId: 'p1', minRows: 2 })); await linesDrawn(); expect(buttonsLabelled('Remove row').map((b) => b.disabled)).toEqual([true, true]); - // It adds no blank lines to reach the number: two lines plus the entry row. - expect(lineInputs()).toHaveLength(3); + // It adds no blank lines to reach the number: the two lines, no more. + expect(lineInputs()).toHaveLength(2); }); - it('maxRows disables Add line and Duplicate row and drops the entry row at that many lines; CONTROL: without it they stay', async () => { + it('maxRows disables Add line and Duplicate row at that many lines; CONTROL: without it they stay', async () => { const open = makeAdapter(); mount(open, node({ parentId: 'p1' })); await linesDrawn(); expect(buttonNamed('Add line')?.disabled).toBe(false); expect(buttonsLabelled('Duplicate row').map((b) => b.disabled)).toEqual([false, false]); - expect(lineInputs()).toHaveLength(3); + expect(lineInputs()).toHaveLength(2); cleanup(); const capped = makeAdapter(); diff --git a/ui/packages/plugin-form/src/__tests__/masterDetailDetailsMembers-8071.test.tsx b/ui/packages/plugin-form/src/__tests__/masterDetailDetailsMembers-8071.test.tsx index 0080d9e8d92..473510bcb76 100644 --- a/ui/packages/plugin-form/src/__tests__/masterDetailDetailsMembers-8071.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/masterDetailDetailsMembers-8071.test.tsx @@ -111,7 +111,7 @@ */ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import React from 'react'; import { registerAllFields, type GridColumn } from '@object-ui/fields'; import type { ObjectMasterDetailFormProps } from '@objectstack/spec/ui'; @@ -214,8 +214,26 @@ function gridOf(heading: string): Record { const headings = (container: HTMLElement) => Array.from(container.querySelectorAll('section > h3')).map((h) => h.textContent); -/** Fill the Nth ghost `Qty` cell (0-based), which turns it into a real line. */ +/** + * The line grid whose columns include `label`, its Add pressed until it draws + * line `n` (0-based): the grid draws no trailing entry row (objectstack#35507). + */ +async function addLineTo(label: string, n: number) { + const grid = await waitFor(() => { + const found = screen + .getAllByTestId('line-items') + .find((el) => within(el).queryAllByRole('columnheader', { name: label }).length > 0); + if (!found) throw new Error(`no grid with a ${label} column yet`); + return found; + }); + while (within(grid).queryAllByLabelText(label).length <= n) { + fireEvent.click(within(grid).getByTestId('line-items-add')); + } +} + +/** Fill the Nth `Qty` cell (0-based), adding lines until it exists. */ async function fillQty(n: number, value: string) { + await addLineTo('Qty', n); const cell = await waitFor(() => { const cells = screen.getAllByLabelText('Qty'); if (cells.length <= n) throw new Error(`no Qty cell ${n} yet`); @@ -402,6 +420,7 @@ describe('`object-master-detail-form` — the member shape of `details`', () => fireEvent.change(container.querySelector('input[name="ref"]')!, { target: { value: 'PO-1' } }); await fillQty(0, '5'); await fillQty(1, '7'); + await addLineTo('Note', 0); fireEvent.change(screen.getAllByLabelText('Note')[0], { target: { value: 'rush' } }); fireEvent.click(screen.getByRole('button', { name: /^create$/i })); diff --git a/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx index d8be54e4ead..42239fc864b 100644 --- a/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/modalMaximize-34604.test.tsx @@ -323,7 +323,8 @@ describe('#34604 — the master-detail (subforms) arm', () => { const { onOpenChange } = renderMd(); const title = await headerInput(); fireEvent.change(title, { target: { value: 'Q-1' } }); - await waitFor(() => expect(qtyInputs().length).toBeGreaterThan(0)); + // The grid is drawn: its Add button (the grid draws no trailing entry row, objectstack#35507). + await waitFor(() => expect(screen.getByTestId('line-items-add')).toBeTruthy()); const before = qtyInputs().length; fireEvent.click(screen.getByRole('button', { name: /add/i })); await waitFor(() => expect(qtyInputs().length).toBe(before + 1)); diff --git a/ui/packages/plugin-form/src/__tests__/topLevelFieldsWarnCoverage-8847.test.tsx b/ui/packages/plugin-form/src/__tests__/topLevelFieldsWarnCoverage-8847.test.tsx index 46837868556..88bdc82c5a2 100644 --- a/ui/packages/plugin-form/src/__tests__/topLevelFieldsWarnCoverage-8847.test.tsx +++ b/ui/packages/plugin-form/src/__tests__/topLevelFieldsWarnCoverage-8847.test.tsx @@ -248,8 +248,9 @@ describe('object-master-detail-form `fields` — the member shape (objectui#8071 it('a name the parent does not declare is dropped — a DETAIL column name included — while the line grid keeps its column', async () => { const { container } = await mountMembers({ fields: ['qty', 'status', 'nowhere'] }); expect(parentFields(container), 'no untyped stub for either name').toEqual(['status']); + // The column header, read on an empty grid (the grid draws no trailing entry row, objectstack#35507). expect( - screen.getAllByLabelText('Qty').length, + screen.getAllByRole('columnheader', { name: 'Qty' }).length, 'the detail vocabulary is untouched by the parent key', ).toBeGreaterThan(0); }); diff --git a/ui/packages/plugin-form/src/createFormGrant-12082.test.tsx b/ui/packages/plugin-form/src/createFormGrant-12082.test.tsx index 25d2757575c..fa104f68b89 100644 --- a/ui/packages/plugin-form/src/createFormGrant-12082.test.tsx +++ b/ui/packages/plugin-form/src/createFormGrant-12082.test.tsx @@ -278,6 +278,8 @@ describe('MasterDetailForm under a create-only grant on the child (objectui#1208 it('a create form\'s line cells are live: every line is an insert of the child', async () => { mountMD('create'); + // A line to read (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); for (const el of [...(await cells('Instalment No.')), ...(await cells('Instalment notes'))]) { expect(el.disabled).toBe(false); } @@ -285,7 +287,8 @@ describe('MasterDetailForm under a create-only grant on the child (objectui#1208 it('CONTROL — an edit form\'s line cells stay locked under the same grant', async () => { mountMD('edit'); - await waitFor(async () => expect((await cells('Instalment No.')).length).toBeGreaterThan(1)); + // The one stored line (the grid draws no trailing entry row, objectstack#35507). + await waitFor(async () => expect((await cells('Instalment No.')).length).toBe(1)); for (const el of [...(await cells('Instalment No.')), ...(await cells('Instalment notes'))]) { expect(el.disabled).toBe(true); } diff --git a/ui/packages/plugin-form/src/discardGuard.test.tsx b/ui/packages/plugin-form/src/discardGuard.test.tsx index 5ed6e8bc901..79a9556edee 100644 --- a/ui/packages/plugin-form/src/discardGuard.test.tsx +++ b/ui/packages/plugin-form/src/discardGuard.test.tsx @@ -344,6 +344,8 @@ describe('master-detail overlay unsaved-changes guard (objectstack#34599)', () = const onOpenChange = vi.fn(); render(); await headerInput(); + // A line to edit (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const amount = await waitFor(() => screen.getAllByLabelText('Amount')[0] as HTMLInputElement); fireEvent.change(amount, { target: { value: '42' } }); diff --git a/ui/packages/plugin-form/src/formChrome.i18n-11071.test.tsx b/ui/packages/plugin-form/src/formChrome.i18n-11071.test.tsx index 1970e427c03..5343ad94871 100644 --- a/ui/packages/plugin-form/src/formChrome.i18n-11071.test.tsx +++ b/ui/packages/plugin-form/src/formChrome.i18n-11071.test.tsx @@ -197,6 +197,8 @@ describe('MasterDetailForm chrome resolves through the i18n catalogue (objectui# // The header record has loaded and a line has been typed, so the save has // something to send. await waitFor(() => expect((container.querySelector('input[name="ref"]') as HTMLInputElement)?.value).toBe('PO-1')); + // A line to type into (the grid draws no trailing entry row, objectstack#35507). + fireEvent.click(await screen.findByTestId('line-items-add')); const cell = (await screen.findAllByLabelText('Line Total'))[0]; fireEvent.change(cell, { target: { value: '5' } }); await waitFor(() => expect(screen.getByTestId('md-form-submit')).not.toBeDisabled()); diff --git a/ui/packages/plugin-form/src/formFaces.displayLocale-9909.test.tsx b/ui/packages/plugin-form/src/formFaces.displayLocale-9909.test.tsx index 168b58083a7..bd5fd1f471d 100644 --- a/ui/packages/plugin-form/src/formFaces.displayLocale-9909.test.tsx +++ b/ui/packages/plugin-form/src/formFaces.displayLocale-9909.test.tsx @@ -128,6 +128,8 @@ const SURFACES: Surface[] = [ name: 'MasterDetailForm — subtotal stack', node: () => , read: async () => { + // The grid draws no trailing entry row (objectstack#35507): Add the line first. + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const cell = await waitFor(() => screen.getAllByLabelText('Line Total')[0] as HTMLInputElement); fireEvent.change(cell, { target: { value: '1234.5' } }); return waitFor(() => { diff --git a/ui/packages/plugin-form/src/submitHandlerSeam.test.tsx b/ui/packages/plugin-form/src/submitHandlerSeam.test.tsx index 69e9f586c6b..2b93b5dc2bf 100644 --- a/ui/packages/plugin-form/src/submitHandlerSeam.test.tsx +++ b/ui/packages/plugin-form/src/submitHandlerSeam.test.tsx @@ -117,7 +117,7 @@ const masterDetailSchema = (formType: string) => ({ }); /** - * Fill the parent header AND the first (ghost) line, so the save carries BOTH + * Fill the parent header AND a first line, so the save carries BOTH * legs. Without a real child row the batch would be a single-op list and the * atomicity claim would have nothing to be atomic about. */ @@ -128,6 +128,8 @@ async function fillHeaderAndLine(container: HTMLElement) { return el; }); fireEvent.change(ref, { target: { value: 'PO-1' } }); + // The grid draws no trailing entry row (objectstack#35507): Add the line first. + fireEvent.click(await waitFor(() => screen.getByTestId('line-items-add'))); const qty = await waitFor(() => screen.getAllByLabelText('Qty')[0] as HTMLInputElement); fireEvent.change(qty, { target: { value: '5' } }); }