Skip to content
Merged
16 changes: 16 additions & 0 deletions .changeset/35689-inline-edit-a11y.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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);

Expand Down Expand Up @@ -75,11 +80,14 @@ function schemaOf(onRowSave: Save, extra: Record<string, unknown> = {}) {
};
}

function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true) {
function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true, language?: string) {
const DataTable = ComponentRegistry.get('data-table')!;
const tree = (schema: any) => (withProvider
const table = (schema: Record<string, unknown>) => (withProvider
? <GridCellSelectionProvider value={{}}><DataTable schema={schema} /></GridCellSelectionProvider>
: <DataTable schema={schema} />);
const tree = (schema: any) => (language
? <I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>{table(schema)}</I18nProvider>
: 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;
Expand Down Expand Up @@ -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<HTMLElement>('[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<string, unknown>, _row?: unknown) => {});
const onSelectionChange = vi.fn();
const t = renderTable(onRowSave, { selectable: 'multiple', onSelectionChange });
const rowChecks = () => [...t.container.querySelectorAll('tbody tr')].map((tr) => tr.querySelector<HTMLElement>('[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);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 }) => (
<div role="group" aria-label="Pick a name">
<button type="button" data-testid="pick-omega" onClick={() => ctx.commit('Omega')}>Omega</button>
<button type="button" onClick={() => ctx.commit('Sigma')}>Sigma</button>
</div>
),
},
{ describeCell: (_row, key) => (key === 'name' ? { editor: 'below' } : null) },
);
const panel = (t: ReturnType<typeof renderTable>) => 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<HTMLButtonElement>('[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<HTMLButtonElement>('[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());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<HTMLButtonElement>('[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<HTMLButtonElement>('[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<string, unknown> }) => (
<GridCellSelectionProvider value={value}><DataTable schema={schema} /></GridCellSelectionProvider>
);
const value = { describeCell };
const utils = render(<Host value={value} schema={schemaOf()} />);
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(<Host value={value} schema={schemaOf()} />);
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(<Host value={{ describeCell }} schema={schemaOf()} />);
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();
});
});
10 changes: 9 additions & 1 deletion ui/packages/components/src/context/gridCellSelection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading