diff --git a/.changeset/35684-35687-list-cells-select-first.md b/.changeset/35684-35687-list-cells-select-first.md index 2c09483711c..1f1609dae28 100644 --- a/.changeset/35684-35687-list-cells-select-first.md +++ b/.changeset/35684-35687-list-cells-select-first.md @@ -18,8 +18,8 @@ Skills-docs: none — `skills/objectstack-ui/rules/list-views.md` already teache **The select-first cell model** (`data-table`, behind the new `GridCellSelectionProvider` in `@object-ui/components`; `ObjectGrid` mounts it when its host passes the new `cellSelection` prop, and `ListView` passes it for every `object-grid` view it draws, on the hosts listed below): - A click selects a cell (a ring around it) and neither edits it nor opens the record. A link the cell draws (the name, a lookup, a phone or an email) keeps its own click. A touch tap opens the record and never edits in place. -- Double-click, Enter or F2 edits, keeping the value with the caret at its end; typing a character replaces the value with it (a picker or a date opens instead); Backspace or Delete opens an empty editor and saves nothing. -- While editing, Enter commits and moves down, Tab and Shift+Tab commit and move right and left, Escape cancels and keeps the cell selected; in a multi-line editor Enter is a new line and Ctrl/Cmd+Enter commits. Commits are the grid's staged edits, saved by the row's Save and Save All as before. +- Double-click, Enter or F2 edits, keeping the value with the caret at its end; typing a character replaces the value with it (a picker or a date opens instead); Backspace or Delete clears the cell and saves at once, and a required field keeps its value and says it is required (objectstack#36023). +- While editing, Enter commits and stays on the cell (objectstack#36023), Tab and Shift+Tab commit and move right and left, Escape cancels and keeps the cell selected; in a multi-line editor Enter is a new line and Ctrl/Cmd+Enter commits. Commits are the grid's staged edits, saved by the row's Save and Save All as before. - On the selected cell the arrows and Tab move the selection, Space opens the record (a checkbox cell flips and commits instead, as a second click on it does), Ctrl/Cmd+C copies, Ctrl/Cmd+V converts the text to the field's type and commits it, and Escape clears the selection. - An input method's composition is kept whole: keys pressed while composing, and the 229 Enter Safari raises after it, never commit, cancel or move, and a composition started on a selected cell opens the editor with the composed text. This guard applies to every `data-table` editor. - A cell that opens no editor says why on the cell: the field is read-only, calculated or not editable in a list, the reader may not edit the field, these records or this record, the view turned editing off, or the record is locked by an approval. The approval lock is read from the approvals service's per-record lock when a cell of the row is selected, through the record page's rule (`resolveApprovalLock`); until it answers, the row's `approval_status` stands in only where the view fetches that column, which a view that authors its columns does only when a column, a row predicate or a grouping names it. diff --git a/.changeset/36023-cell-panel-below.md b/.changeset/36023-cell-panel-below.md new file mode 100644 index 00000000000..65dfc562392 --- /dev/null +++ b/.changeset/36023-cell-panel-below.md @@ -0,0 +1,26 @@ +--- +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +'@object-ui/fields': patch +'@object-ui/i18n': patch +--- + +feat(ui): in a list cell, a picker opens under the cell, Backspace clears, a refused value stays, and Enter stays on the cell + +Clause-②: yes (widening) +Metadata-protocol: none + +`GridCellFacts` (the select-first grid's per-cell host facts, `@object-ui/components`) gains three optional keys: `editor` (`'below'` draws the cell's editor as a panel under the cell, which keeps showing its value; absent or `'cover'`, the editor stays a layer over the cell), `clearRefusal` (why Backspace or Delete leave the cell as it is) and `validate` (why a committed value is refused). A host that sets none of them gets the editor placement and commits it had, with Backspace now clearing (below). + +In every grid `ObjectGrid` draws with the select-first model (the list page): + +- **Pickers open under the cell.** Single and multi select, status, tags, date, date-time, time, colour, lookup and user cells open their list, calendar or palette as a panel under the cell; the cell keeps its value as drawn (a coloured badge stays coloured) and the row height does not change. On a date the typeable box is the top of the panel and the calendar shows beneath it. Typed input, long text and an address still edit in place. +- **Backspace or Delete clears the selected cell and saves at once.** A required field keeps its value and says it is required (a required rating too, for Backspace, Delete and the 0 key); a read-only cell says why, as before; a checkbox cell is left alone. +- **A value that fails the field's rules is not saved.** The rules are the record form's (required, length, range, email and URL shape), and text a number box cannot read is refused too. The editor stays open with what was typed and says why under it (a number box that already says it cannot read its text is not told twice); correct it and commit again, or press Escape to discard. A click elsewhere does nothing while a refused value is open; a refused value whose cell scrolls out of sight is discarded. +- **A person's face no longer makes its row taller.** A user cell drew a 32 px face, which made its list row 41 px tall against 33 px for a row of text; the face is now 24 px and the row stays 33 px, at rest and while the cell is edited. +- **The selected cell's frame stays under the frozen columns** when the cell scrolls beneath them, and a cell deselected with Escape is left with no focus ring. +- **Enter saves and keeps the same cell selected**, with the focus back on it. It used to save and move the selection one row down. Tab and Shift+Tab still save and move right and left. + +`@object-ui/i18n` adds `table.cellNotNumber` and `table.cellInvalid` in every locale. + +Forms, dialogs and the record page keep their current controls. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index f681192d058..0938e415e7f 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -406,10 +406,20 @@ object and the view does not declare `userActions.editInline: false`, and into the editor in the same place and at the same size. - **Editing** starts on a double-click, Enter or F2 (the value kept, caret at its end), or by typing, which replaces the value; an input method's - composition is kept whole. Backspace or Delete opens an empty editor and - saves nothing yet. -- **While editing**, Enter commits and moves down, Tab / Shift+Tab commit and - move right / left, and Escape cancels and keeps the cell selected. In a + composition is kept whole. Backspace or Delete clears the cell and saves at + once; a required field keeps its value and says it is required. +- **Where the editor draws** (objectstack#36023): a picker (single and multi + select, status, tags, date, date-time, time, colour, a lookup or a user) + opens as a panel under the cell, which keeps showing its value; the date + panel has the typeable box on top and the calendar beneath. Typed input, + long text and an address edit in place over the cell. +- **A value that fails its rules is not saved**: the field's required, length, + range, email or URL rule, or text a number box cannot read. The editor stays + open with what was typed and says why under it; correct it and commit again, + or press Escape to discard. A click elsewhere does nothing meanwhile. +- **While editing**, Enter commits and keeps the same cell selected, Tab / + Shift+Tab commit and move right / left, and Escape cancels and keeps the cell + selected. In a multi-line editor Enter is a new line and Ctrl/Cmd+Enter commits. A click elsewhere commits. - **Selected cell keys:** the arrows and Tab move the selection; Space is typed diff --git a/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx index 97d00d2cb28..6dfd8e9773d 100644 --- a/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-cell-overlay-35688.test.tsx @@ -212,7 +212,7 @@ describe('data-table — typed values edit flat in the cell; a rating is set in expect(layer.className).toContain(':not([data-in-cell-input])]:h-8'); }); - function renderRating() { + function renderRating(facts: Record = {}) { const onCellChange = vi.fn(); const t = renderTable( { @@ -230,7 +230,7 @@ describe('data-table — typed values edit flat in the cell; a rating is set in data: [{ id: '1', name: 'Alpha', score: 2 }], onCellChange, }, - { describeCell: (_row, key) => (key === 'score' ? { stars: 5 } : null) }, + { describeCell: (_row, key) => (key === 'score' ? { stars: 5, ...facts } : null) }, ); return { ...t, onCellChange }; } @@ -250,6 +250,20 @@ describe('data-table — typed values edit flat in the cell; a rating is set in expect(t.editorLayer()).toBeNull(); }); + it('a required rating is never cleared: 0, Backspace and Delete keep its stars and say why (objectstack#36023)', () => { + const t = renderRating({ clearRefusal: 'Score is required' }); + fireEvent.click(t.cell(0, 1)); + for (const key of ['0', 'Backspace', 'Delete']) { + fireEvent.keyDown(t.catcher(), { key }); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(document.querySelector('[data-testid="cell-readonly-reason"]')).toHaveTextContent('Score is required'); + expect(t.cell(0, 1).querySelectorAll('[data-rating-star][data-filled]')).toHaveLength(2); + } + // CONTROL: a digit above zero still sets the stars on a required rating. + fireEvent.keyDown(t.catcher(), { key: '4' }); + expect(t.onCellChange).toHaveBeenLastCalledWith(0, 'score', 4, expect.anything()); + }); + it('Enter, F2 and a double-click open no editor on a rating', () => { const t = renderRating(); fireEvent.click(t.cell(0, 1)); diff --git a/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx b/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx index 69c8dbe00a2..459e524823c 100644 --- a/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx @@ -12,15 +12,21 @@ * * 1. On the selected cell: the arrows and Tab move the selection; Escape * clears it; typing opens the editor with the typed text in place of the - * value (a number column gets the number); Backspace opens it empty and - * writes nothing; Ctrl/Cmd+V converts and commits; Ctrl/Cmd+C copies. - * 2. While editing: Enter commits and moves down, Tab / Shift+Tab commit and - * move right / left, Escape cancels and keeps the selection. In a - * multi-line editor Enter is the editor's and Ctrl/Cmd+Enter commits. + * value (a number column gets the number); Ctrl/Cmd+V converts and + * commits; Ctrl/Cmd+C copies. (Backspace: section 4.) + * 2. While editing: Enter commits and stays on the cell (objectstack#36023; + * it moved down before), Tab / Shift+Tab commit and move right / left, + * Escape cancels and keeps the selection. In a multi-line editor Enter + * is the editor's and Ctrl/Cmd+Enter commits. * 3. An input method: the keys pressed while it composes, and the 229 * Enter a browser raises after `compositionend`, never commit; a * composition started on the selected cell opens the editor with the * whole composed text. + * 4. objectstack#36023: Backspace / Delete clear the cell and save at once, + * unless the host says why not (a required field); a picker's editor is a + * panel under the cell, which keeps its value drawn; a commit the browser + * or the host refuses keeps the editor and the input, says why under it, + * and Escape discards. */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -121,15 +127,6 @@ describe('data-table select-first keys — on the selected cell (objectstack#356 expect(t.onCellChange).not.toHaveBeenCalled(); }); - it.each(['Backspace', 'Delete'])('%s opens an empty editor and writes nothing', (key) => { - const t = renderTable(); - t.select(1, 1); - fireEvent.keyDown(t.catcher(), { key }); - expect(t.editor()).not.toBeNull(); - expect(t.editor()!.value).toBe(''); - expect(t.onCellChange).not.toHaveBeenCalled(); - }); - it('Ctrl/Cmd+V converts the text to the column and commits it; text that is no value writes nothing', () => { const t = renderTable(); t.select(0, 1); @@ -186,21 +183,22 @@ describe('data-table select-first keys — on the selected cell (objectstack#356 }); describe('data-table select-first keys — while editing', () => { - it('Enter commits and moves down; Tab commits and moves right; Shift+Tab left', () => { + it('Enter commits and stays on the cell, focus on it; Tab commits and moves right; Shift+Tab left (objectstack#36023)', () => { const t = renderTable(); t.select(0, 0); fireEvent.change(t.catcher(), { target: { value: 'A' } }); fireEvent.keyDown(t.editor()!, { key: 'Enter' }); expect(t.onCellChange).toHaveBeenLastCalledWith(0, 'name', 'A', ROWS[0]); expect(t.editor()).toBeNull(); - expect(t.selected()).toBe('1:0'); + expect(t.selected()).toBe('0:0'); + expect(document.activeElement).toBe(t.catcher()); fireEvent.keyDown(t.catcher(), { key: 'Enter' }); fireEvent.keyDown(t.editor()!, { key: 'Tab' }); - expect(t.selected()).toBe('1:1'); + expect(t.selected()).toBe('0:1'); expect(t.editor()).toBeNull(); fireEvent.keyDown(t.catcher(), { key: 'F2' }); fireEvent.keyDown(t.editor()!, { key: 'Tab', shiftKey: true }); - expect(t.selected()).toBe('1:0'); + expect(t.selected()).toBe('0:0'); expect(t.onCellChange).toHaveBeenCalledTimes(3); }); @@ -229,7 +227,7 @@ describe('data-table select-first keys — while editing', () => { fireEvent.keyDown(area, { key: 'Enter', metaKey: true }); expect(t.container.querySelector('textarea')).toBeNull(); expect(t.onCellChange).toHaveBeenCalledTimes(1); - expect(t.selected()).toBe('1:2'); + expect(t.selected()).toBe('0:2'); }); }); @@ -268,3 +266,168 @@ describe('data-table select-first keys — an input method', () => { expect(t.onCellChange).not.toHaveBeenCalled(); }); }); + +describe('data-table select-first — clearing, the panel under the cell, a refused commit (objectstack#36023)', () => { + it.each(['Backspace', 'Delete'])('%s clears the cell and saves at once, with no editor', (key) => { + const t = renderTable(); + t.select(1, 1); + fireEvent.keyDown(t.catcher(), { key }); + expect(t.editor()).toBeNull(); + expect(t.onCellChange).toHaveBeenCalledWith(1, 'amount', null, ROWS[1]); + expect(t.selected()).toBe('1:1'); + }); + + it('a cell the host refuses to clear keeps its value and says why on the cell', () => { + const t = renderTable({}, { describeCell: () => ({ clearRefusal: 'Amount is required' }) }); + t.select(1, 1); + fireEvent.keyDown(t.catcher(), { key: 'Backspace' }); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(t.editor()).toBeNull(); + expect(t.cell(1, 1)).toHaveTextContent('20'); + expect(document.querySelector('[data-testid="cell-readonly-reason"]')).toHaveTextContent('Amount is required'); + }); + + it('a two-state cell has nothing to clear: Backspace writes nothing', () => { + const t = renderTable({}, { describeCell: () => ({ toggles: true }) }); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'Delete' }); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it('a read-only cell says it is read-only and is not cleared', () => { + const t = renderTable({}, { describeCell: () => ({ readOnlyReason: 'This value is calculated.' }) }); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'Backspace' }); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(document.querySelector('[data-testid="cell-readonly-reason"]')).toHaveTextContent('This value is calculated.'); + }); + + it('`editor: below` opens a panel under the cell, which keeps drawing its value; the default covers it', () => { + const below = renderTable({}, { describeCell: (_row, key) => (key === 'name' ? { editor: 'below' } : null) }); + below.select(0, 0); + fireEvent.keyDown(below.catcher(), { key: 'Enter' }); + const host = below.cell(0, 0); + expect(host.querySelector('[data-slot="cell-editor-overlay"]')).toHaveAttribute('data-placement', 'below'); + expect(host.querySelector('[data-slot="cell-display"]')).toHaveTextContent('Alpha'); + fireEvent.keyDown(below.editor()!, { key: 'Escape' }); + cleanup(); + // CONTROL: no fact, the layer covers the cell and the cell's text is not drawn under it. + const cover = renderTable(); + cover.select(0, 0); + fireEvent.keyDown(cover.catcher(), { key: 'Enter' }); + expect(cover.cell(0, 0).querySelector('[data-slot="cell-editor-overlay"]')).toHaveAttribute('data-placement', 'cover'); + expect(cover.cell(0, 0).querySelector('[data-slot="cell-display"]')).toBeNull(); + }); + + it('a value the host refuses keeps the editor and the input, says why, and Enter does not move', () => { + const validate = vi.fn((v: unknown) => (Number(v) > 100 ? 'Amount must be at most 100' : null)); + const t = renderTable({}, { describeCell: (_row, key) => (key === 'amount' ? { validate } : null) }); + t.select(0, 1); + fireEvent.change(t.catcher(), { target: { value: '5' } }); + fireEvent.change(t.editor()!, { target: { value: '500' } }); + fireEvent.keyDown(t.editor()!, { key: 'Enter' }); + expect(validate).toHaveBeenCalledWith('500'); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(t.editor()).toHaveValue(500); + expect(t.selected()).toBe('0:1'); + expect(t.cell(0, 1).querySelector('[data-testid="cell-edit-refusal"]')).toHaveTextContent('Amount must be at most 100'); + // Tab is refused the same way. + fireEvent.keyDown(t.editor()!, { key: 'Tab' }); + expect(t.selected()).toBe('0:1'); + expect(t.onCellChange).not.toHaveBeenCalled(); + // Correcting the value takes the reason away, and Tab commits and moves on. + fireEvent.change(t.editor()!, { target: { value: '50' } }); + expect(t.cell(0, 1).querySelector('[data-testid="cell-edit-refusal"]')).toBeNull(); + fireEvent.keyDown(t.editor()!, { key: 'Tab' }); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'amount', '50', ROWS[0]); + expect(t.selected()).toBe('0:2'); + }); + + it('Escape after a refusal discards the edit', () => { + const t = renderTable({}, { describeCell: () => ({ validate: () => 'No.' }) }); + t.select(0, 0); + fireEvent.change(t.catcher(), { target: { value: 'Z' } }); + fireEvent.keyDown(t.editor()!, { key: 'Enter' }); + expect(t.editor()).toHaveValue('Z'); + fireEvent.keyDown(t.editor()!, { key: 'Escape' }); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 0)).toHaveTextContent('Alpha'); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it('text a number box cannot read is refused by the table itself', () => { + const t = renderTable(); + t.select(0, 1); + fireEvent.change(t.catcher(), { target: { value: '5' } }); + const input = t.editor() as HTMLInputElement; + // jsdom never reports bad input; the browser does for text in a number box. + Object.defineProperty(input, 'validity', { configurable: true, value: { badInput: true, typeMismatch: false } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(t.cell(0, 1).querySelector('[data-testid="cell-edit-refusal"]')).toHaveTextContent('Enter a number.'); + // CONTROL: once the box reads, the commit goes through. + Object.defineProperty(input, 'validity', { configurable: true, value: { badInput: false, typeMismatch: false } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'amount', 5, ROWS[0]); + }); + + it('an in-cell box that already says why it cannot read its text is refused without a second sentence', () => { + const t = renderTable(); + t.select(0, 1); + fireEvent.change(t.catcher(), { target: { value: '5' } }); + const input = t.editor() as HTMLInputElement; + // The in-cell number face marks its box and draws its own bad-input line. + input.setAttribute('aria-invalid', 'true'); + Object.defineProperty(input, 'validity', { configurable: true, value: { badInput: true, typeMismatch: false } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(t.editor()).not.toBeNull(); + expect(t.cell(0, 1).querySelector('[data-testid="cell-edit-refusal"]')).toBeNull(); + }); + + it('a press outside an injected editor holding a refused value keeps the editor, and the click selects nothing', () => { + const t = renderTable( + { + renderCellEditor: (ctx: any) => ( + ctx.stage(e.target.value)} /> + ), + }, + { describeCell: (_row, key) => (key === 'name' ? { validate: (v) => (v === '' ? 'Name is required' : null) } : null) }, + ); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + const injected = () => t.container.querySelector('[data-testid="injected"]'); + fireEvent.change(injected()!, { target: { value: '' } }); + fireEvent.pointerDown(t.cell(2, 2)); + fireEvent.click(t.cell(2, 2)); + expect(injected()).not.toBeNull(); + expect(t.selected()).toBe('0:0'); + expect(t.onCellChange).not.toHaveBeenCalled(); + expect(t.cell(0, 0).querySelector('[data-testid="cell-edit-refusal"]')).toHaveTextContent('Name is required'); + // CONTROL: a value the host accepts commits on the press outside. + fireEvent.change(injected()!, { target: { value: 'Omega' } }); + fireEvent.pointerDown(t.cell(2, 2)); + expect(injected()).toBeNull(); + expect(t.onCellChange).toHaveBeenCalledWith(0, 'name', 'Omega', ROWS[0]); + }); + + it('the selected cell is framed by a child under the frozen columns, not by its outline, and Esc leaves no ring', () => { + const t = renderTable({ frozenColumns: 1 }); + const frame = (row: number, col: number) => t.cell(row, col).querySelector('[data-slot="cell-selection-frame"]'); + t.select(0, 1); + // The frame sits in the cell's own layer (below the sticky z-10 column). + expect(frame(0, 1)).toHaveClass('absolute', 'inset-0', 'pointer-events-none'); + expect(frame(0, 1)!.className).not.toMatch(/z-(?:[1-9]\d|\[(?:[1-9]\d))/); + expect(t.cell(0, 1).className).not.toContain('outline-primary'); + // A frozen cell selected is framed the same way. + t.select(0, 0); + expect(frame(0, 1)).toBeNull(); + expect(frame(0, 0)).not.toBeNull(); + // Esc deselects: the focus stays on the cell, which draws no ring at all. + fireEvent.keyDown(t.catcher(), { key: 'Escape' }); + expect(t.selected()).toBeNull(); + expect(document.activeElement).toBe(t.cell(0, 0)); + expect(t.cell(0, 0)).toHaveClass('outline-none'); + expect(frame(0, 0)).toBeNull(); + }); +}); diff --git a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx index b0de1635bd9..ae7d6137b50 100644 --- a/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx @@ -94,7 +94,7 @@ describe('data-table select-first — a click selects (objectstack#35684)', () = fireEvent.click(t.cell(0, 0)); expect(t.cell(0, 0)).toHaveAttribute('data-selected-cell'); expect(t.cell(0, 0)).toHaveAttribute('aria-selected', 'true'); - expect(t.cell(0, 0).className).toContain('outline-primary'); + expect(t.cell(0, 0).querySelector('[data-slot="cell-selection-frame"]')).not.toBeNull(); expect(t.editor()).toBeNull(); expect(t.onRowClick).not.toHaveBeenCalled(); expect(document.activeElement).toBe(t.catcher()); diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index c72be55cf6f..7851626eb97 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -14,8 +14,8 @@ * single click, never edited by it and never opening the record. An editor * opens on double-click, Enter, F2 or typing (Space included; a two-state * cell flips instead); the title link or a touch tap opens the record; Esc - * cancels; Enter and Tab commit and move (in a multi-line editor Enter is a - * newline and Ctrl/Cmd+Enter commits). A cell that opens no editor says why + * cancels; Enter commits and stays on the cell, Tab commits and moves (in a + * multi-line editor Enter is a newline and Ctrl/Cmd+Enter commits). A cell that opens no editor says why * in place. Outside a provider (`null`, the default) the table keeps its * click-to-edit / click-to-open behaviour byte for byte, so every host that * does not mount this keeps what it had. @@ -56,6 +56,24 @@ export interface GridCellFacts { * text is not one (Ctrl/Cmd+V on the selected cell then writes nothing). */ fromText?: (text: string) => unknown; + /** + * Where this cell's editor draws: `below` opens it as a panel under the + * cell, which keeps showing its value (a picker: a list, a calendar); absent + * or `cover`, the editor is a layer over the cell itself (typed input). + */ + editor?: 'cover' | 'below'; + /** + * Why Backspace or Delete on the selected cell leaves it as it is (a + * required field), as a sentence in the reader's language. Absent ⇒ those + * keys clear the cell and save at once. + */ + clearRefusal?: string | null; + /** + * Why a value committed into this cell is refused before it is saved, or + * `null` when it is accepted. A refused commit keeps the editor open with + * what was typed, and says the reason under it; Escape discards. + */ + validate?: (value: unknown) => string | null | undefined; } export interface GridCellSelection { diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 9e0e63f0b42..f38d3077e1f 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -364,6 +364,11 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { // objectstack#35684 — a selected cell that opens no editor, when its host // gives no reason of its own. 'table.cellReadOnly': 'This cell can\'t be edited here.', + // objectstack#36023 — why a list cell's typed value was not saved, said under the editor. + 'table.cellNotNumber': 'Enter a number.', + 'table.cellInvalid': 'This value isn\'t valid.', + 'validation.email': 'Please enter a valid email address', + 'validation.url': 'Please enter a valid URL', // objectstack#35685 — a list cell's own save state, and the way out of a // rule the list cannot complete. 'table.cellSaving': 'Saving…', @@ -1977,6 +1982,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { editValueRef.current = value; setEditValueState(value); }; + // objectstack#36023 — why the open edit's last commit was refused, and the + // value it refused: the reason shows while the editor still holds that value. + const [editRefusal, setEditRefusal] = useState<{ text: string; value: unknown } | null>(null); // Track pending changes for multi-cell editing, per record (objectui#12310): // record key -> { row, changes: { columnKey -> newValue } } const [pendingChanges, setPendingChanges] = useState(new Map()); @@ -2809,6 +2817,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const cell: EditingCell = { rowKey, columnKey, row }; editingCellRef.current = cell; setEditingCell(cell); + setEditRefusal(null); // Check if there's a pending change for this cell, otherwise use current data value const rowChanges = pendingChanges.get(rowKey)?.changes; @@ -2822,11 +2831,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { : { had: false, value: undefined }; }; - const saveEdit = (force: boolean = false, explicitValue?: any) => { - if (!editingCell) return; + /** + * Commit the open edit. `false` when nothing was committed: no edit is open, + * or the value was refused (objectstack#36023), and then the editor stays + * open with what was typed and the reason under it. + */ + const saveEdit = (force: boolean = false, explicitValue?: any): boolean => { + if (!editingCell) return false; // Don't save if we're in cancelled state (unless forced) - if (!force && editingCell === null) return; + if (!force && editingCell === null) return false; const { rowKey, columnKey } = editingCell; // The record the editor is open on, as the table holds it now — or, if @@ -2841,6 +2855,17 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // (objectui#12664) has not reached state yet either. const valueToStage = explicitValue !== undefined ? explicitValue : editValueRef.current; + // objectstack#36023 — a value that fails its rules is not written: the + // editor stays open with the reader's input, and says why. + const refusal = selectFirst ? editRefusalOf(row, columnKey, valueToStage) : null; + if (refusal !== null) { + setEditRefusal({ text: refusal, value: valueToStage }); + // A commit blurs the editor's control first (`flushInjectedEditor`): give it the caret back. + const editor = tableRef.current?.querySelector('[data-slot="cell-editor-overlay"]'); + if (editor && !editor.contains(document.activeElement)) firstEditorControl(editor)?.focus({ preventScroll: true }); + return false; + } + // objectstack#35685 — a value the host asks to confirm first: the editor // closes with nothing of this session staged, and the value is written // only once the host says yes (a no leaves the cell as it was). @@ -2851,8 +2876,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { editingCellRef.current = null; setEditingCell(null); setEditValue(''); + setEditRefusal(null); settleCommitConfirmation(asked, row, columnKey, valueToStage); - return; + return true; } // Update pending changes — or drop this cell's entry when the committed @@ -2873,6 +2899,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { editingCellRef.current = null; setEditingCell(null); setEditValue(''); + setEditRefusal(null); + return true; }; // Latest-ref to `saveEdit` so the document-level click-outside listener (whose @@ -2983,6 +3011,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { editingCellRef.current = null; setEditingCell(null); setEditValue(''); + setEditRefusal(null); }; const cancelEdit = () => { @@ -3573,6 +3602,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }, [selectedPosKey, editingCell]); // The preview's size, taken as the editor replaces it, so the layer does not jump. const [editorSeedSize, setEditorSeedSize] = useState(null); + // objectstack#36023 — the open editor is a panel under its cell (`GridCellFacts.editor`). + const [editorBelow, setEditorBelow] = useState(false); const focusSelectionRef = useRef(false); useEffect(() => { if (!focusSelectionRef.current || editingCell) return; @@ -3607,6 +3638,31 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const factsOf = (row: any, col: TableColumn) => cellSelection?.describeCell?.(row, col.accessorKey) ?? null; + /** + * objectstack#36023 — why the open editor's value may not be committed, or + * `null`: first what the browser itself cannot read in the editor's input (a + * number box holding letters, an email box holding no address), then the + * host's rules for the cell (`GridCellFacts.validate`). + */ + /** Why a committed value is refused (`''`: refused, and the editor already says why), or `null`. */ + const editRefusalOf = (row: any, columnKey: string, value: unknown): string | null => { + const editor = tableRef.current?.querySelector('[data-slot="cell-editor-overlay"]'); + const unreadable = editor + ? Array.from(editor.querySelectorAll('input')).find((input) => input.validity?.badInput || input.validity?.typeMismatch) + : undefined; + if (unreadable) { + // An in-cell face that already says why under its box (a number box's + // own bad-input line) is refused without a second sentence. + if (unreadable.getAttribute('aria-invalid') === 'true') return ''; + if (unreadable.type === 'number') return t('table.cellNotNumber'); + if (unreadable.type === 'email') return t('validation.email'); + if (unreadable.type === 'url') return t('validation.url'); + return t('table.cellInvalid'); + } + const col = columns.find((c) => c.accessorKey === columnKey); + return (col && factsOf(row, col)?.validate?.(value)) || null; + }; + /** Why this cell opens no editor, or `null` when it opens one. */ const readOnlyReasonOf = (row: any, col: TableColumn): string | null => { const reason = factsOf(row, col)?.readOnlyReason; @@ -3631,7 +3687,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { ? tableRef.current?.querySelector('[data-slot="cell-preview-overlay"]') : null; const rect = preview?.getBoundingClientRect(); - setEditorSeedSize(rect ? { width: rect.width, height: rect.height } : null); + // A panel under the cell does not take the size of the preview it replaces. + const below = factsOf(row, col)?.editor === 'below'; + setEditorSeedSize(rect && !below ? { width: rect.width, height: rect.height } : null); + setEditorBelow(below); setSelectedCell({ rowIndex, colIndex }); startEdit(row, col.accessorKey, seed); }; @@ -3675,13 +3734,25 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const whole = typeof stars === 'number' && Number.isFinite(stars) ? Math.floor(stars) : 0; return whole > 0 ? whole : null; }; + // No stars is a clear, refused like any clear on a required field (objectstack#36023). const setStars = (rowIndex: number, colIndex: number, count: number) => - writeCell(rowIndex, colIndex, () => (count > 0 ? count : null)); + count > 0 ? writeCell(rowIndex, colIndex, () => count) : clearCell(rowIndex, colIndex); const toggleCell = (rowIndex: number, colIndex: number) => writeCell(rowIndex, colIndex, (row, col) => { const staged = pendingChanges.get(pendingRowKeyOf(row))?.changes; const current = staged && col.accessorKey in staged ? staged[col.accessorKey] : row[col.accessorKey]; return current !== true; }); + /** Backspace or Delete on the selected cell: emptied and saved, or said why not. */ + const clearCell = (rowIndex: number, colIndex: number) => writeCell(rowIndex, colIndex, (row, col) => { + // A two-state cell has no empty state to go to. + if (togglesCell(row, col)) return undefined; + const refusal = factsOf(row, col)?.clearRefusal; + if (refusal) { + setCellNotice({ rowIndex, colIndex, text: refusal }); + return undefined; + } + return null; + }); const pasteIntoCell = (rowIndex: number, colIndex: number, text: string) => writeCell(rowIndex, colIndex, (row, col) => { const fromText = factsOf(row, col)?.fromText; return fromText ? fromText(text) : defaultValueFromText(col, text); @@ -3701,12 +3772,19 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { attemptEdit(rowIndex, colIndex, { value: converted !== undefined ? converted : text }); }; - /** After Enter or Tab committed the selected cell's edit: the cell it moves to. */ - const moveSelection = (direction: 'down' | 'right' | 'left') => { + /** + * After Enter or Tab committed the selected cell's edit (objectstack#36023): + * Enter stays on the cell, with the focus back on it; Tab moves right and + * Shift+Tab left. + */ + const commitMoves = (e: React.KeyboardEvent) => { if (!selectedPos) return; const { rowIndex, colIndex } = selectedPos; - if (direction === 'down') selectCell(Math.min(paginatedData.length - 1, rowIndex + 1), colIndex); - else selectCell(rowIndex, Math.max(0, Math.min(columns.length - 1, colIndex + (direction === 'right' ? 1 : -1)))); + if (e.key !== 'Tab') { + focusSelectionRef.current = true; + return; + } + selectCell(rowIndex, Math.max(0, Math.min(columns.length - 1, colIndex + (e.shiftKey ? -1 : 1)))); }; /** The selected cell's keys, while no editor is open (an open editor owns every key). */ @@ -3773,15 +3851,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { e.preventDefault(); toggleCell(rowIndex, colIndex); } else if (bare && /^[0-9]$/.test(e.key) && starsOf(row, col) !== null) { - // objectstack#36023 — a digit on a rating sets that many stars, at most its scale. + // objectstack#36023 — a digit on a rating sets that many stars, at most its + // scale; 0 clears it, as Backspace does. e.preventDefault(); setStars(rowIndex, colIndex, Math.min(Number(e.key), starsOf(row, col)!)); } else if ((e.key === 'Backspace' || e.key === 'Delete') && bare) { + // objectstack#36023 — the cell is cleared and saved at once; a cell the + // host refuses to clear (a required field, a required rating included) + // says why and keeps its value. e.preventDefault(); - // A rating clears in place; anywhere else, an empty editor, and nothing - // is written until it commits. - if (starsOf(row, col) !== null) setStars(rowIndex, colIndex, 0); - else attemptEdit(rowIndex, colIndex, { value: '' }); + clearCell(rowIndex, colIndex); } // A printable key lands in the catcher, which reads it (`typeIntoCell`). }; @@ -3858,9 +3937,12 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { e.preventDefault(); // Already saving here; suppress the redundant save the ensuing blur triggers. skipBlurSaveRef.current = true; - saveEdit(true); - // The select-first model: Enter saves and moves down, Tab right, Shift+Tab left. - if (selectFirst) moveSelection(e.key === 'Enter' ? 'down' : e.shiftKey ? 'left' : 'right'); + const committed = saveEdit(true); + // A refused value keeps the editor, whose next blur saves as before. + if (!committed) skipBlurSaveRef.current = false; + // The select-first model (objectstack#36023): Enter saves and stays on + // the cell, Tab moves right, Shift+Tab left. + if (committed && selectFirst) commitMoves(e); } else if (e.key === 'Escape') { e.preventDefault(); focusSelectionRef.current = selectFirst; @@ -3936,7 +4018,19 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // (objectui#12664): this runs before the browser moves focus, so a // widget that reads its input on blur would otherwise not have staged. flushInjectedEditor(); - saveEditRef.current(true); + if (saveEditRef.current(true)) return; + // objectstack#36023 — a refused value keeps the editor open: this press + // and the click it makes do nothing, so the reader can correct it or + // press Escape. + e.preventDefault(); + e.stopPropagation(); + const swallowClick = (click: MouseEvent) => { + click.preventDefault(); + click.stopPropagation(); + }; + document.addEventListener('click', swallowClick, { capture: true, once: true }); + // A press that makes no click (a drag) leaves no listener behind. + window.setTimeout(() => document.removeEventListener('click', swallowClick, { capture: true }), 1000); }; document.addEventListener('pointerdown', onPointerDown, true); return () => document.removeEventListener('pointerdown', onPointerDown, true); @@ -4901,6 +4995,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const hasPendingChange = rowChanges[col.accessorKey] !== undefined; const cellValue = hasPendingChange ? rowChanges[col.accessorKey] : originalValue; const isEditing = editingCell !== null && editingCell.rowKey === rowKey && editingCell.columnKey === col.accessorKey; + // objectstack#36023 — a picker's panel opens under the cell, which keeps its value drawn. + const editsBelow = isEditing && selectFirst && editorBelow; // The reason the last refusal gave for THIS cell, if it // named it (objectstack-ai/objectstack#27520). const cellError = rowCellErrors?.[col.accessorKey]; @@ -4942,8 +5038,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // keeps overflow-hidden for truncation. isFit ? 'whitespace-nowrap' : 'overflow-hidden', !selectFirst && isEditable && !isEditing && "cursor-text hover:bg-muted/50", - // A ring that moves no layout (outline, not border). - isSelectedCell && "outline-2 -outline-offset-2 outline-primary", + // objectstack#36023 — the selected cell's frame is a child + // (below), not the cell's outline: an outline paints over a + // frozen column the cell has scrolled under. A cell the + // reader deselected with Esc keeps the focus with no ring. + selectFirst && "outline-none", selectFirst && !isFrozen && "relative", !autosaves && hasPendingChange && "font-semibold text-amber-700 dark:text-amber-400", cellError !== undefined && "ring-2 ring-inset ring-destructive", @@ -5047,6 +5146,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { data-cell-error={cellError} title={cellError} > + {isSelectedCell && ( + // A frame that moves no layout, drawn under the frozen + // columns like the rest of the cell. + + )} {isSelectedCell && !isEditing && ( { ); })()} - {isEditing ? ( + {isEditing && ( { flushInjectedEditor(); saveEditRef.current(true); }} + // Scrolled out of sight: commit, as a click outside does; a + // value that cannot be committed is discarded with the editor. + onHidden={() => { flushInjectedEditor(); if (!saveEditRef.current(true)) exitEdit(true); }} > {/* The per-type floor rides an inner box: on the layer's own class it would replace the layer's cell-width floor. */} @@ -5178,7 +5288,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // focus back to the selected cell, as Enter does. commit: (v?: any) => { focusSelectionRef.current = selectFirst; - saveEdit(true, v); + if (!saveEdit(true, v)) focusSelectionRef.current = false; }, cancel: cancelEdit, }); @@ -5231,8 +5341,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // A commit-on-blur widget stages // on this blur (objectui#12664). flushInjectedEditor(); - saveEdit(true); - if (selectFirst) moveSelection(e.key === 'Enter' ? 'down' : e.shiftKey ? 'left' : 'right'); + if (saveEdit(true) && selectFirst) commitMoves(e); } else if (e.key === 'Escape') { e.preventDefault(); focusSelectionRef.current = selectFirst; @@ -5359,8 +5468,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { ); })()} + {editRefusal && editRefusal.text !== '' && isUnchangedCellValue(editValue, editRefusal.value) && ( + // objectstack#36023 — why the value was not saved, under the input. +

+ {editRefusal.text} +

+ )}
- ) : ( + )} + {(!isEditing || editsBelow) && (
void; + /** `cover` = over the cell; `below` = a panel under it, the cell left as drawn. */ + placement?: 'cover' | 'below'; }) { const markerRef = React.useRef(null); const contentRef = React.useRef(null); @@ -118,9 +124,10 @@ export function CellOverlay({ diff --git a/ui/packages/fields/src/__tests__/userCell.rowHeight-36023.test.tsx b/ui/packages/fields/src/__tests__/userCell.rowHeight-36023.test.tsx new file mode 100644 index 00000000000..8fc6a3706a1 --- /dev/null +++ b/ui/packages/fields/src/__tests__/userCell.rowHeight-36023.test.tsx @@ -0,0 +1,53 @@ +/** + * 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. + */ + +/** + * objectstack#36023 — a person's face never makes its list row taller. + * + * Measured in the browser before the fix: a list row holding a `user` cell + * was 41 px tall (a 32 px face plus the cell's padding) while every row of + * text was 33 px, and it dropped back to 33 px while the cell was edited, so + * the list jumped. The face is now drawn at 24 px and laid out at 20 px (a + * negative block margin), the line height of the cell's text, so the row is + * the height of a row of text with and without the face. jsdom lays nothing + * out; the pin is on the classes that decide it, and the browser reading is + * the PR's. + */ +import React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { UserCellRenderer } from '../index'; + +afterEach(cleanup); + +// The face is the Avatar root (a rounded-full span); it carries no slot attribute. +const faces = (container: HTMLElement) => Array.from(container.querySelectorAll('span.rounded-full.overflow-hidden')); + +describe('UserCellRenderer — the face is no taller than a line of text (objectstack#36023)', () => { + it('one person: a 24 px face laid out at 20 px, never the 32 px one', () => { + const { container } = render(); + const [face] = faces(container); + expect(face).toBeDefined(); + expect(face).toHaveClass('size-6', '-my-0.5'); + expect(face).not.toHaveClass('size-8'); + expect(container).toHaveTextContent('Ada Lovelace'); + }); + + it('several people: every face in the stack and the "+N" face are the same size', () => { + const people = ['Ada Lovelace', 'Alan Turing', 'Grace Hopper', 'Edsger Dijkstra'].map((name, i) => ({ id: `u_${i}`, name })); + const { container } = render(); + const all = faces(container); + expect(all).toHaveLength(4); + for (const face of all) { + expect(face).toHaveClass('size-6', '-my-0.5'); + expect(face).not.toHaveClass('size-8'); + } + expect(all[3]).toHaveTextContent('+1'); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 4deb0e1bce5..84982f519ea 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -3264,6 +3264,14 @@ export function UnresolvedReferenceMark({ * `sys_user` policy, the object the runtime expands it into and the object * `UserField` points the picker at. The field's `reference` is not read. */ +/** + * A person's face in a cell (objectstack#36023): 24 px drawn, 20 px laid out, + * so it never makes its row taller than a row of text. A 32 px face made a + * list row 41 px tall, and the row dropped back to 33 px while the cell was + * edited, so the list jumped. + */ +const CELL_AVATAR_CLASS = 'size-6 -my-0.5'; + export function UserCellRenderer({ value }: CellRendererProps): React.ReactElement { // Called before any early return (rules of hooks). A policy that loads or // changes re-renders this cell through the context, and the drawing follows. @@ -3325,19 +3333,19 @@ export function UserCellRenderer({ value }: CellRendererProps): React.ReactEleme return ( {user.image && } - + {initials} ); })} {value.length > 3 && ( - - + + +{value.length - 3} @@ -3376,9 +3384,9 @@ export function UserCellRenderer({ value }: CellRendererProps): React.ReactEleme return (
- + {user.image && } - + {initials} diff --git a/ui/packages/fields/src/widgets/InCellOptionList.tsx b/ui/packages/fields/src/widgets/InCellOptionList.tsx index c874b775921..ae6807636ea 100644 --- a/ui/packages/fields/src/widgets/InCellOptionList.tsx +++ b/ui/packages/fields/src/widgets/InCellOptionList.tsx @@ -24,8 +24,8 @@ export interface InCellOption { * * 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 - * on to the grid, which cancels. + * Enter goes on to the grid, which commits and stays on the cell. Escape + * always goes on to the grid, which cancels. */ export function InCellOptionList({ options, diff --git a/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx b/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx index e6233665d49..77364b1d104 100644 --- a/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx +++ b/ui/packages/fields/src/widgets/date-picker/DatePickerField.tsx @@ -125,8 +125,7 @@ function TemporalPicker({ const locale = useDisplayLocale(); const { t } = useFieldTranslation(); const noticeId = React.useId(); - // The grid's cell editor opens with its calendar showing (objectstack#35688). - const [open, setOpen] = React.useState(!!inCell && !readonly); + const [open, setOpen] = React.useState(false); const hourRef = React.useRef(null); const rootRef = React.useRef(null); @@ -251,37 +250,149 @@ function TemporalPicker({ ? [domProps['aria-describedby'], noticeId].filter(Boolean).join(' ') : domProps['aria-describedby']; + /** The text box: the value as the reader's locale writes it, typeable. */ + const textBox = (className: string) => ( + setText(e.target.value)} + onBlur={(e) => { + commitText(); + domProps.onBlur?.(e); + }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + // Commit, and keep a bare Enter from submitting the form with + // the text not yet read. + e.preventDefault(); + commitText(); + } + }} + disabled={disabled} + // After the DOM spread, the objectui#3222 idiom `DateField` follows. + aria-invalid={!!error || impossible || badText !== null} + aria-describedby={describedBy} + /> + ); + + /** The calendar, the time on the `datetime` face, and the quick picks. */ + const panel = ( + <> + {/* Opens on the value's month, and on today's with no value. */} + {/* Below `sm` each day and month arrow is a 44 px cell: seven fit a 375 px screen. */} + + {withTime ? ( +
+
+ ) : null} +
+ + + {inCell ? ( + <> + {/* Seven days from today (ruling of record 7057128455). */} + + + + ) : null} +
+ + ); + + const noticeLine = notice ? ( +

+ {notice} +

+ ) : null; + + if (inCell) { + // The grid's cell editor (objectstack#36023): one panel under the cell, + // the typeable box on top and the calendar always showing beneath it. + return ( +
+
{textBox('h-8')}
+ {panel} + {noticeLine ?
{noticeLine}
: null} +
+ ); + } + return (
- setText(e.target.value)} - onBlur={(e) => { - commitText(); - domProps.onBlur?.(e); - }} - onKeyDown={(e) => { - if (e.key === 'Enter') { - // Commit, and keep a bare Enter from submitting the form with - // the text not yet read. - e.preventDefault(); - commitText(); - } - }} - disabled={disabled} - // After the DOM spread, the objectui#3222 idiom `DateField` follows. - aria-invalid={!!error || impossible || badText !== null} - aria-describedby={describedBy} - /> + {/* Below `sm` the two buttons inside grow to the touch floor, so the + text stops short of both (2 x 44 px plus the gap). */} + {textBox(cn(PHONE_TOUCH_HEIGHT, 'pr-24 sm:pr-16', domProps.className))}
{!disabled && (text || nativeValue) ? ( - - {inCell ? ( - <> - {/* Seven days from today (ruling of record 7057128455). */} - - - - ) : null} -
+ {panel}
- {notice ? ( -

- {notice} -

- ) : null} + {noticeLine}
); } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 67f10f44d8e..b64d90ad7b9 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -563,6 +563,9 @@ const ar = { cancelChanges: "إلغاء التغييرات", saveRow: "حفظ الصف", cellReadOnly: "لا يمكن تحرير هذه الخلية هنا.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "أدخل رقمًا.", + cellInvalid: "هذه القيمة غير صالحة.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "جارٍ الحفظ…", cellSaved: "تم الحفظ", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index a13959f73f7..304c075f3f1 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -529,6 +529,9 @@ const de = { cancelChanges: "Änderungen verwerfen", saveRow: "Zeile speichern", cellReadOnly: "Diese Zelle kann hier nicht bearbeitet werden.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "Geben Sie eine Zahl ein.", + cellInvalid: "Dieser Wert ist ungültig.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Wird gespeichert…", cellSaved: "Gespeichert", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3062cd03f8e..7c93f411eb1 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -795,6 +795,9 @@ const en = { cancelChanges: 'Cancel changes', saveRow: 'Save row', cellReadOnly: 'This cell can\'t be edited here.', + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: 'Enter a number.', + cellInvalid: 'This value isn\'t valid.', // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: 'Saving…', cellSaved: 'Saved', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index bf2e6d0d783..42eb2bc1d77 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -541,6 +541,9 @@ const es = { cancelChanges: "Descartar cambios", saveRow: "Guardar fila", cellReadOnly: "Esta celda no se puede editar aquí.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "Introduce un número.", + cellInvalid: "Este valor no es válido.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Guardando…", cellSaved: "Guardado", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 63af255230c..b4cd4fd14bb 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -536,6 +536,9 @@ const fr = { cancelChanges: "Annuler les modifications", saveRow: "Enregistrer la ligne", cellReadOnly: "Cette cellule ne peut pas être modifiée ici.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "Saisissez un nombre.", + cellInvalid: "Cette valeur n'est pas valide.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Enregistrement…", cellSaved: "Enregistré", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index f6941796ba2..0276b6825ae 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -529,6 +529,9 @@ const ja = { cancelChanges: "変更を取り消す", saveRow: "行を保存", cellReadOnly: "このセルはここでは編集できません。", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "数値を入力してください。", + cellInvalid: "この値は無効です。", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "保存中…", cellSaved: "保存しました", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 157e8f58610..373752d2144 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -529,6 +529,9 @@ const ko = { cancelChanges: "변경 취소", saveRow: "행 저장", cellReadOnly: "이 셀은 여기에서 편집할 수 없습니다.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "숫자를 입력하세요.", + cellInvalid: "이 값은 유효하지 않습니다.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "저장 중…", cellSaved: "저장됨", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index dce7132a73b..954de55f57e 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -536,6 +536,9 @@ const pt = { cancelChanges: "Descartar alterações", saveRow: "Salvar linha", cellReadOnly: "Esta célula não pode ser editada aqui.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "Digite um número.", + cellInvalid: "Este valor não é válido.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Salvando…", cellSaved: "Salvo", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 31f6b3cbffd..7e3b73fa9ef 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -546,6 +546,9 @@ const ru = { cancelChanges: "Отменить изменения", saveRow: "Сохранить строку", cellReadOnly: "Эту ячейку нельзя изменить здесь.", + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: "Введите число.", + cellInvalid: "Это значение недопустимо.", // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Сохранение…", cellSaved: "Сохранено", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 77c9064d816..3a630cec98c 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -542,6 +542,9 @@ const zh = { cancelChanges: '取消更改', saveRow: '保存行', cellReadOnly: '此单元格不能在这里编辑。', + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: '请输入数字。', + cellInvalid: '这个值无效。', // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: '保存中…', cellSaved: '已保存', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e6c94d5da72..e90898869d3 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -542,6 +542,9 @@ const zhHant = { cancelChanges: '取消更改', saveRow: '儲存行', cellReadOnly: '此單元格不能在這裡編輯。', + // objectstack#36023 — why a list cell's typed value was not saved, under the editor. + cellNotNumber: '請輸入數字。', + cellInvalid: '這個值無效。', // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: '儲存中…', cellSaved: '已儲存', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 24fa446e3a1..8b4977dc132 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -48,7 +48,7 @@ import { resolveI18nLabel as resolveInlineI18nLabel } from '@objectstack/spec/ui import { stateMachineNextValues } from './inline-edit-options'; import { isStateMachineField, stateLabelOf, type StateChangeConfirm } from './objectGridStateConfirm'; import { useCellRequiredPrompt } from './objectGridRequiredPrompt'; -import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText } from './objectGridCellFacts'; +import { cellReadOnlyKind, readOnlyReasonText, inlineTyping, choiceFromText, inlineEditorPlacement, clearRefusalText, cellValueRefusal } from './objectGridCellFacts'; import { Badge, Button, NavigationOverlay, EmptyValue, legacyRecordDrawerWidthKey, recordOverlayWidthStorageKey, @@ -1341,6 +1341,11 @@ export const ObjectGrid: React.FC = ({ // objectstack#36023 — a rating is set in place: digits, or a click on a star. ...(type === 'rating' ? { stars: ratingScaleOf(fieldDef) } : {}), ...(fromText ? { fromText } : {}), + // objectstack#36023 — a picker opens under the cell; a required + // field refuses Backspace; a commit is judged by the form's rules. + ...(inlineEditorPlacement(type) ? { editor: inlineEditorPlacement(type) } : {}), + clearRefusal: clearRefusalText(fieldDef, columnKey, t), + validate: (value) => cellValueRefusal(fieldDef, columnKey, value, t), }; }, onCellSelect: (row) => { diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx index e4fcc746bd8..8a0b610704a 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx @@ -19,6 +19,9 @@ * 3. The lock is read from the approvals service's per-record answer when a * cell of the row is selected; with no answer the row's * `approval_status` stands in (`resolveApprovalLock`). + * 4. objectstack#36023: a select cell's editor opens under the cell, which + * keeps its value drawn; a required cell refuses Backspace in the form's + * words; a value over the field's declared length stays in the editor. */ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -189,3 +192,70 @@ describe('ObjectGrid cellSelection — why a cell opens no editor', () => { await waitFor(() => expect(g.container.querySelector('td[data-editing-cell]')).not.toBeNull()); }); }); + +describe('ObjectGrid cellSelection — the panel, Backspace and the rules (objectstack#36023)', () => { + const RULES = { + name: { type: 'text', label: 'Name', required: true, maxLength: 5 }, + stage: { type: 'select', label: 'Stage', options: [{ value: 'open', label: 'Open' }, { value: 'won', label: 'Won' }] }, + notes: { type: 'text', label: 'Notes' }, + }; + async function renderRules() { + const utils = render( + , + ); + await screen.findByText('Alpha', {}, { timeout: 5000 }); + const cell = (col: number) => utils.container.querySelectorAll('tbody tr td[data-grid-cell]')[col]; + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]')!; + return { ...utils, cell, catcher }; + } + + it('a select cell opens its list under the cell, and the cell keeps showing its value', async () => { + const g = await renderRules(); + fireEvent.click(g.cell(1)); + fireEvent.keyDown(g.catcher(), { key: 'Enter' }); + const overlay = await waitFor(() => { + const el = g.cell(1).querySelector('[data-slot="cell-editor-overlay"]'); + expect(el).not.toBeNull(); + return el!; + }); + expect(overlay).toHaveAttribute('data-placement', 'below'); + expect(g.cell(1).querySelector('[data-slot="cell-display"]')).toHaveTextContent('Open'); + // CONTROL: a text cell's editor covers its cell. + fireEvent.keyDown(overlay.querySelector('input')!, { key: 'Escape' }); + fireEvent.click(g.cell(2)); + fireEvent.keyDown(g.catcher(), { key: 'Enter' }); + await waitFor(() => expect(g.cell(2).querySelector('[data-slot="cell-editor-overlay"]')).toHaveAttribute('data-placement', 'cover')); + }); + + it('Backspace on a required cell keeps its value and says it is required', async () => { + const g = await renderRules(); + fireEvent.click(g.cell(0)); + fireEvent.keyDown(g.catcher(), { key: 'Backspace' }); + expect(await screen.findByTestId('cell-readonly-reason')).toHaveTextContent('Name is required'); + expect(g.cell(0)).toHaveTextContent('Alpha'); + }); + + it('a name longer than the field allows stays in the editor with the reason', async () => { + const g = await renderRules(); + fireEvent.click(g.cell(0)); + fireEvent.change(g.catcher(), { target: { value: 'Alphabet' } }); + const input = await waitFor(() => { + const el = g.cell(0).querySelector('[data-slot="cell-editor-overlay"] input'); + expect(el).not.toBeNull(); + return el!; + }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(await screen.findByTestId('cell-edit-refusal')).toHaveTextContent('Name must be at most 5 characters'); + expect(g.cell(0).querySelector('[data-slot="cell-editor-overlay"] input')).toHaveValue('Alphabet'); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts b/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts index 74561e5c61c..6d015910863 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts @@ -9,10 +9,12 @@ /** * The cell facts `ObjectGrid` hands the select-first table * (objectstack#35684, objectstack#35687): the reason order, what typing does - * per field type, and what pasted text stands for in a choice field. + * per field type, and what pasted text stands for in a choice field; and + * (objectstack#36023) which editors open under the cell, which cells refuse + * Backspace, and which committed values the field's rules refuse. */ import { describe, it, expect } from 'vitest'; -import { cellReadOnlyKind, inlineTyping, choiceFromText, type CellReadOnlyInputs } from './objectGridCellFacts'; +import { cellReadOnlyKind, inlineTyping, choiceFromText, inlineEditorPlacement, clearRefusalText, cellValueRefusal, type CellReadOnlyInputs } from './objectGridCellFacts'; import { fieldInlineReadOnlyKind, isFieldInlineEditable } from './inline-edit-options'; const OPEN: CellReadOnlyInputs = { @@ -102,3 +104,41 @@ describe('choiceFromText — pasted text in a choice field (objectstack#35687)', expect(choiceFromText(undefined)).toBeNull(); }); }); + +// The sentences, keyed: what the grid's translation hands back for each rule. +const t = (key: string, o: Record = {}) => `${key}|${Object.entries(o).map(([k, v]) => `${k}=${v}`).join(',')}`; + +describe('the editor, Backspace and the commit rules a cell is given (objectstack#36023)', () => { + it('pickers open under the cell; typed input, long text and an address edit in place', () => { + for (const type of ['select', 'status', 'multiselect', 'tags', 'date', 'datetime', 'time', 'color', 'lookup', 'master_detail', 'user']) { + expect(inlineEditorPlacement(type), type).toBe('below'); + } + for (const type of ['text', 'number', 'currency', 'percent', 'email', 'phone', 'url', 'textarea', 'address', 'rating', 'boolean', undefined]) { + expect(inlineEditorPlacement(type), String(type)).toBeUndefined(); + } + }); + + it('a required field refuses Backspace in the form\'s words, or its own message; any other may be cleared', () => { + expect(clearRefusalText({ type: 'text', required: true, label: 'Name' }, 'name', t)).toBe('validation.required|field=Name'); + expect(clearRefusalText({ type: 'text', required: true }, 'name', t)).toBe('validation.required|field=name'); + expect(clearRefusalText({ type: 'text', required: true, required_message: 'Say a name' }, 'name', t)).toBe('Say a name'); + expect(clearRefusalText({ type: 'text' }, 'name', t)).toBeNull(); + expect(clearRefusalText(undefined, 'name', t)).toBeNull(); + }); + + it('a commit is judged by the record form\'s rules: required, length, range, email and URL shape', () => { + const name = { type: 'text', label: 'Name', required: true, minLength: 2, maxLength: 4 }; + expect(cellValueRefusal(name, 'name', '', t)).toBe('validation.required|field=Name'); + expect(cellValueRefusal(name, 'name', 'A', t)).toBe('validation.minLength|field=Name,min=2'); + expect(cellValueRefusal(name, 'name', 'Alpha', t)).toBe('validation.maxLength|field=Name,max=4'); + expect(cellValueRefusal(name, 'name', 'Abe', t)).toBeNull(); + const amount = { type: 'number', label: 'Amount', min: 0, max: 100 }; + expect(cellValueRefusal(amount, 'amount', 101, t)).toBe('validation.max|field=Amount,max=100'); + expect(cellValueRefusal(amount, 'amount', -1, t)).toBe('validation.min|field=Amount,min=0'); + expect(cellValueRefusal(amount, 'amount', null, t)).toBeNull(); + expect(cellValueRefusal({ type: 'email', label: 'Mail' }, 'mail', 'nobody', t)).toBe('validation.email|field=Mail'); + expect(cellValueRefusal({ type: 'email', label: 'Mail' }, 'mail', 'a@b.co', t)).toBeNull(); + expect(cellValueRefusal({ type: 'url', label: 'Site' }, 'site', 'example.com', t)).toBe('validation.url|field=Site'); + expect(cellValueRefusal({ type: 'select', options: ['a'] }, 'pick', 'a', t)).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts index b80afebc820..8d12fdda036 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -12,6 +12,7 @@ * on it does, and what pasted text stands for. The table asks when the reader * acts on a cell, never while it draws. */ +import { buildValidationRules } from '@object-ui/fields'; import { fieldInlineReadOnlyKind } from './inline-edit-options'; /** Why a cell opens no editor, in the order a cell names them. */ @@ -125,3 +126,78 @@ export function choiceFromText( if (type === 'lookup' || type === 'master_detail' || type === 'user' || type === 'owner') return () => undefined; return null; } + +/** + * Field types whose cell editor is a panel opened under the cell, which keeps + * showing its value (objectstack#36023): a list to pick from, a calendar, a + * clock, a palette. Typed input, long text and an address edit in place. + */ +const PANEL_EDITOR_FIELD_TYPES: ReadonlySet = new Set([ + 'select', 'status', 'radio', 'multiselect', 'checkboxes', 'tags', + 'date', 'datetime', 'time', 'color', + 'lookup', 'master_detail', 'user', 'owner', +]); + +/** Where the cell editor of this field type draws; `undefined` leaves it to the table. */ +export function inlineEditorPlacement(fieldType: unknown): 'below' | undefined { + return typeof fieldType === 'string' && PANEL_EDITOR_FIELD_TYPES.has(fieldType) ? 'below' : undefined; +} + +type Translate = (key: string, options?: Record) => string; + +/** A value the cell holds nothing in: what Backspace writes and `required` refuses. */ +export function isEmptyCellValue(value: unknown): boolean { + return value === null || value === undefined || value === '' || (Array.isArray(value) && value.length === 0); +} + +/** What a field's name reads as in a sentence about it. */ +function fieldLabelOf(fieldDef: { label?: unknown; name?: unknown }, columnKey: string): string { + return typeof fieldDef.label === 'string' && fieldDef.label !== '' ? fieldDef.label : columnKey; +} + +/** + * Why Backspace leaves this cell as it is: a required field is never cleared + * (objectstack#36023). `null` when the cell may be cleared. + */ +export function clearRefusalText( + fieldDef: Record | null | undefined, + columnKey: string, + t: Translate, +): string | null { + if (!fieldDef?.required) return null; + return typeof fieldDef.required_message === 'string' + ? fieldDef.required_message + : t('validation.required', { field: fieldLabelOf(fieldDef, columnKey) }); +} + +/** + * Why a value committed into a cell is refused before it is saved, by the + * field's declared rules, or `null` (objectstack#36023). The rules are the + * record form's own (`buildValidationRules`): required, length, range and + * the email / URL shape, each said with the form's sentence. A rule other + * than `required` does not judge an empty value. + */ +export function cellValueRefusal( + fieldDef: Record | null | undefined, + columnKey: string, + value: unknown, + t: Translate, +): string | null { + if (!fieldDef) return null; + const rules = buildValidationRules(fieldDef); + if (!rules) return null; + const field = fieldLabelOf(fieldDef, columnKey); + const said = (rule: any, interp: Record = {}) => + typeof rule?.message === 'string' ? rule.message : t(rule?.messageKey ?? 'validation.pattern', { field, ...interp }); + if (isEmptyCellValue(value)) return clearRefusalText(fieldDef, columnKey, t); + if (typeof value === 'string') { + if (rules.minLength && value.length < rules.minLength.value) return said(rules.minLength, { min: rules.minLength.value }); + if (rules.maxLength && value.length > rules.maxLength.value) return said(rules.maxLength, { max: rules.maxLength.value }); + if (rules.pattern?.value instanceof RegExp && !rules.pattern.value.test(value)) return said(rules.pattern); + } + if (typeof value === 'number') { + if (rules.min && value < rules.min.value) return said(rules.min, { min: rules.min.value }); + if (rules.max && value > rules.max.value) return said(rules.max, { max: rules.max.value }); + } + return null; +}