From de846e7eb00eacb3ba2ecb22bb64cb99adbff1cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:55:03 +0000 Subject: [PATCH 1/8] feat(fields): the line-item grid's select and date cells open their panel under the cell (#36023 S5) Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- .../fields/src/widgets/GridField.test.tsx | 230 +++++++++++ ui/packages/fields/src/widgets/GridField.tsx | 185 ++++++--- .../fields/src/widgets/InCellOptionList.tsx | 10 +- .../fields/src/widgets/gridCellPanels.tsx | 383 ++++++++++++++++++ 4 files changed, 742 insertions(+), 66 deletions(-) create mode 100644 ui/packages/fields/src/widgets/gridCellPanels.tsx diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 8d01d64c1f5..87164692f81 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -997,3 +997,233 @@ describe('column header help (objectstack#35804)', () => { expect(columnHelpByField(undefined)).toEqual({}); }); }); + +describe('cell faces that open under the cell (objectstack#36023)', () => { + const STATUS = [ + { label: 'To Do', value: 'todo' }, + { label: 'Done', value: 'done' }, + { label: 'Doing', value: 'doing' }, + ]; + const cols = { + columns: [ + { name: 'description', label: 'Description', type: 'text' as const }, + { name: 'status', label: 'Status', type: 'select' as const, options: STATUS }, + { name: 'due_on', label: 'Due On', type: 'date' as const }, + { name: 'at', label: 'At', type: 'datetime' as const }, + { name: 'qty', label: 'Qty', type: 'number' as const }, + ], + } as any; + + function Stateful({ initial, onChange }: { initial: any[]; onChange?: (v: any[]) => void }) { + const [rows, setRows] = React.useState(initial); + return ( + { + setRows(v); + onChange?.(v); + }} + field={cols} + /> + ); + } + + describe('a select cell', () => { + it('shows the option label, and a click opens a searchable list under it; a pick writes and closes', async () => { + const onChange = vi.fn(); + render(); + const cell = screen.getByRole('combobox', { name: 'Status' }); + expect(cell.textContent).toBe('To Do'); + fireEvent.click(cell); + const panel = await screen.findByTestId('line-items-select-panel'); + // The cell keeps its value while the list is open. + expect(cell.textContent).toBe('To Do'); + const search = panel.querySelector('input') as HTMLInputElement; + await waitFor(() => expect(document.activeElement).toBe(search)); + fireEvent.change(search, { target: { value: 'do' } }); + expect(Array.from(panel.querySelectorAll('[role="option"]')).map((o) => o.textContent)).toEqual(['To Do', 'Done', 'Doing']); + fireEvent.change(search, { target: { value: 'don' } }); + fireEvent.click(screen.getByRole('option', { name: 'Done' })); + expect(onChange.mock.calls.at(-1)![0][0].status).toBe('done'); + await waitFor(() => expect(screen.queryByTestId('line-items-select-panel')).toBeNull()); + expect(screen.getByRole('combobox', { name: 'Status' }).textContent).toBe('Done'); + }); + + it('a typed letter opens the list with that letter as its search; Enter picks the first match', async () => { + const onChange = vi.fn(); + render(); + const cell = screen.getByRole('combobox', { name: 'Status' }); + cell.focus(); + fireEvent.keyDown(cell, { key: 'g' }); + const panel = await screen.findByTestId('line-items-select-panel'); + const search = panel.querySelector('input') as HTMLInputElement; + expect(search.value).toBe('g'); + expect(Array.from(panel.querySelectorAll('[role="option"]')).map((o) => o.textContent)).toEqual(['Doing']); + fireEvent.keyDown(search, { key: 'Enter' }); + expect(onChange.mock.calls.at(-1)![0][0].status).toBe('doing'); + }); + + it('Esc in the list closes it and writes nothing', async () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('combobox', { name: 'Status' })); + const panel = await screen.findByTestId('line-items-select-panel'); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('line-items-select-panel')).toBeNull()); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('Tab in the list closes it and moves on to the next cell', async () => { + render(); + fireEvent.click(screen.getByRole('combobox', { name: 'Status' })); + const panel = await screen.findByTestId('line-items-select-panel'); + fireEvent.keyDown(panel.querySelector('input')!, { key: 'Tab' }); + await waitFor(() => expect(screen.queryByTestId('line-items-select-panel')).toBeNull()); + expect(document.activeElement).toBe(screen.getAllByLabelText('Due On')[0]); + }); + + it('the arrows still move between lines from a select cell', () => { + render(); + const [first, second] = screen.getAllByRole('combobox', { name: 'Status' }); + first.focus(); + fireEvent.keyDown(first, { key: 'ArrowDown' }); + expect(document.activeElement).toBe(second); + expect(screen.queryByTestId('line-items-select-panel')).toBeNull(); + }); + }); + + describe('a date cell', () => { + it('stays the native control, typed into as before, and opens its calendar under the cell on arrival', async () => { + const onChange = vi.fn(); + render(); + const input = screen.getAllByLabelText('Due On')[0] as HTMLInputElement; + expect(input.type).toBe('date'); + fireEvent.focus(input); + expect(await screen.findByTestId('line-items-date-panel')).toBeTruthy(); + // The caret stays in the cell: keyboard entry is unchanged. + fireEvent.change(input, { target: { value: '2026-06-20' } }); + expect(onChange.mock.calls.at(-1)![0][0].due_on).toBe('2026-06-20'); + }); + + it('a calendar day writes the value and closes the calendar; the cell keeps the focus', async () => { + const onChange = vi.fn(); + render(); + const input = screen.getAllByLabelText('Due On')[0] as HTMLInputElement; + input.focus(); + const panel = await screen.findByTestId('line-items-date-panel'); + const day = Array.from(panel.querySelectorAll('button')).find((b) => b.textContent === '24')!; + fireEvent.click(day); + expect(onChange.mock.calls.at(-1)![0][0].due_on).toBe('2026-06-24'); + await waitFor(() => expect(screen.queryByTestId('line-items-date-panel')).toBeNull()); + expect(document.activeElement).toBe(screen.getAllByLabelText('Due On')[0]); + }); + + it('Clear empties the cell; Today writes today', async () => { + const onChange = vi.fn(); + render(); + let input = screen.getAllByLabelText('Due On')[0] as HTMLInputElement; + input.focus(); + fireEvent.click(await screen.findByTestId('line-items-date-clear')); + expect(onChange.mock.calls.at(-1)![0][0].due_on).toBe(''); + input = screen.getAllByLabelText('Due On')[0] as HTMLInputElement; + fireEvent.click(input); + const panel = await screen.findByTestId('line-items-date-panel'); + fireEvent.click(Array.from(panel.querySelectorAll('button')).find((b) => b.textContent === 'Today')!); + const d = new Date(); + const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + expect(onChange.mock.calls.at(-1)![0][0].due_on).toBe(today); + }); + + it('a date-time day keeps the time of day', async () => { + const onChange = vi.fn(); + render(); + const input = screen.getAllByLabelText('At')[0] as HTMLInputElement; + expect(input.type).toBe('datetime-local'); + input.focus(); + const panel = await screen.findByTestId('line-items-date-panel'); + fireEvent.click(Array.from(panel.querySelectorAll('button')).find((b) => b.textContent === '24')!); + const stored = onChange.mock.calls.at(-1)![0][0].at as string; + const back = new Date(stored); + expect([back.getFullYear(), back.getMonth() + 1, back.getDate(), back.getHours(), back.getMinutes()]).toEqual([2026, 6, 24, 9, 45]); + }); + + it('leaving the cell closes the calendar, and Enter still moves down', async () => { + render(); + const [first, second] = screen.getAllByLabelText('Due On'); + first.focus(); + await screen.findByTestId('line-items-date-panel'); + fireEvent.keyDown(first, { key: 'Enter' }); + expect(document.activeElement).toBe(second); + }); + }); + + describe('Esc in a cell', () => { + it('takes back what this visit to the cell typed, and only that line', () => { + const onChange = vi.fn(); + render(); + const input = screen.getAllByLabelText('Description')[0] as HTMLInputElement; + input.focus(); + fireEvent.change(input, { target: { value: 'Abc' } }); + fireEvent.keyDown(input, { key: 'Escape' }); + const last = onChange.mock.calls.at(-1)![0]; + expect(last[0]).toEqual({ description: 'A', qty: 1 }); + expect(last[1]).toEqual({ description: 'B', qty: 2 }); + expect((screen.getAllByLabelText('Description')[0] as HTMLInputElement).value).toBe('A'); + }); + + it('keeps the untouched mark of a new line it takes back', () => { + const onChange = vi.fn(); + render(); + const input = screen.getAllByLabelText('Description')[0] as HTMLInputElement; + input.focus(); + fireEvent.change(input, { target: { value: 'x' } }); + fireEvent.keyDown(input, { key: 'Escape' }); + expect(isUntouchedNewRow(onChange.mock.calls.at(-1)![0][0])).toBe(true); + }); + + it('does not reach a dialog the form is open in: the dialog and every line stay', async () => { + const { Dialog, DialogContent, DialogTitle } = await import('@object-ui/components'); + const onOpenChange = vi.fn(); + render( + + + Lines + + + , + ); + const input = screen.getAllByLabelText('Description')[0] as HTMLInputElement; + input.focus(); + fireEvent.change(input, { target: { value: 'Abc' } }); + fireEvent.keyDown(input, { key: 'Escape' }); + fireEvent.keyDown(input, { key: 'Escape' }); + expect(onOpenChange).not.toHaveBeenCalled(); + expect((screen.getAllByLabelText('Description')[0] as HTMLInputElement).value).toBe('A'); + // A cell's open calendar takes the Esc itself: it closes, the dialog stays. + const date = screen.getAllByLabelText('Due On')[0] as HTMLInputElement; + date.focus(); + await screen.findByTestId('line-items-date-panel'); + fireEvent.keyDown(date, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByTestId('line-items-date-panel')).toBeNull()); + expect(onOpenChange).not.toHaveBeenCalled(); + }); + + it('control: Esc outside the grid still reaches the dialog', async () => { + const { Dialog, DialogContent, DialogTitle } = await import('@object-ui/components'); + const onOpenChange = vi.fn(); + render( + + + Lines + + + + , + ); + const outside = screen.getByRole('button', { name: 'outside' }); + outside.focus(); + fireEvent.keyDown(outside, { key: 'Escape' }); + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + }); +}); diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index 44fda94024d..7703a9c2dfb 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -4,11 +4,6 @@ import { cn, Button, Input, - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, Popover, PopoverTrigger, PopoverContent, @@ -32,6 +27,8 @@ 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 { GRID_CELL_CONTROL_CLASS, GridDateCell, GridSelectCell, GrowingCellInput } from './gridCellPanels.js'; +import { isImeKey } from './imeKey.js'; import type { InlineGridColumn } from '@objectstack/spec/data'; import { GRID_FIELD_RETIRED_KEYS, type GridFieldMetadata, type GridFieldRetiredKey } from '@object-ui/types'; @@ -1174,6 +1171,64 @@ function GridFieldBody({ [focusCell, rows.length, allowAdd, isList, addRow], ); + /** + * Esc in a cell takes back what this visit to the cell changed + * (objectstack#36023): the line returns to what it held when the cell was + * entered, its other cells included (a lookup pick's autofill), and the + * untouched mark of a new line with it. The key stops at the grid, so a + * form open in a dialog keeps its dialog and every other line: Esc in a + * cell never closes it. A cell whose panel is open hands Esc to the panel, + * which closes and writes nothing. + * + * Read on the window's capture phase, ahead of the dialog's own document + * listener, which would close the dialog before any handler in the table + * ran. + */ + const cellVisit = useRef<{ key: string; rowIdx: number; row: Row } | null>(null); + const rowsRef = useRef(rows); + const emitRef = useRef(emit); + React.useLayoutEffect(() => { + rowsRef.current = rows; + emitRef.current = emit; + }); + const cellKeyOf = (el: EventTarget | null): { key: string; rowIdx: number } | null => { + const cell = el instanceof Element ? el.closest('[data-grid-cell]') : null; + const key = cell?.getAttribute('data-grid-cell'); + if (!cell || !key || !gridRef.current?.contains(cell)) return null; + return { key, rowIdx: Number(key.slice(0, key.indexOf(':'))) }; + }; + const onGridFocus = (e: React.FocusEvent) => { + const at = cellKeyOf(e.target); + if (!at || cellVisit.current?.key === at.key) return; + const row = rowsRef.current[at.rowIdx]; + cellVisit.current = row ? { key: at.key, rowIdx: at.rowIdx, row } : null; + }; + const onGridBlur = (e: React.FocusEvent) => { + const to = e.relatedTarget as Element | null; + // Into a cell's own panel (portaled out of the table) is still the visit. + if (to && (gridRef.current?.contains(to) || to.closest('[data-radix-popper-content-wrapper]'))) return; + cellVisit.current = null; + }; + const editable = !readonly && !isList; + React.useEffect(() => { + if (!editable) return; + const onKey = (e: KeyboardEvent) => { + if (e.key !== 'Escape' || e.defaultPrevented || isImeKey({ nativeEvent: e, keyCode: e.keyCode })) return; + const at = cellKeyOf(e.target); + if (!at) return; + const cell = (e.target as Element).closest('[data-grid-cell]'); + if (cell?.querySelector('[aria-expanded="true"]')) return; + e.stopPropagation(); + e.preventDefault(); + const visit = cellVisit.current; + const current = rowsRef.current; + if (!visit || visit.key !== at.key || current[visit.rowIdx] === visit.row) return; + emitRef.current(current.map((r, i) => (i === visit.rowIdx ? visit.row : r)), false); + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [editable]); + const removeRow = useCallback( (rowIdx: number) => { if (rows.length <= minRows) return; @@ -1488,22 +1543,20 @@ function GridFieldBody({ /> ); } + // objectstack#36023 — the option list opens under the cell, searchable, + // and a pick writes the value; the cell keeps showing the label meanwhile. if (c.type === 'select') { return ( - + ({ value: String(o.value), label: o.label }))} + value={val} + onPick={(v) => setCell(rowIdx, c, v)} + disabled={locked} + invalid={invalid} + label={c.label || c.name} + onNavKeyDown={(e) => onCellKeyDown(e, rowIdx, colIdx)} + data-cell={`${rowIdx}-${colIdx}`} + /> ); } // The editable currency cell shows the SAME symbol its display face does @@ -1513,68 +1566,71 @@ function GridFieldBody({ // not exist (objectui#10474, objectui#10567): its control can paint that // only blank — the `date` control sanitises the verbatim day // `toDateInputValue` keeps, so it is handed `""` below, as the `datetime` - // adapter already does — so the stored string is named under it and the - // control is marked invalid. Nothing is written until the user picks a new - // value — the same face `DateField` / `DateTimeField` give it. + // adapter already does — so the + // control is marked invalid, its description naming the stored string. + // Nothing is written until the user picks a new value — the same face + // `DateField` / `DateTimeField` give it. const impossibleDay = (c.type === 'date' || c.type === 'datetime') && isImpossibleStoredDay(val); const noticeId = impossibleDay ? `${cellIdBase}-impossible-${rowIdx}-${colIdx}` : undefined; + const impossibleText = impossibleDay + ? t(c.type === 'date' ? 'fields.date.impossibleDay' : 'fields.dateTime.impossibleDay', { value: String(val) }) + : null; + // objectstack#36023 — a date or date-time cell is still typed into, and + // its calendar opens under the cell on arrival. The stored-day notice + // reads at the top of that calendar, and stays the control's description + // (out of sight in the cell, so the row keeps its height). + if (c.type === 'date' || c.type === 'datetime') { + return ( + <> + onCellKeyDown(e, rowIdx, colIdx)} + className={cn(GRID_CELL_CONTROL_CLASS, PHONE_TOUCH_HEIGHT)} + nativeValue={c.type === 'date' ? (impossibleDay ? '' : toDateInputValue(val)) : toDateTimeInputValue(val)} + onNativeChange={(next) => setCell(rowIdx, c, next)} + notice={impossibleText} + disabled={locked} + /> + {impossibleDay && ( + + {impossibleText} + + )} + + ); + } + // A text cell floats right over its neighbours while its text is longer + // than the column (objectstack#36023); numbers and times keep their box. + const CellInput = !c.type || c.type === 'text' ? GrowingCellInput : Input; return (
{adornment && ( {adornment} )} - onCellKeyDown(e, rowIdx, colIdx)} className={cn( - 'h-8 rounded-none border-0 bg-transparent px-2 shadow-none focus-visible:ring-1 focus-visible:ring-ring/60', + GRID_CELL_CONTROL_CLASS, PHONE_TOUCH_HEIGHT, adornment && 'pl-6', isNumeric(c.type) && 'text-right tabular-nums', )} - type={ - c.type === 'date' - ? 'date' - : c.type === 'datetime' - ? 'datetime-local' - : c.type === 'time' - ? 'time' - : isNumeric(c.type) - ? 'number' - : 'text' - } + type={c.type === 'time' ? 'time' : isNumeric(c.type) ? 'number' : 'text'} step={isNumeric(c.type) ? c.step ?? 'any' : undefined} aria-label={c.label || c.name} - // A temporal cell holding the API's ISO shape (`2026-06-17T14:30:00.000Z`) - // is SILENTLY rejected by the native control — the attribute lands in - // the DOM but `input.value` reads back `''` and the cell paints empty - // (objectui#3566, the sub-grid face of #3127). So each type reads - // through its own adapter: - // date → `YYYY-MM-DD`; the control writes that shape back - // verbatim, so no paired conversion on `onChange`. - // datetime → `YYYY-MM-DDTHH:mm` local; PAIRED with - // `fromDateTimeInputValue` in `coerce` so read and write - // share one basis (objectui#3569). - // time → `HH:mm[:ss]` is already the stored shape, both ways. - value={ - c.type === 'date' - ? (impossibleDay ? '' : toDateInputValue(val)) - : c.type === 'datetime' - ? toDateTimeInputValue(val) - : val != null - ? String(val) - : '' - } + // `time` reads and writes `HH:mm[:ss]`, the stored shape, both ways; + // the date types read through their adapters above (objectui#3566). + value={val != null ? String(val) : ''} onChange={(e) => setCell(rowIdx, c, e.target.value)} disabled={locked} /> - {impossibleDay && ( -

