diff --git a/.changeset/35689-inline-edit-a11y.md b/.changeset/35689-inline-edit-a11y.md new file mode 100644 index 00000000000..3ebbe1d7f1e --- /dev/null +++ b/.changeset/35689-inline-edit-a11y.md @@ -0,0 +1,16 @@ +--- +'@object-ui/components': patch +'@object-ui/i18n': patch +'@object-ui/plugin-grid': patch +--- + +feat(components): in a list's grid a read-only cell says it is read-only, a cell save is said in one live region, and a touch never edits a cell in place + +Clause-②: yes (widening) +Metadata-protocol: none + +The widening is additive: the new key `table.cellSavedAnnouncement` in every locale pack `@object-ui/i18n` publishes through `./locales`. + +- **Read-only cells.** When the data table is a grid (`role="grid"`: a list page with the select-first cell model, or `keyboardNavigation`), a cell that opens no editor carries `aria-readonly="true"`, and so does the focus inside the selected cell, so a screen reader says "read only" on the cell it moves to. The selected cell adds the host's own facts (`GridCellSelection.describeCell`), asked as it becomes selected and again only when the row is re-read or the host hands a new value, never on each render; the rest read the table's own (`editable`, the column, the row). A plain table carries no `aria-readonly`. In a list, an approval lock or an update verdict that answers after the cell was selected is said on that cell at once, without the reader moving: the lock read re-renders the grid when it answers, and the grid hands the table a new value only when what its cell facts read changed. +- **Save results.** A table that saves each cell (`GridCellSelection` with `onRowSave`) draws one visually hidden polite live region for its whole life and says each saved cell there, by column name ("Saved: Amount"; new pack key `table.cellSavedAnnouncement`, in all eleven locales). Cells saved together are joined in the locale's list punctuation (`validation.formInvalidJoiner`: `、` in ja and zh); a column with no header is never named by its key (the region says "Saved"). A refused save is said once, by the cell's existing alert. The cell's saving/saved mark is no longer a live region of its own (it was mounted with its words and announced unreliably); it stays a named image. +- **Touch.** A tap on a cell that is not selected never edits in place: a lookup cell's edit button is not drawn for a finger, and a tap that lands on one drawn earlier for a mouse does nothing (the row ignores a click on a button). A tap elsewhere on the cell still opens the record, which is where a touch edits. A later click on the button with no pointer of its own (assistive tech) edits as before. diff --git a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx index bf088cc00ef..c9e041c8e2c 100644 --- a/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx +++ b/ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx @@ -24,6 +24,10 @@ * 8. A commit the host asks to confirm (`confirmCommit`, slice S3) is held * with nothing staged: No leaves the cell as it was, Yes writes it; a * paste is asked too, an unchanged value is not. + * 9. objectstack#35689: a save is said in the table's one live region, + * there from the first render; a refusal is said once, by the cell's + * alert. With rows checked, a cell edit writes that one cell, and the + * checks stay. */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -36,6 +40,7 @@ import '../renderers'; // at collection, never inside a case's clocked window (`check:test-source-alias`). import '@object-ui/react-runtime'; import { GridCellSelectionProvider } from '../context/gridCellSelection'; +import { I18nProvider } from '@object-ui/i18n'; afterEach(cleanup); @@ -75,11 +80,14 @@ function schemaOf(onRowSave: Save, extra: Record = {}) { }; } -function renderTable(onRowSave: Save, extra: Record = {}, withProvider = true) { +function renderTable(onRowSave: Save, extra: Record = {}, withProvider = true, language?: string) { const DataTable = ComponentRegistry.get('data-table')!; - const tree = (schema: any) => (withProvider + const table = (schema: Record) => (withProvider ? : ); + const tree = (schema: any) => (language + ? {table(schema)} + : table(schema)); const utils = render(tree(schemaOf(onRowSave, extra))); const cell = (row: number, col: number) => utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement; @@ -403,3 +411,94 @@ describe('data-table autosave — a commit the host asks to confirm first (objec expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' }); }); }); + +describe('data-table autosave — the result is said to assistive tech (objectstack#35689)', () => { + const region = (c: HTMLElement) => c.querySelector('[data-slot="cell-save-announcer"]'); + + it('a saved cell is said in the one live region; the same words again are a new saying', async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave); + // There, and silent, before anything is saved. + expect(region(t.container)).toHaveAttribute('aria-live', 'polite'); + expect(region(t.container)).toHaveClass('sr-only'); + expect(region(t.container)!.textContent).toBe(''); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + // Saving is not said, and the cell's mark is no live region of its own. + expect(region(t.container)!.textContent).toBe(''); + expect(t.cell(0, 0).querySelector('[data-slot="cell-save-state"]')).not.toHaveAttribute('role', 'status'); + expect(t.container.querySelectorAll('[aria-live], [role="status"], [role="alert"]')).toHaveLength(1); + await act(async () => { calls[0].resolve(); }); + expect(region(t.container)).toHaveTextContent('Saved: Name'); + const first = region(t.container)!.firstElementChild; + t.typeAndEnter(0, 0, 'Alpha 3'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + await act(async () => { calls[1].resolve(); }); + expect(region(t.container)).toHaveTextContent('Saved: Name'); + expect(region(t.container)!.firstElementChild).not.toBe(first); + }); + + it("a refused save is said by the cell's alert alone; the region drops the words it held", async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + await act(async () => { calls[0].resolve(); }); + expect(region(t.container)).toHaveTextContent('Saved: Name'); + t.typeAndEnter(0, 1, 'won'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + await act(async () => { calls[1].reject(fieldRefusal([{ field: 'stage', message: 'Stage cannot move to won' }])); }); + expect(screen.getByTestId('cell-save-failure')).toHaveAttribute('role', 'alert'); + expect(screen.getByTestId('cell-save-failure')).toHaveTextContent('Stage cannot move to won'); + expect(region(t.container)!.textContent).toBe(''); + }); + + it("cells saved together are named in the locale's list punctuation", async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave, {}, true, 'zh'); + // A refused cell stays pending and travels with the next commit on its row. + t.typeAndEnter(0, 1, 'won'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + await act(async () => { calls[0].reject(fieldRefusal([{ field: 'stage', message: 'Stage cannot move to won' }])); }); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2)); + expect(Object.keys(calls[1].changes)).toEqual(['stage', 'name']); + await act(async () => { calls[1].resolve(); }); + expect(region(t.container)!.textContent).toBe('已保存:Stage、Name'); + }); + + it('a column with no header is not named by its key', async () => { + const { onRowSave, calls } = deferredSave(); + const t = renderTable(onRowSave, { columns: [{ header: '', accessorKey: 'name' }] }); + t.typeAndEnter(0, 0, 'Alpha 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + await act(async () => { calls[0].resolve(); }); + expect(region(t.container)!.textContent).toBe('Saved'); + }); + + it('CONTROL: a table that does not save per cell draws no region', () => { + const t = renderTable(vi.fn(async () => {}), {}, false); + expect(region(t.container)).toBeNull(); + }); +}); + +describe('data-table autosave — checked rows and a cell edit (objectstack#35689)', () => { + it('with two rows checked, a cell edit writes that one cell of that one row, and both checks stay', async () => { + const onRowSave = vi.fn(async (_i: number, _changes: Record, _row?: unknown) => {}); + const onSelectionChange = vi.fn(); + const t = renderTable(onRowSave, { selectable: 'multiple', onSelectionChange }); + const rowChecks = () => [...t.container.querySelectorAll('tbody tr')].map((tr) => tr.querySelector('[role="checkbox"]')!); + fireEvent.click(rowChecks()[0]); + fireEvent.click(rowChecks()[1]); + expect(onSelectionChange).toHaveBeenLastCalledWith([ROWS[0], ROWS[1]]); + const selectionCalls = onSelectionChange.mock.calls.length; + t.typeAndEnter(1, 0, 'Beta 2'); + await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1)); + expect(onRowSave.mock.calls[0][0]).toBe(1); + expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Beta 2' }); + expect(t.cell(0, 0)).toHaveTextContent('Alpha'); + await act(async () => {}); + for (const check of rowChecks()) expect(check).toHaveAttribute('aria-checked', 'true'); + expect(onSelectionChange).toHaveBeenCalledTimes(selectionCalls); + }); +}); 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 459e524823c..6b21e39e189 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 @@ -27,6 +27,8 @@ * 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. + * 5. objectstack#35689: a picker's panel under the cell hands the focus back + * to the cell when it closes, by Esc and by a pick. */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -431,3 +433,46 @@ describe('data-table select-first — clearing, the panel under the cell, a refu expect(frame(0, 0)).toBeNull(); }); }); + +describe('data-table select-first keys — the focus after a picker panel closes (objectstack#35689)', () => { + // A picker as a host injects it: options that commit on a pick. + const renderPicker = () => renderTable( + { + renderCellEditor: (ctx: { commit: (v?: unknown) => void }) => ( +
+ + +
+ ), + }, + { describeCell: (_row, key) => (key === 'name' ? { editor: 'below' } : null) }, + ); + const panel = (t: ReturnType) => t.cell(0, 0).querySelector('[data-slot="cell-editor-overlay"]'); + + it('Esc in the panel closes it, and the focus is back on the cell, still selected', () => { + const t = renderPicker(); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + expect(panel(t)).toHaveAttribute('data-placement', 'below'); + const option = t.container.querySelector('[data-testid="pick-omega"]')!; + option.focus(); + fireEvent.keyDown(option, { key: 'Escape' }); + expect(panel(t)).toBeNull(); + expect(t.selected()).toBe('0:0'); + expect(document.activeElement).toBe(t.catcher()); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it('a pick commits, closes the panel, and the focus is back on the cell', () => { + const t = renderPicker(); + t.select(0, 0); + fireEvent.keyDown(t.catcher(), { key: 'Enter' }); + const option = t.container.querySelector('[data-testid="pick-omega"]')!; + option.focus(); + fireEvent.click(option); + expect(t.onCellChange).toHaveBeenLastCalledWith(0, 'name', 'Omega', ROWS[0]); + expect(panel(t)).toBeNull(); + expect(t.selected()).toBe('0:0'); + expect(document.activeElement).toBe(t.catcher()); + }); +}); 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 22dbbc20889..9d2a2df6074 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 @@ -34,6 +34,9 @@ * chip; the cell draws an edit button, not the open button, and the edit * button opens the editor through the same gate as double-click * (objectstack#36015). + * 9. objectstack#35689: a touch tap or double-tap never edits in place, the + * edit button included; in the grid a read-only cell carries + * `aria-readonly`, on the cell and on the focus inside it. */ import React from 'react'; import { describe, it, expect, afterEach, vi } from 'vitest'; @@ -504,3 +507,115 @@ describe('data-table select-first — a reference chip opens its record in place expect(t.editButton(0, 1)).toBeNull(); }); }); + +describe('data-table select-first — a touch never edits in place (objectstack#35689)', () => { + it('a touch tap opens the record; a touch double-tap neither selects nor edits', () => { + const t = renderTable(); + fireEvent.pointerDown(t.cell(0, 1), { pointerType: 'touch' }); + fireEvent.click(t.cell(0, 1), { detail: 1 }); + fireEvent.pointerDown(t.cell(0, 1), { pointerType: 'touch' }); + fireEvent.click(t.cell(0, 1), { detail: 2 }); + fireEvent.doubleClick(t.cell(0, 1)); + expect(t.onRowClick).toHaveBeenCalled(); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 1)).not.toHaveAttribute('data-selected-cell'); + expect(t.onCellChange).not.toHaveBeenCalled(); + }); + + it("a tap on a reference cell's edit button, on a cell not selected, edits nothing; a mouse click on it edits", () => { + const openRecord = vi.fn(); + const t = renderTable({ selection: { referenceCells: { isReferenceColumn: (key) => key === 'site', openRecord } } }); + const button = () => t.cell(0, 3).querySelector('[data-testid="cell-edit-button"]')!; + // A finger reaching the cell does not draw the button. + fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'touch' }); + expect(button().className).toContain('hidden'); + // Drawn for a mouse before, a tap on it is still not an edit. + fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'mouse' }); + expect(button().className).toMatch(/(^|\s)flex(\s|$)/); + fireEvent.pointerDown(button(), { pointerType: 'touch' }); + fireEvent.click(button()); + expect(t.editor()).toBeNull(); + expect(t.cell(0, 3)).not.toHaveAttribute('data-selected-cell'); + // CONTROL: the mouse's click on the same button edits. + fireEvent.pointerDown(button(), { pointerType: 'mouse' }); + fireEvent.click(button()); + expect(t.editor()).not.toBeNull(); + }); +}); + +describe('data-table select-first — a touch press is read by its own click only (objectstack#35689)', () => { + it('after a tap on the edit button, a click with no pointer of its own (assistive tech) edits', () => { + const t = renderTable({ selection: { referenceCells: { isReferenceColumn: (key) => key === 'site', openRecord: vi.fn() } } }); + const button = () => t.cell(0, 3).querySelector('[data-testid="cell-edit-button"]')!; + fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'mouse' }); + fireEvent.pointerDown(button(), { pointerType: 'touch' }); + fireEvent.click(button()); + expect(t.editor()).toBeNull(); + fireEvent.click(button()); + expect(t.editor()).not.toBeNull(); + }); +}); + +describe('data-table select-first — a read-only cell says so in the grid (objectstack#35689)', () => { + it("the selected cell reads the host's facts: aria-readonly on the cell and on its focus; an editable one carries none", () => { + const t = renderTable({ + selection: { describeCell: (_row, key) => (key === 'amount' ? { readOnlyReason: 'This value is calculated.' } : null) }, + }); + expect(t.container.querySelector('table')).toHaveAttribute('role', 'grid'); + fireEvent.click(t.cell(0, 1)); + expect(t.cell(0, 1)).toHaveAttribute('aria-readonly', 'true'); + expect(t.catcher()).toHaveAttribute('aria-readonly', 'true'); + expect(document.activeElement).toBe(t.catcher()); + fireEvent.keyDown(t.catcher()!, { key: 'ArrowLeft' }); + expect(t.cell(0, 0)).not.toHaveAttribute('aria-readonly'); + expect(t.catcher()).not.toHaveAttribute('aria-readonly'); + }); + + it("the host's facts are asked as the cell becomes selected, never per render; a new host value is asked again", () => { + const DataTable = ComponentRegistry.get('data-table')!; + let locked = false; + const describeCell = vi.fn((_row: unknown, key: string) => (key === 'amount' && locked ? { readOnlyReason: 'Locked.' } : null)); + const schemaOf = () => ({ + type: 'data-table', + columns: [{ header: 'Name', accessorKey: 'name' }, { header: 'Amount', accessorKey: 'amount', type: 'number' }], + data: ROWS, + editable: true, + searchable: false, + pagination: false, + }); + const Host = ({ value, schema }: { value: GridCellSelection; schema: Record }) => ( + + ); + const value = { describeCell }; + const utils = render(); + const amount = () => utils.container.querySelectorAll('tbody tr')[0].querySelectorAll('td[data-grid-cell]')[1]; + fireEvent.click(amount()); + expect(amount()).toHaveAttribute('data-selected-cell'); + expect(amount()).not.toHaveAttribute('aria-readonly'); + const asked = describeCell.mock.calls.length; + expect(asked).toBeGreaterThan(0); + // The table renders again, three times, with nothing the answer reads changed. + for (let i = 0; i < 3; i++) utils.rerender(); + expect(describeCell).toHaveBeenCalledTimes(asked); + // The host's answer changed and it hands a new value: the cell says so + // where it is, without the reader moving. + locked = true; + utils.rerender(); + expect(amount()).toHaveAttribute('data-selected-cell'); + expect(amount()).toHaveAttribute('aria-readonly', 'true'); + expect(utils.container.querySelector('[data-slot="cell-type-catcher"]')).toHaveAttribute('aria-readonly', 'true'); + }); + + it("every cell of a table that edits nothing is read-only, by the table's own facts", () => { + const t = renderTable({ extra: { editable: false } }); + const cells = [...t.container.querySelectorAll('td[data-grid-cell]')]; + expect(cells.length).toBe(ROWS.length * 4); + for (const td of cells) expect(td).toHaveAttribute('aria-readonly', 'true'); + }); + + it('CONTROL: outside the grid no cell carries aria-readonly', () => { + const t = renderTable({ selection: null, extra: { editable: false } }); + expect(t.container.querySelector('table')).not.toHaveAttribute('role'); + expect(t.container.querySelector('[aria-readonly]')).toBeNull(); + }); +}); diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index 6c7c8a88304..b4d83686973 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -109,7 +109,15 @@ export interface GridReferenceCells { } export interface GridCellSelection { - /** The host's facts for one cell; asked when the reader acts on it, never per render. */ + /** + * The host's facts for one cell. The table asks for them when the reader + * acts on a cell (an edit, a key, a paste), and for the selected cell's + * `aria-readonly` (objectstack#35689): once as the cell becomes selected, + * and again when its row is re-read or the provider's value is a new + * object. The value's identity is part of this contract: keep it stable + * across renders (memoise it) and hand a new one only when an answer may + * have changed, or the selected cell is asked on every render. + */ describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined; /** Called when a cell becomes the selected one (a host may prefetch what an edit will need). */ onCellSelect?: (row: any, columnKey: string) => void; diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index bdd4df1d66a..5909612bcb9 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -374,6 +374,11 @@ const TABLE_DEFAULT_TRANSLATIONS: Record = { // rule the list cannot complete. 'table.cellSaving': 'Saving…', 'table.cellSaved': 'Saved', + // objectstack#35689 — what the table's live region says when cells saved. + 'table.cellSavedAnnouncement': 'Saved: {{fields}}', + // The pack's list punctuation the announcement joins column names with + // (`、` in ja and zh), the key the form's field lists use. + 'validation.formInvalidJoiner': ', ', 'table.openRecordToFinish': 'Open the record to finish this change', 'common.actions': 'Actions', // objectui#10625 — the inline date editors' notice for a stored value @@ -1487,6 +1492,13 @@ function CellEditButton({ const ref = useRef(null); const editableRef = useRef(editable); editableRef.current = editable; + const selectedRef = useRef(selected); + selectedRef.current = selected; + // objectstack#35689 — the pointer that pressed the button for the click that + // follows, cleared by that click. A touch never selects the cell, so on a + // cell not selected the button is never drawn for it, and one it lands on + // anyway (drawn for a mouse before) edits nothing. + const pressedByRef = useRef(''); const [allowed, setAllowed] = useState(false); useLayoutEffect(() => { if (selected) setAllowed(editableRef.current()); @@ -1494,7 +1506,8 @@ function CellEditButton({ useEffect(() => { const host = ref.current?.closest('td'); if (!host) return undefined; - const measure = () => setAllowed(editableRef.current()); + const measure = (e: PointerEvent) => + setAllowed(e.pointerType === 'touch' && !selectedRef.current ? false : editableRef.current()); host.addEventListener('pointerenter', measure); return () => host.removeEventListener('pointerenter', measure); }, []); @@ -1511,9 +1524,19 @@ function CellEditButton({ allowed ? 'flex' : 'hidden', selected ? 'opacity-100' : 'opacity-0 group-hover/cell:opacity-100', )} + onPointerDown={(e) => { pressedByRef.current = e.pointerType; }} onMouseDown={(e) => e.preventDefault()} onDoubleClick={(e) => e.stopPropagation()} onClick={(e) => { + // objectstack#35689 — a tap on an unselected cell edits nothing in + // place. On the button it does nothing at all: the row's click ignores + // a click on a button, so the tap opens no record either (a tap beside + // the button opens it). The press is read once: a later click with no + // pointer of its own (assistive tech) is not taken for this touch. + const pressedBy = pressedByRef.current; + pressedByRef.current = ''; + const pointer = (e.nativeEvent as PointerEvent).pointerType || pressedBy; + if (!selected && pointer === 'touch') return; e.stopPropagation(); onEdit(); }} @@ -2169,6 +2192,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const [rowRefusals, setRowRefusals] = useState>(new Map()); // Each cell's save state while it shows: in flight, or just saved. const [cellSaveStates, setCellSaveStates] = useState>>(new Map()); + // objectstack#35689 — what the table's one live region says about the last + // cell save. `seq` gives each saying a node of its own, so the same words + // twice are said twice. + const [saveAnnouncement, setSaveAnnouncement] = useState<{ seq: number; text: string }>({ seq: 0, text: '' }); // The refused cell whose reason opens on its own as the refusal lands. const [failureNotice, setFailureNotice] = useState<{ rowKey: PendingRowKey; columnKey: string } | null>(null); // The rows a save updated in place since the rows last loaded, each as it @@ -3420,6 +3447,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { }); setFailureNotice((prev) => (prev?.rowKey === rowKey ? null : prev)); flashSaved(rowKey, sentKeys); + // Each saved cell by its column's header, in the locale's list + // punctuation; a column with no header is never named by its key. + const fields = sentKeys.flatMap((key) => { + const header = columns.find((c) => c.accessorKey === key)?.header; + return typeof header === 'string' && header !== '' ? [header] : []; + }); + const said = fields.length > 0 + ? t('table.cellSavedAnnouncement', { fields: fields.join(t('validation.formInvalidJoiner')) }) + : t('table.cellSaved'); + setSaveAnnouncement((prev) => ({ seq: prev.seq + 1, text: said })); } catch (error) { // The edits stay pending and the cells keep what was typed. Each cell the // refusal names shows its own reason; a cell it does not name shows them @@ -3443,6 +3480,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { needsRecord: Object.keys(named).some((field) => !editableHere(field)), })); setFailureNotice({ rowKey, columnKey: sentKeys[0] }); + // The refusal is said by the cell's own alert (`CellSaveFailure`), once; + // the region drops an earlier "saved" so it is never read after it. + setSaveAnnouncement((prev) => (prev.text === '' ? prev : { seq: prev.seq + 1, text: '' })); } finally { runningSavesRef.current.delete(rowKey); if (saveAgainRef.current.delete(rowKey)) requestAutosave(rowKey); @@ -3689,6 +3729,25 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const selectedPos = selectedRowIndex >= 0 && selectedColIndex >= 0 ? { rowIndex: selectedRowIndex, colIndex: selectedColIndex } : null; + // objectstack#35689 — whether the host holds the selected cell read-only + // (`GridCellSelection.describeCell`), for its `aria-readonly`. Asked as a + // cell becomes selected, and again only when what the answer reads changes: + // the row is re-read, or the host hands the grid a new value (an answer it + // was waiting on arrived). Not asked per render (a host keeps its value + // stable: `GridCellSelection.describeCell`); every render reads this. + const selectedRow = selectedPos ? paginatedData[selectedPos.rowIndex] : undefined; + const selectedColumnKey = selectedPos ? columns[selectedPos.colIndex].accessorKey : undefined; + const [selectedHostReadOnly, setSelectedHostReadOnly] = useState<{ row: unknown; columnKey: string } | null>(null); + useLayoutEffect(() => { + const readOnly = selectedRow !== undefined && selectedColumnKey !== undefined + && !!cellSelection?.describeCell?.(selectedRow, selectedColumnKey)?.readOnlyReason; + setSelectedHostReadOnly((prev) => { + if (!readOnly || selectedColumnKey === undefined) return null; + return prev !== null && prev.row === selectedRow && prev.columnKey === selectedColumnKey + ? prev + : { row: selectedRow, columnKey: selectedColumnKey }; + }); + }, [selectedRow, selectedColumnKey, cellSelection]); const setSelectedCell = (pos: { rowIndex: number; colIndex: number } | null) => setSelectedCellKey(pos ? { rowKey: pendingRowKeyOf(paginatedData[pos.rowIndex]), columnKey: columns[pos.colIndex].accessorKey } : null); // objectstack#35688 — a selected cell whose content is cut off shows it in @@ -4550,6 +4609,15 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { )} + {/* objectstack#35689 — the one live region a cell save is said in. It is + drawn for the table's whole life: a region that appears with its words + in it is often not read. */} + {autosaves && ( +
+ {saveAnnouncement.text !== '' && {saveAnnouncement.text}} +
+ )} + {/* Table. When `borderless`, drop the rounded frame so the table sits flush against its container. The outer box holds the scroll box and the right-edge scroll shadow beside it (objectui#12463). */} @@ -5205,6 +5273,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // objectstack#35684 — the selected cell of the select-first model. const isSelectedCell = selectFirst && selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex; const showsPreview = isSelectedCell && !isEditing && previewKey === `${rowIndex}:${colIndex}`; + // objectstack#35689 — a read-only cell says so to assistive tech, in the + // grid only, from the table's own facts. The selected cell (the one a + // reader moves to) adds the host's, asked when it became selected + // (`selectedHostReadOnly`: `describeCell` is not asked per render). + const cellReadOnly = keyboardNavigation + && (!isEditable || (isSelectedCell && selectedHostReadOnly !== null + && selectedHostReadOnly.row === row && selectedHostReadOnly.columnKey === col.accessorKey)); // What the cell draws; the preview layer draws the same, unclipped. const drawCell = (): React.ReactNode => (typeof col.cell === 'function' ? col.cell(cellValue, row) @@ -5360,6 +5435,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { data-editing-cell={isEditing ? '' : undefined} data-selected-cell={isSelectedCell ? '' : undefined} aria-selected={selectFirst ? isSelectedCell : undefined} + aria-readonly={cellReadOnly || undefined} data-cell-error={cellError} title={cellError} > @@ -5381,6 +5457,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { autoComplete="off" spellCheck={false} aria-label={typeof col.header === 'string' ? col.header : col.accessorKey} + // The focus a reader lands on, so it says read-only too. + aria-readonly={cellReadOnly || undefined} className={cn( "absolute inset-0 h-full w-full min-w-0 border-0 bg-transparent px-3 py-0 text-transparent caret-transparent outline-none pointer-events-none", // An open composition is drawn over the cell, so its @@ -5446,13 +5524,14 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { })()} {selectFirst && !isEditing && cellSaveStates.get(rowKey)?.[col.accessorKey] && (() => { // objectstack#35685 — the cell's own save state, drawn over its - // edge so nothing moves. + // edge so nothing moves. The result is said by the table's live + // region (objectstack#35689); the mark is named, never live. const state = cellSaveStates.get(rowKey)?.[col.accessorKey]; return ( diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 1fa0256b476..224ab05a7db 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -570,6 +570,7 @@ const ar = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "جارٍ الحفظ…", cellSaved: "تم الحفظ", + cellSavedAnnouncement: "تم الحفظ: {{fields}}", openRecordToFinish: "افتح السجل لإكمال التغيير", }, grid: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7791b59d402..e6b4542679c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -536,6 +536,7 @@ const de = { // 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", + cellSavedAnnouncement: "Gespeichert: {{fields}}", openRecordToFinish: "Datensatz öffnen, um die Änderung abzuschließen", }, grid: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 06a2ea41f63..3904727e6a4 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -804,6 +804,8 @@ const en = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: 'Saving…', cellSaved: 'Saved', + // objectstack#35689 — what the list's live region says when cells saved. + cellSavedAnnouncement: 'Saved: {{fields}}', openRecordToFinish: 'Open the record to finish this change', }, grid: { diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 84b4753fdef..4f96bcf9dd1 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -548,6 +548,7 @@ const es = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Guardando…", cellSaved: "Guardado", + cellSavedAnnouncement: "Guardado: {{fields}}", openRecordToFinish: "Abre el registro para completar el cambio", }, grid: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index e5f07ac6881..8703583b1d4 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -543,6 +543,7 @@ const fr = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Enregistrement…", cellSaved: "Enregistré", + cellSavedAnnouncement: "Enregistré : {{fields}}", openRecordToFinish: "Ouvrir la fiche pour terminer la modification", }, grid: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 056bf21a38b..9aaab45e7b4 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -536,6 +536,7 @@ const ja = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "保存中…", cellSaved: "保存しました", + cellSavedAnnouncement: "保存しました:{{fields}}", openRecordToFinish: "レコードを開いて変更を完了してください", }, grid: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 92f7645689c..67257ce865a 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -536,6 +536,7 @@ const ko = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "저장 중…", cellSaved: "저장됨", + cellSavedAnnouncement: "저장됨: {{fields}}", openRecordToFinish: "레코드를 열어 변경을 완료하세요", }, grid: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0f89efbb6fc..9f4c5a6e3fc 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -543,6 +543,7 @@ const pt = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Salvando…", cellSaved: "Salvo", + cellSavedAnnouncement: "Salvo: {{fields}}", openRecordToFinish: "Abra o registro para concluir a alteração", }, grid: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index aea162b0410..a617ec92c30 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -553,6 +553,7 @@ const ru = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: "Сохранение…", cellSaved: "Сохранено", + cellSavedAnnouncement: "Сохранено: {{fields}}", openRecordToFinish: "Откройте запись, чтобы завершить изменение", }, grid: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index cc782f9a597..42aa5b51f6c 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -549,6 +549,7 @@ const zh = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: '保存中…', cellSaved: '已保存', + cellSavedAnnouncement: '已保存:{{fields}}', openRecordToFinish: '打开记录完成修改', }, grid: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 4c10186e75a..4cef4948b0a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -549,6 +549,7 @@ const zhHant = { // objectstack#35685 — a list cell's own save state, and the way out of a rule the list cannot complete. cellSaving: '儲存中…', cellSaved: '已儲存', + cellSavedAnnouncement: '已儲存:{{fields}}', openRecordToFinish: '開啟記錄完成修改', }, grid: { diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 1b6644db463..813cf6e70c2 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1371,7 +1371,19 @@ export const ObjectGrid: React.FC = ({ } : undefined, }); - const gridCellSelection: GridCellSelection | null = hostCellSelection + // objectstack#35689 — the value is new only when what `describeCell` + // answers from changed (the object, its fields, the reader's permissions, + // a verdict or an approval lock landing, the language): the table asks the + // selected cell's facts again on a new value, so one new on every render + // would ask on every render. The commit question and the chip opener read + // what this render holds through `latestCellHooks`. + const gridEditable = schema.editable ?? false; + const latestCellHooks = React.useRef({ requiredPrompt, askStateMove, openReferencedRecord }); + React.useLayoutEffect(() => { + latestCellHooks.current = { requiredPrompt, askStateMove, openReferencedRecord }; + }); + const opensReferencedRecords = !!openReferencedRecord; + const gridCellSelection = useMemo((): GridCellSelection | null => (hostCellSelection ? { describeCell: (row, columnKey) => { const fieldDef = objectFields?.[columnKey]; @@ -1383,9 +1395,13 @@ export const ObjectGrid: React.FC = ({ const kind = cellReadOnlyKind({ fieldDef, fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey), - gridEditable: schema.editable ?? false, + gridEditable, objectEditable: objectInlineEditable, - canUpdate: resolveAffordanceGrant('listInlineEdit', affordanceSource), + canUpdate: resolveAffordanceGrant('listInlineEdit', { + objectSchema: objectSchema as SchemaLike | null | undefined, + objectName, + perms, + }), approvalLocked: approvalLocks.isLocked(recordId, row), recordUpdate, }); @@ -1422,19 +1438,25 @@ export const ObjectGrid: React.FC = ({ // before anything is written (`./objectGridStateConfirm`). A move that // needs fields filled asks for them first; that dialog is the // confirmation, so a state-machine move does not ask twice. - confirmCommit: (row, columnKey, value) => - requiredPrompt.ask(row, columnKey, value, () => askStateMove(row, columnKey, value)), + confirmCommit: (row, columnKey, value) => { + const { requiredPrompt: prompt, askStateMove: askMove } = latestCellHooks.current; + return prompt.ask(row, columnKey, value, () => askMove(row, columnKey, value)); + }, // objectstack#36015 — a lookup cell's chip opens its record in place. - ...(openReferencedRecord + ...(opensReferencedRecords ? { referenceCells: { isReferenceColumn: (columnKey: string) => opensReferenceInPlace(objectFields?.[columnKey]), - openRecord: openReferencedRecord, + openRecord: (target: string, recordId: string) => + latestCellHooks.current.openReferencedRecord?.(target, recordId), }, } : {}), } - : null; + : null), [ + hostCellSelection, opensReferencedRecords, objectFields, objectSchema, objectName, perms, + gridEditable, objectInlineEditable, approvalLocks, recordVerdict, pageRecordIds, t, + ]); // objectstack#35685 — the state-machine confirm, the grid's next question // when the required-fields prompt has nothing to ask. function askStateMove(row: any, columnKey: string, value: unknown): Promise | null { 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 25e93292b31..e139ec0e90e 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 @@ -79,6 +79,8 @@ let lockStatus = 200; let lockReads: string[][] = []; /** How long the lock read and the explain read take, in ms; 0 answers at once. */ let lockDelay = 0; +/** While set, a lock read answers only once it settles (objectstack#35689). */ +let lockGate: Promise | null = null; let explainDelay = 0; let explainReads = 0; /** The rows the explain engine refuses `update` on. */ @@ -95,6 +97,7 @@ beforeEach(() => { lockStatus = 200; lockReads = []; lockDelay = 0; + lockGate = null; explainDelay = 0; explainReads = 0; refusedIds = new Set(); @@ -105,6 +108,7 @@ beforeEach(() => { const ids: string[] = Array.isArray(body.recordIds) ? body.recordIds : []; if (href.endsWith(LOCKS_URL)) { lockReads.push(ids); + if (lockGate) await lockGate; return after(lockDelay, { ok: lockStatus < 300, status: lockStatus, @@ -221,6 +225,41 @@ describe('ObjectGrid cellSelection — why a cell opens no editor', () => { }); }); +describe('ObjectGrid cellSelection — the selected cell says a lock that answers after it was selected (objectstack#35689)', () => { + const catcher = (g: { container: HTMLElement }) => g.container.querySelector('[data-slot="cell-type-catcher"]'); + function holdLockRead(): () => void { + let answer!: () => void; + lockGate = new Promise((resolve) => { answer = resolve; }); + return answer; + } + + it('a row the service says is locked turns aria-readonly on where the selection is', async () => { + lockedIds = new Set(['3']); + const answer = holdLockRead(); + const g = await renderGrid(); + // Gamma has no approval_status: editable until the service answers. + fireEvent.click(g.cell(2, 0)); + await waitFor(() => expect(lockReads).toEqual([['3', '1', '2']])); + expect(g.cell(2, 0)).not.toHaveAttribute('aria-readonly'); + answer(); + await waitFor(() => expect(g.cell(2, 0)).toHaveAttribute('aria-readonly', 'true')); + expect(catcher(g)).toHaveAttribute('aria-readonly', 'true'); + expect(g.cell(2, 0)).toHaveAttribute('data-selected-cell'); + }); + + it("a row whose approval_status stands in as locked turns it off when the service says it is not", async () => { + const answer = holdLockRead(); + const g = await renderGrid(); + fireEvent.click(g.cell(1, 0)); + await waitFor(() => expect(lockReads).toEqual([['2', '1', '3']])); + expect(g.cell(1, 0)).toHaveAttribute('aria-readonly', 'true'); + answer(); + await waitFor(() => expect(g.cell(1, 0)).not.toHaveAttribute('aria-readonly')); + expect(catcher(g)).not.toHaveAttribute('aria-readonly'); + expect(g.cell(1, 0)).toHaveAttribute('data-selected-cell'); + }); +}); + describe('ObjectGrid cellSelection — an edit waits for the row\'s lock and verdict (objectstack#35795)', () => { const CHECKING = 'Checking whether this record can be edited…'; const LOCKED = "This record is locked while it's in approval."; diff --git a/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts index 2cfa8657cdc..271953e6457 100644 --- a/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts +++ b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts @@ -29,6 +29,11 @@ * back to the column (fail open: the server refuses a locked write whatever * this says). A 501 (no approvals service in this deployment) is latched and * the read is not sent again, like the record page's. + * + * A read that answers re-renders the host (objectstack#35689), so what the + * grid already says of the selected cell (its `aria-readonly`) follows the + * lock without waiting for the reader to move: `isLocked`, and the value this + * hook returns, are new exactly when the answers it reads changed. */ import * as React from 'react'; import { APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS } from '@objectstack/spec/contracts'; @@ -75,9 +80,13 @@ export function useRowApprovalLocks(objectName: string | undefined): RowApproval const answersRef = React.useRef(new Map()); /** The read each row asked is waiting on, while it is on the wire. */ const wiresRef = React.useRef(new Map>()); + // Counts the changes to what `isLocked` reads: a read answering, the answers dropped. + const [answerSeq, setAnswerSeq] = React.useState(0); React.useEffect(() => { + const dropped = answersRef.current.size > 0; answersRef.current = new Map(); wiresRef.current = new Map(); + if (dropped) setAnswerSeq((n) => n + 1); }, [objectName, invalidation]); const probe = React.useCallback((recordIds: readonly unknown[]) => { @@ -124,13 +133,18 @@ export function useRowApprovalLocks(objectName: string | undefined): RowApproval answers.set(id, answered.get(id) ?? 'unanswered'); wires.delete(id); } + // Answers for answers since dropped (the object changed) read nowhere. + if (answered.size > 0 && answers === answersRef.current) setAnswerSeq((n) => n + 1); } })(); for (const id of chunk) if (answers.get(id) === 'asking') wires.set(id, wire); } }, [objectName, apiFetch]); + // `answerSeq` is read so this callback, and the value below, are new when a + // read answers: the host's cell facts depend on it. const isLocked = React.useCallback((recordId: unknown, row: any) => { + void answerSeq; const answer = recordId == null ? undefined : answersRef.current.get(String(recordId)); const readAnswered = typeof answer === 'object'; return resolveApprovalLock({ @@ -138,7 +152,7 @@ export function useRowApprovalLocks(objectName: string | undefined): RowApproval openApproval: readAnswered && answer.locked ? { locked: true } : null, recordStatus: row?.approval_status, }).locked; - }, []); + }, [answerSeq]); const settling = React.useCallback( (recordId: unknown) => (recordId == null ? null : wiresRef.current.get(String(recordId)) ?? null),