- {t(c.type === 'date' ? 'fields.date.impossibleDay' : 'fields.dateTime.impossibleDay', { value: String(val) })} -

- )}
); }; @@ -1602,8 +1658,8 @@ function GridFieldBody({ data-testid="line-items" > {columnChooser &&
{columnChooser}
} -
- +
+
@@ -1725,6 +1781,7 @@ function GridFieldBody({ // travels with `invalid` into `renderCellInput`. title={invalid ? requiredCellText(c) : undefined} data-testid={invalid ? `line-items-invalid-${rowIdx}-${c.name}` : undefined} + data-grid-cell={`${rowIdx}:${c.name}`} className={cn( 'border-r border-border/40 px-1 py-0.5 align-middle last:border-r-0', isList && 'px-2 py-1.5', diff --git a/ui/packages/fields/src/widgets/InCellOptionList.tsx b/ui/packages/fields/src/widgets/InCellOptionList.tsx index c874b775921..dfff8bf122e 100644 --- a/ui/packages/fields/src/widgets/InCellOptionList.tsx +++ b/ui/packages/fields/src/widgets/InCellOptionList.tsx @@ -22,6 +22,9 @@ export interface InCellOption { * editor stays open and commits when the user moves on. * - `onAdd` (tags) — when the typed text matches no row, an "Add" row writes it. * + * - `initialQuery` — the search text it opens with: the line-item grid opens + * the list on a typed letter, which becomes the first letter of the search. + * * Enter that picks is kept from the grid (`stopPropagation`): the grid's own * Enter would commit the value it held before the pick. With no active row, * Enter goes on to the grid, which commits and moves down. Escape always goes @@ -36,6 +39,7 @@ export function InCellOptionList({ placeholder, testId, inputProps, + initialQuery, }: { options: readonly InCellOption[]; selected: readonly string[]; @@ -46,10 +50,12 @@ export function InCellOptionList({ testId?: string; /** The host's DOM pass-through (id, aria-describedby, …), onto the search box. */ inputProps?: React.InputHTMLAttributes; + /** The search text the list opens with; absent opens it unfiltered. */ + initialQuery?: string; }) { const { t } = useFieldTranslation(); const listId = React.useId(); - const [query, setQuery] = React.useState(''); + const [query, setQuery] = React.useState(initialQuery ?? ''); const needle = query.trim().toLocaleLowerCase(); const shown = needle ? options.filter((o) => o.label.toLocaleLowerCase().includes(needle)) : options; const addText = onAdd && query.trim() !== '' && !options.some((o) => o.label === query.trim()) ? query.trim() : null; @@ -63,7 +69,7 @@ export function InCellOptionList({ // list, which is the list shown again when the search box is cleared (an // index into the filtered list would land on another option then). const initialActive = multiple ? -1 : options.findIndex((o) => selected.includes(o.value)); - const [active, setActive] = React.useState(initialActive); + const [active, setActive] = React.useState(() => (query.trim() ? 0 : initialActive)); const listRef = React.useRef(null); React.useEffect(() => { diff --git a/ui/packages/fields/src/widgets/gridCellPanels.tsx b/ui/packages/fields/src/widgets/gridCellPanels.tsx new file mode 100644 index 00000000000..7c19e92e6bd --- /dev/null +++ b/ui/packages/fields/src/widgets/gridCellPanels.tsx @@ -0,0 +1,383 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The line-item grid's cell faces that open a panel under the cell + * (objectstack#36023): a select cell's searchable option list, a date or + * date-time cell's calendar, and a text cell that floats right over its + * neighbours while its text is longer than the column. + * + * The grid stays a typing-first grid: a text, number or date cell is a live + * input the user types into on arrival, and a panel never takes that away. + * Every face keeps the row's height: a panel floats over the table, and the + * cell keeps drawing its value while it is open. + */ + +import React from 'react'; +import { + cn, + Calendar, + Button, + Input, + Popover, + PopoverContent, + PopoverTrigger, +} from '@object-ui/components'; +import { InCellOptionList, type InCellOption } from './InCellOptionList.js'; +import { useFieldTranslation } from './useFieldTranslation.js'; +import { PHONE_TOUCH_HEIGHT } from './touchTarget.js'; +import { fromLocalDay, toLocalDay } from './date-picker/localeDateText.js'; + +/** The flat face every line-item cell control shares (no border, radius or fill of its own). */ +export const GRID_CELL_CONTROL_CLASS = + 'h-8 rounded-none border-0 bg-transparent px-2 shadow-none focus-visible:ring-1 focus-visible:ring-ring/60'; + +/** The panel's popper box: under the cell, at least as wide as it. */ +const PANEL_CLASS = 'w-auto min-w-[var(--radix-popover-trigger-width)] p-1'; + +/** + * The tabbable control after (or before) `from` in its table, so Tab pressed + * inside a panel (which the popover portals out of the table) still moves to + * the next cell. `null` at either end. + */ +function neighbourTabbable(from: HTMLElement, backwards: boolean): HTMLElement | null { + const table = from.closest('table'); + if (!table) return null; + const all = Array.from( + table.querySelectorAll('input, button, select, textarea, [tabindex]:not([tabindex="-1"])'), + ).filter((el) => !(el as HTMLInputElement).disabled && el.tabIndex >= 0); + const at = all.indexOf(from); + if (at < 0) return null; + return all[at + (backwards ? -1 : 1)] ?? null; +} + +/** A key that types a character: it opens a select cell's list as its search. */ +function isTypedCharacter(e: React.KeyboardEvent): boolean { + return e.key.length === 1 && e.key !== ' ' && !e.ctrlKey && !e.metaKey && !e.altKey; +} + +export interface GridSelectCellProps { + options: readonly InCellOption[]; + value: unknown; + onPick: (value: string) => void; + disabled?: boolean; + invalid?: boolean; + label: string; + /** The grid's own key handler: the arrows move between lines. */ + onNavKeyDown: (e: React.KeyboardEvent) => void; + 'data-cell': string; +} + +/** + * A select cell: the cell shows the option's label; a click, Enter, Space, + * F2 or Alt+ArrowDown opens the searchable list under it, and a typed letter + * opens it with that letter as the search. A pick writes the value and + * closes the list; Esc closes it and writes nothing. Tab moves on to the next + * cell, as from any other cell. + */ +export function GridSelectCell({ + options, + value, + onPick, + disabled, + invalid, + label, + onNavKeyDown, + 'data-cell': dataCell, +}: GridSelectCellProps) { + const [open, setOpen] = React.useState(false); + const [initialQuery, setInitialQuery] = React.useState(undefined); + const triggerRef = React.useRef(null); + const current = value == null || value === '' ? null : String(value); + const shown = current == null ? null : options.find((o) => o.value === current)?.label ?? current; + + const openList = (query?: string) => { + setInitialQuery(query); + setOpen(true); + }; + + return ( + + + + + { + // The search box takes the caret, after any letter it opened with. + e.preventDefault(); + const box = (e.currentTarget as HTMLElement | null)?.querySelector('input'); + if (!box) return; + box.focus(); + box.setSelectionRange(box.value.length, box.value.length); + }} + onKeyDown={(e) => { + if (e.key !== 'Tab') return; + // The panel lives outside the table, so Tab is moved on by hand. + e.preventDefault(); + setOpen(false); + const trigger = triggerRef.current; + if (!trigger) return; + (neighbourTabbable(trigger, e.shiftKey) ?? trigger).focus(); + }} + > + { + onPick(v); + setOpen(false); + }} + /> + + + ); +} + +export interface GridDateCellProps extends Omit, 'value' | 'onChange'> { + /** `date` or `datetime`: which native control, and what a calendar day writes. */ + kind: 'date' | 'datetime'; + /** The native control's value: `YYYY-MM-DD`, or `YYYY-MM-DDTHH:mm`. */ + nativeValue: string; + /** Write a native-shaped value (`''` clears). */ + onNativeChange: (next: string) => void; + /** A notice about the stored value, drawn at the top of the panel. */ + notice?: React.ReactNode; +} + +/** + * A date or date-time cell: the browser's own control stays in the cell, so + * the value is typed exactly as before, and the calendar opens under the cell + * as soon as the cell is entered, with today / tomorrow / next week / clear. + * A day picked writes the value (a date-time keeps its time) and closes the + * calendar; the cell keeps the focus. Leaving the cell closes it. + */ +export function GridDateCell({ kind, nativeValue, onNativeChange, notice, className, ...inputProps }: GridDateCellProps) { + const { t } = useFieldTranslation(); + const [open, setOpen] = React.useState(false); + const inputRef = React.useRef(null); + const panelRef = React.useRef(null); + // A focus the panel itself hands back to the cell does not reopen it. + const quietFocus = React.useRef(false); + // A pick in the panel hands the focus back to the cell once the panel is gone. + const refocus = React.useRef(false); + const disabled = !!inputProps.disabled; + + const day = nativeValue ? nativeValue.slice(0, 10) : ''; + const selected = day ? fromLocalDay(day) : undefined; + + const finish = (next: string) => { + onNativeChange(next); + refocus.current = true; + setOpen(false); + }; + const pickDay = (picked: Date | undefined) => { + if (!picked) return; + const nextDay = toLocalDay(picked); + finish(kind === 'datetime' ? `${nextDay}T${nativeValue.slice(11, 16) || '00:00'}` : nextDay); + }; + const shortcut = (offsetDays: number) => { + const d = new Date(); + d.setHours(0, 0, 0, 0); + d.setDate(d.getDate() + offsetDays); + pickDay(d); + }; + + return ( + + + onNativeChange(e.target.value)} + className={cn( + // The browser's own calendar button gives way to the panel. + '[&::-webkit-calendar-picker-indicator]:hidden', + className, + )} + onFocus={(e) => { + inputProps.onFocus?.(e); + if (!quietFocus.current) setOpen(true); + }} + onClick={(e) => { + // The trigger's own toggle is replaced: a click on the cell opens, never closes. + e.preventDefault(); + inputProps.onClick?.(e); + setOpen(true); + }} + onBlur={(e) => { + inputProps.onBlur?.(e); + const to = e.relatedTarget as Node | null; + if (to && panelRef.current?.contains(to)) return; + setOpen(false); + }} + /> + + e.preventDefault()} + onCloseAutoFocus={(e) => { + e.preventDefault(); + if (!refocus.current) return; + refocus.current = false; + quietFocus.current = true; + inputRef.current?.focus(); + quietFocus.current = false; + }} + onInteractOutside={(e) => { + if (inputRef.current?.contains(e.target as Node)) e.preventDefault(); + }} + > + {notice ?
{notice}
: null} + +
+ + + {/* Seven days from today (ruling of record 7057128455). */} + + +
+
+
+ ); +} + +/** + * A text cell's input that, while it holds the focus and its text is longer + * than the column, floats right over the neighbouring cells (as far as the + * grid's own scroll box allows) instead of scrolling its text out of sight. + * The column and the row keep their size: a spacer holds the cell's place. + */ +export const GrowingCellInput = React.forwardRef>( + function GrowingCellInput({ className, onFocus, onBlur, onInput, ...props }, forwardedRef) { + const ownRef = React.useRef(null); + const [width, setWidth] = React.useState(null); + const setRefs = (el: HTMLInputElement | null) => { + ownRef.current = el; + if (typeof forwardedRef === 'function') forwardedRef(el); + else if (forwardedRef) forwardedRef.current = el; + }; + + const measure = () => { + const el = ownRef.current; + const cell = el?.parentElement; + if (!el || !cell || document.activeElement !== el) return; + const base = cell.clientWidth; + // The text's own width: what the input would need to show all of it. + const needed = el.scrollWidth + 2; + if (needed <= base) { + setWidth(null); + return; + } + const box = cell.closest('[data-line-items-scroll]') ?? cell.closest('table'); + const room = box ? box.getBoundingClientRect().right - cell.getBoundingClientRect().left - 4 : needed; + setWidth(Math.max(base, Math.min(needed, room))); + }; + // The value is controlled by the grid; measure after each render it changes. + React.useLayoutEffect(measure, [props.value]); + + return ( +
+ {width != null ?
: null} + { + onFocus?.(e); + measure(); + }} + onInput={(e) => { + onInput?.(e); + measure(); + }} + onBlur={(e) => { + onBlur?.(e); + setWidth(null); + }} + /> +
+ ); + }, +); From 84d9a5d7fabc9a4a1d7c2a1b608af56d8846b3d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:56:14 +0000 Subject: [PATCH 2/8] docs(fields): the line-item grid's cell panels, and their changeset (#36023 S5) Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- .changeset/36023-line-grid-cell-panels.md | 18 ++++++++++++++++++ ui/packages/fields/README.md | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 .changeset/36023-line-grid-cell-panels.md diff --git a/.changeset/36023-line-grid-cell-panels.md b/.changeset/36023-line-grid-cell-panels.md new file mode 100644 index 00000000000..b04ac2c7ea0 --- /dev/null +++ b/.changeset/36023-line-grid-cell-panels.md @@ -0,0 +1,18 @@ +--- +'@object-ui/fields': patch +--- + +feat(fields): the line-item grid's select and date cells open their panel under the cell, and Esc in a cell takes back only that cell + +Clause-②: no +Metadata-protocol: none + +In a form's line-item grid (`GridField`, the master-detail lines): + +- A **select** cell shows its option label; a click, Enter, Space or a typed letter opens a searchable option list under the cell (the letter becomes the search), and a pick writes the value. Esc closes the list and writes nothing. +- A **date** or **date-time** cell keeps the browser's own control, typed into as before, and opens a calendar under the cell when the cell is entered, with Today, Tomorrow, Next week and Clear. A day picked on a date-time keeps its time of day. +- A **text** cell whose text is longer than the column floats right over its neighbours while it has the focus. +- **Esc** in a cell puts the line back as it was when the cell was entered, and no longer reaches a dialog the form is open in, so the dialog and its other lines stay. +- A stored day that does not exist is named at the top of the calendar and in the cell's tooltip instead of a line under the cell, so the row keeps its height. + +Enter still moves to the next line (and adds one on the last line). Nothing a metadata author writes changes. diff --git a/ui/packages/fields/README.md b/ui/packages/fields/README.md index bfeaf8ef475..2c547916114 100644 --- a/ui/packages/fields/README.md +++ b/ui/packages/fields/README.md @@ -349,6 +349,29 @@ or photo per row without opening the row form (objectui#2360). Columns accept exported as `FileCell`). Auto-derived subform columns map `file`/`image`/ `avatar` fields to file columns instead of dropping them. +### Cell panels in line-item grids + +`GridField` stays a typing-first grid: a text, number, currency, time or date +cell is a live input the user types into on arrival, and Enter moves to the +same column of the next line (on the last line it adds one). What opens a panel +opens it under the cell, over the table, and the row keeps its height: + +- **Select** — the cell shows the option label. A click, Enter, Space, F2 or + Alt+ArrowDown opens a searchable option list under it; a typed letter opens it + with that letter as the search. A pick writes the value and closes the list; + Esc closes it and writes nothing; Tab moves on to the next cell. +- **Date and date-time** — the browser's own control stays in the cell, typed + into as before, and the calendar opens under the cell when the cell is + entered, with Today, Tomorrow, Next week and Clear. A day writes the value (a + date-time keeps its time of day) and the cell keeps the focus. +- **Text** — while the cell has the focus and its text is longer than the + column, the input floats right over the neighbouring cells instead of + scrolling its text out of sight. +- **Esc in a cell** takes back what this visit to the cell changed (the whole + line returns to what it held when the cell was entered) and stops there: a + form open in a dialog keeps its dialog. A cell whose panel is open hands Esc + to the panel. + ### Registry-name pickers (`position-ref`, `permission-ref`) A `text` field that stores the machine name of one registry item declares From 7e888d4fb8af834e8d2ceb2ce9df5748570fe8bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 09:56:29 +0000 Subject: [PATCH 3/8] docs(form): editing in the line-item grid (#36023 S5) Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- content/docs/frontend/plugins/plugin-form.mdx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/content/docs/frontend/plugins/plugin-form.mdx b/content/docs/frontend/plugins/plugin-form.mdx index 05c19339df2..9628bc1a730 100644 --- a/content/docs/frontend/plugins/plugin-form.mdx +++ b/content/docs/frontend/plugins/plugin-form.mdx @@ -101,6 +101,16 @@ Which fields an edit save sends, and which fields and line-item actions a caller A select governed by the object's blocking `state_machine` validation offers only the values the server accepts. On an edit form that is the stored value plus its declared next states; on a create form it is the machine's `initialStates`, plus the value the form opens with (a `default: true` option or a caller's pre-fill), which is never dropped. A machine that declares no `initialStates`, or a `warning`, inactive or update-only one, leaves a create form's options as they are. Every form layout, the master-detail header included, applies the same rule. +## Editing in the line-item grid + +The child grid of a master-detail form (and of `record:line_items`) is typed into directly: click a cell or Tab to it and type, and Enter moves to the same column of the next line (on the last line it adds one). Choice cells open a panel under the cell, over the table, so the row keeps its height: + +- a **select** cell opens a searchable option list on a click, Enter, Space or a typed letter, and a pick writes the value; +- a **date** or **date-time** cell keeps its typed control and shows a calendar under the cell, with Today, Tomorrow, Next week and Clear; +- a **text** cell whose text is longer than the column floats right over its neighbours while you type. + +Esc in a cell takes back what you changed in that cell and goes no further: a form open in a dialog stays open, with its other lines. + ## Field Types The plugin supports these field types: From f46f745e98c977d4d030bccf3e4752da008a9e24 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 10:04:13 +0000 Subject: [PATCH 4/8] fix(fields): keep the line grid's day helpers out of the lazy date-picker chunk (#36023 S5) Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- ui/packages/fields/src/widgets/gridCellPanels.tsx | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/ui/packages/fields/src/widgets/gridCellPanels.tsx b/ui/packages/fields/src/widgets/gridCellPanels.tsx index 7c19e92e6bd..c761e4081e7 100644 --- a/ui/packages/fields/src/widgets/gridCellPanels.tsx +++ b/ui/packages/fields/src/widgets/gridCellPanels.tsx @@ -31,7 +31,18 @@ import { import { InCellOptionList, type InCellOption } from './InCellOptionList.js'; import { useFieldTranslation } from './useFieldTranslation.js'; import { PHONE_TOUCH_HEIGHT } from './touchTarget.js'; -import { fromLocalDay, toLocalDay } from './date-picker/localeDateText.js'; + +// The two day helpers are spelled here rather than imported from +// `./date-picker/`: that directory is its own lazy chunk, and the line-item +// grid is in the Console's eager closure. +const pad2 = (n: number) => String(n).padStart(2, '0'); +/** The local calendar day of `d` as `YYYY-MM-DD`. */ +const toLocalDay = (d: Date): string => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; +/** Local midnight of a `YYYY-MM-DD` day, for the calendar to select. */ +function fromLocalDay(day: string): Date | undefined { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day); + return m ? new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])) : undefined; +} /** The flat face every line-item cell control shares (no border, radius or fill of its own). */ export const GRID_CELL_CONTROL_CLASS = From 50c8b8c034898813687aba5d82c552486bcc8a7c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 10:06:18 +0000 Subject: [PATCH 5/8] test(fields): load the dialog primitives at module top (#36023 S5) Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- ui/packages/fields/src/widgets/GridField.test.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index 87164692f81..d763a5587f5 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -2,6 +2,7 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent, waitFor } 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 { GridField, LineItemsField, sumColumn, lookupAutofillPatch, UNTOUCHED_NEW_ROW, isUntouchedNewRow, columnHelpByField } from './GridField'; @@ -1182,7 +1183,6 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { }); it('does not reach a dialog the form is open in: the dialog and every line stay', async () => { - const { Dialog, DialogContent, DialogTitle } = await import('@object-ui/components'); const onOpenChange = vi.fn(); render( @@ -1208,8 +1208,7 @@ describe('cell faces that open under the cell (objectstack#36023)', () => { expect(onOpenChange).not.toHaveBeenCalled(); }); - it('control: Esc outside the grid still reaches the dialog', async () => { - const { Dialog, DialogContent, DialogTitle } = await import('@object-ui/components'); + it('control: Esc outside the grid still reaches the dialog', () => { const onOpenChange = vi.fn(); render( From 99536b01548a81abd0ad0c7f5b80d955ec2dedd2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 10:29:30 +0000 Subject: [PATCH 6/8] fix(fields): show a grown line-grid text cell from its start, centre the day panel (#36023 S5) Measured in the running Console: the floated text input kept the scroll the narrow cell needed, so the first characters stayed clipped, and the calendar sat left in a panel the shortcut row widened. Claude-Session: https://claude.ai/code/session_01L6bhgXrmZgxib5C1kX7vnD Co-authored-by: Claude --- .../fields/src/widgets/gridCellPanels.tsx | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/ui/packages/fields/src/widgets/gridCellPanels.tsx b/ui/packages/fields/src/widgets/gridCellPanels.tsx index c761e4081e7..2e99539c5c6 100644 --- a/ui/packages/fields/src/widgets/gridCellPanels.tsx +++ b/ui/packages/fields/src/widgets/gridCellPanels.tsx @@ -299,7 +299,7 @@ export function GridDateCell({ kind, nativeValue, onNativeChange, notice, classN defaultMonth={selected} selected={selected} onSelect={pickDay} - className="[--cell-size:2.75rem] sm:[--cell-size:2rem]" + className="mx-auto bg-transparent [--cell-size:2.75rem] sm:[--cell-size:2rem]" />
#