Skip to content

Commit 5345905

Browse files
feat(grid): read-only cells say so in the grid, a cell save is said in one live region, a touch never edits in place (#35689 slice A) (#36332)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XURgXCZHcjPoyo5g9cMEATi)_ Part of #35689 — slice A (touch, accessibility, checked rows). Slice B (a row moving to its new group, group subtotals and the footer total refreshing after a save) stays on the card for its own PR. Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 平板上点列表的一行只会打开记录,不会误进格子编辑;读屏软件移到不能改的格子会读出「只读」(审批锁在选中后才查到时也会立刻读出),格子保存后会读出「已保存:字段名」,失败时读出原因;其余用户无感。 - 列表行内编辑重做专题的收尾(无障碍与触屏部分),分组移动与合计刷新另开一个 PR。 - 出错时最坏是读屏软件少读或多读一句、平板上点到编辑按钮没反应,不影响保存的数据;可以直接撤回。 - 无 ## What changes Measured on `origin/main` before any edit (the dispatch's six mechanism assumptions): 1. **Touch.** A touch tap on a cell opens the record and never selects or edits (`isTouchPress`, from #35684): holds, pinned. One gap measured: a lookup cell's edit button (the pencil) is drawn at `opacity-0` once any pointer enters the cell and is still hit-testable, so a tap on the right edge of an unselected lookup cell landed on the invisible button and **opened the editor in place**. Fixed in `CellEditButton`: a finger entering an unselected cell does not draw the button, and a touch click on one drawn earlier for a mouse does nothing (the row ignores a click on a button). The press is read by its own click only, then cleared, so a later click with no pointer of its own (assistive tech) edits as before. The explicit edit entry on touch is the record page (a tap beside the button opens it), per the card's 「通过记录页或显式的编辑入口」. 2. **`aria-readonly`.** Absent. Now, only when the table is `role="grid"`, a data cell that opens no editor carries `aria-readonly="true"`, and so does the type-catcher input that holds focus in the selected cell (the element a screen reader lands on). Every cell reads the table's own facts (`editable`, the column, `isRowEditable`); the selected cell adds the host's (`describeCell`). The host's answer is **asked as the cell becomes selected and kept in state** (`selectedHostReadOnly`), asked again only when the selected row is re-read or the host hands the table a new `GridCellSelection` value, so it is not asked per render for a host whose value is stable. `describeCell`'s TSDoc now says exactly that: asked when the reader acts on a cell, once as a 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 the contract, so a host keeps it stable (memoised) or the selected cell is asked on every render. - In the list (`ObjectGrid`), the host value is now memoised on what its cell facts read (fields, object, permissions, the view's `editable`, the update verdicts, the approval locks, the page's record ids, the language), so it is new only when an answer can have changed; the commit question and the chip opener read the latest render through a ref. - `useRowApprovalLocks` re-renders its host when a lock read answers (and when the answers are dropped on an invalidation): `isLocked` and the hook's value are new exactly then. So a lock answered after the select-time ask is said on the selected cell at once, without the reader moving, both ways (locked by the service, or a pending `approval_status` the service says is not locked). 3. **Live region.** Before: a per-cell `role="status"` span mounted with its state, its words only in `aria-label`, plus `role="alert"` on failure. A region that mounts with its content is often not announced, and a label is not live content. Now one persistent visually hidden `aria-live="polite"` region per table that saves per cell (`autosaves`), drawn for the table's whole life; a successful save writes "Saved: COLUMN" into it (new key `table.cellSavedAnnouncement`, all eleven packs), each saying in a node of its own so the same words twice are said twice. Cells saved together are joined with the pack's list punctuation (`validation.formInvalidJoiner`, the key the form's field lists use: `、` in ja and zh), and a column with no header is never named by its key (the region then says `table.cellSaved`, "Saved"). A failure stays with the existing cell alert, said once; the region drops the earlier "saved". The per-cell mark becomes `role="img"` with its existing label: named, never live, so no duplicate announcement. 4. **Focus after a picker panel closes** (`placement="below"`): measured, it already returns to the cell by Esc and by a pick (`focusSelectionRef`, #35688). Pinned, no source change. 5. **Selection frame contrast** (`border-2 border-primary`, WCAG 1.4.11, 3:1 needed): passes everywhere, no change. Token arithmetic (sRGB relative luminance) on the shipped themes: - Console light (`--primary` 211 100% 50% on `--background` white): 3.97; on the hover row (muted/40) 3.74; on a checked row (primary/5) 3.73; on a checked hovered or active-record row (primary/10) 3.49; on full muted 3.40. - Console dark (211 100% 60% on 240 6% 6%): 6.34; hover 5.83; checked 6.03; checked hover/active 5.67. - `@object-ui/components` default theme: 17.84 light, 19.09 dark, at least 14.53 on any row state. 6. **Selection.** `commitCellValue` stages one cell and never reads `selectedRowIds`; `selectionResetKey` moves only on bulk actions and refresh: holds, pinned. ### Review round (L1 7076074435, L2 7076070602) | Item | Resolution | Commit | |:---|:---|:---| | S1 (L1, L2): `describeCell` asked per render | Asked at selection, kept in state; re-asked only on a re-read row or a new host value; `ObjectGrid`'s value memoised so it is new only when its facts can change. TSDoc kept as is. | `1733276c`, `6bc85294` | | S2 (L2): a lock answered after the select-time probe | `useRowApprovalLocks` re-renders on an answer; re-applied on main's batched lock read (#36295) in the merge | `1733276c`, `65b9199f` | | N1: touch-tap comment, `pressedByRef` never reset | Comment says the tap does nothing on the button; the press is cleared by the click that reads it | `1733276c` | | N2: hard-coded `', '`, raw `accessorKey` | `validation.formInvalidJoiner`; a header-less column is left unnamed | `1733276c` | | N3: claim's file surface | The final file surface is in the dev report for the seat to amend the claim | report | | L1-d 7078101760 item 1, L2 R1 (7077725274): TSDoc still said "never per render" | `describeCell` TSDoc says when the table asks it and that the provider value's identity matters; the two data-table comments that echoed it aligned | `69919545` | ## Tests New card-named describes, each in the component's existing harness file: - `data-table-select-first-35684.test.tsx`: a touch tap opens the record and a touch double-tap neither selects nor edits; a tap on an unselected lookup cell's edit button edits nothing (control: the mouse's click edits); after such a tap, a click with no pointer of its own edits; the selected read-only cell carries `aria-readonly` on the cell and its focus, an editable one none; **the host's facts are asked as the cell is selected and not again across three re-renders, and a new host value is asked again and turns `aria-readonly` on where the selection is**; a table that edits nothing marks every cell; control: outside the grid no `aria-readonly`. - `data-table-autosave-35685.test.tsx`: the region is there and silent before any save, says "Saved: Name" after one, a second saying is a new node, saving is not said, and the table holds exactly one live element; cells saved together read `已保存:Stage、Name` in zh; a header-less column reads "Saved"; a refused save is said by the cell alert alone and the region empties; control: no region without per-cell save. With two rows checked, a cell edit sends one update of that one cell and both checks stay. - `data-table-keys-35687.test.tsx`: a picker panel under the cell hands focus back to the cell on Esc and on a pick. - `ObjectGrid.cellSelection-35684.test.tsx`: with the page's lock read held open, a row the service says is locked turns `aria-readonly` on once the read answers, and a row whose `approval_status` stands in as locked turns it off once the service says it is not, both while the cell stays selected. Readings, all through `scripts/pm/os-verify-lock.sh`. Head `69919545` changes only the TSDoc and two comments over `65b9199f`: <details><summary>At 6991954 (TSDoc round)</summary> - Closure build `pnpm --workspace-concurrency=2 --filter '@object-ui/components^...' build`, then `pnpm --filter @object-ui/components run type-check`, then the three data-table harnesses and `ObjectGrid.cellSelection-35684`: Test Files 4 passed (4); Tests 116 passed (116); VERDICT command-exit 0. - `dispatch-gates --commands` re-derived: the same 42 families as at 65b9199; `pnpm check:nul-bytes` exit 0. The other families were not re-run locally for a comment-only delta; CI runs them (below). </details> <details><summary>Type-check, the touched harness files and the affected packages' suites at 65b9199</summary> - Closure build `pnpm --workspace-concurrency=2 --filter '@object-ui/plugin-grid^...' build`, then `pnpm --filter @object-ui/components run type-check`, `pnpm --filter @object-ui/plugin-grid run type-check`, `pnpm --filter @object-ui/i18n run type-check`: VERDICT command-exit 0 (each script name echoed in the log). - Six harness files (the three table harnesses, `ObjectGrid.cellSelection-35684`, `ObjectGrid.autosave-35685`, `ObjectGrid.requiredPrompt-35956`): Test Files 6 passed (6); Tests 154 passed (154). - `pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-grid/ packages/components/ packages/i18n/`: Test Files 910 passed, 1 skipped (911); Tests 9532 passed, 37 skipped (9569); VERDICT command-exit 0. - `pnpm --dir ui exec vitest run --maxWorkers=2 scripts/` (derived family): Test Files 172 passed, 2 skipped (174); Tests 5127 passed, 2 skipped (5129); exit 0. </details> <details><summary>Ablations this round (one each, through `scripts/ablation-replace.mjs`: anchor hit once, blob changed, restored to the HEAD blob, `git diff HEAD` empty)</summary> The suites read `data-table.tsx` and the hook from source (the ui vitest config aliases `@object-ui/components` to `src`; the grid test imports the hook relatively), so no rebuild per leg was owed. - A1, the per-render ask put back (`cellReadOnly` calling `readOnlyReasonOf` on the selected cell): 1 red, "the host's facts are asked as the cell becomes selected, never per render" (expected 2 calls, got 5); the other aria pins stay green, as they should. - A2, the hook's re-render on an answer removed: 2 red, both lock-answer pins in `ObjectGrid.cellSelection-35684`. - A3, the press not cleared by its click: 1 red, "after a tap on the edit button, a click with no pointer of its own (assistive tech) edits". - A4, the Latin comma put back: 1 red, the zh list-punctuation pin. - A5, the key fallback put back: 1 red, "a column with no header is not named by its key". - Restore proof after the run: `data-table.tsx` blob b7a0e66 and the hook blob 271953e, each equal to HEAD; `git diff HEAD` 0 lines. </details> <details><summary>Earlier readings (previous dev, heads e276bef and 2c776b4)</summary> - At e276bef: components and i18n type-check exit 0; `packages/components/ packages/i18n/` Test Files 608 passed, 1 skipped; `scripts/` 172 passed, 2 skipped files. - Ablations then: cell `aria-readonly` removed, 2 red; the region's success saying removed, 2 red; the touch guard removed, 1 red. </details> ## Acceptance notes - Not done here, by the card's split: slice B (a row moving to its new group after a save, group subtotals and the footer total refreshing) follows on its own PR. - `aria-readonly` on cells other than the selected one reads the table's own facts only (`editable`, the column, `isRowEditable`); the host's per-cell facts (`describeCell`: field read-only, permission, approval lock) are asked of the selected cell alone, because the table asks `describeCell` only at the moments its TSDoc names, never for every cell. A screen reader moving cell to cell always lands on the selected cell, so the acceptance line holds; a reader browsing the table in its virtual mode hears the coarser answer on cells it does not select. - While the selected row's lock read is on the wire, the selected cell's `aria-readonly` reads the `approval_status` column (the hook's fail-open stand-in) and changes when the read answers; Enter or F2 in that window waits for the read (#36295) and says the reason. - The `ObjectGrid` memo is not pinned by a test of its own (its call count is internal to the host); the table-level pin holds the table to "never per render" for any host whose value is stable. - "A touch never edits in place" is a fact of the select-first model (`cellSelection`): there a click only selects, so `singleClickEdit` is never read, and the touch pins in `data-table-select-first-35684.test.tsx` already run with `singleClickEdit: true`. `ObjectGrid` passes `singleClickEdit: schema.singleClickEdit ?? true` on main today; #36357 (read at `579f99ae`) also edits `ObjectGrid.tsx` (`hostCellSelection = cellSelectionProp ?? inlineEditable`, `singleClickEdit: true`) and `ObjectGrid.cellSelection-35684.test.tsx`; it makes every grid that renders editable select-first, so this behaviour extends to them and no pin here flips; `node scripts/pm/overlap-check.mjs --pr=36357` on 6991954: merges cleanly, VERDICT clean. The one residual is a host passing `cellSelection={false}` explicitly (none in-tree). A grid on the older click-to-edit model (no `cellSelection`, `singleClickEdit` true) still edits on a touch tap, as it did before this PR; that model is outside this slice. - A tap that lands on a lookup cell's edit button drawn earlier for a mouse (a hybrid device) now does nothing at all rather than editing; the row's click handler ignores clicks on buttons, so the tap does not open the record either. A finger alone never draws the button. - Real screen-reader output (VoiceOver, NVDA) and a real iPad were not exercised; the pins are jsdom, and the claim about a region that mounts with its words is the general live-region behaviour, not a measurement here. - Selection frame contrast: no change needed; the readings are in What changes. ## Verification Read first (risk order): 1. `ui/packages/plugin-grid/src/ObjectGrid.tsx`, the `gridCellSelection` memo and its dependency list: a missing dependency would leave the selected cell's `aria-readonly` stale until the reader moves (act-time reads stay fresh either way). 2. `ui/packages/components/src/renderers/complex/data-table.tsx`, the `selectedHostReadOnly` layout effect and the `cellReadOnly` line in the body-cell map. 3. `ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts`, the `answerSeq` bump in the read's `finally` and on the invalidation reset. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx`, expect every test passing, among them the two in "the selected cell says a lock that answers after it was selected (objectstack#35689)". <details><summary>Local gates (targeted, derived from the diff) at 65b9199</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 42 families (19 paths vs merge base c448c61); all run, every one exit 0 (`check:query-options-erasure` re-run without the loop's 300 s cap after the first try hit it: exit 0, "ratchet holds"). `pnpm check:type-check-debt`: exit 0, "0 raw tsc error(s) total". `--ran` reconciliation: 42 derived, 42 run, 0 NOT-MEASURED, 0 UNRUN, exit 0. ui i18n gates: `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys` exit 0. `pnpm check:nul-bytes`: exit 0. `node scripts/pm/overlap-check.mjs` before each push: VERDICT clean (at 65b9199 after merging origin/main, which had conflicted on the lock hook and its test; at 6991954 against origin/main ff60149 and 10 open heads, and with `--pr=36357`). CI on 6991954: 45 success, 13 skipped, 0 failure (on 65b9199 before it: 47 success, 15 skipped), among them Lint and Repo Gates, TypeScript Type Check, Test Core, Governed Surface Queue Guard, Lint UI, Type Check UI, Test UI (16/16 shards), Build and E2E UI, Live E2E UI, Dogfood Regression Gate, Check Changeset, PR-body guards. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jUc3qp6bHKSWijbjds)_ <!-- signed: repo:objectstack#7 · zhuangjianguo · session_01QsR2jUc3qp6bHKSWijbjds --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 761220c commit 5345905

20 files changed

Lines changed: 464 additions & 15 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@object-ui/components': patch
3+
'@object-ui/i18n': patch
4+
'@object-ui/plugin-grid': patch
5+
---
6+
7+
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
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
The widening is additive: the new key `table.cellSavedAnnouncement` in every locale pack `@object-ui/i18n` publishes through `./locales`.
13+
14+
- **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.
15+
- **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.
16+
- **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.

‎ui/packages/components/src/__tests__/data-table-autosave-35685.test.tsx‎

Lines changed: 101 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
* 8. A commit the host asks to confirm (`confirmCommit`, slice S3) is held
2525
* with nothing staged: No leaves the cell as it was, Yes writes it; a
2626
* paste is asked too, an unchanged value is not.
27+
* 9. objectstack#35689: a save is said in the table's one live region,
28+
* there from the first render; a refusal is said once, by the cell's
29+
* alert. With rows checked, a cell edit writes that one cell, and the
30+
* checks stay.
2731
*/
2832
import React from 'react';
2933
import { describe, it, expect, afterEach, vi } from 'vitest';
@@ -36,6 +40,7 @@ import '../renderers';
3640
// at collection, never inside a case's clocked window (`check:test-source-alias`).
3741
import '@object-ui/react-runtime';
3842
import { GridCellSelectionProvider } from '../context/gridCellSelection';
43+
import { I18nProvider } from '@object-ui/i18n';
3944

4045
afterEach(cleanup);
4146

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

78-
function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true) {
83+
function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true, language?: string) {
7984
const DataTable = ComponentRegistry.get('data-table')!;
80-
const tree = (schema: any) => (withProvider
85+
const table = (schema: Record<string, unknown>) => (withProvider
8186
? <GridCellSelectionProvider value={{}}><DataTable schema={schema} /></GridCellSelectionProvider>
8287
: <DataTable schema={schema} />);
88+
const tree = (schema: any) => (language
89+
? <I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>{table(schema)}</I18nProvider>
90+
: table(schema));
8391
const utils = render(tree(schemaOf(onRowSave, extra)));
8492
const cell = (row: number, col: number) =>
8593
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
403411
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Alpha 2' });
404412
});
405413
});
414+
415+
describe('data-table autosave — the result is said to assistive tech (objectstack#35689)', () => {
416+
const region = (c: HTMLElement) => c.querySelector<HTMLElement>('[data-slot="cell-save-announcer"]');
417+
418+
it('a saved cell is said in the one live region; the same words again are a new saying', async () => {
419+
const { onRowSave, calls } = deferredSave();
420+
const t = renderTable(onRowSave);
421+
// There, and silent, before anything is saved.
422+
expect(region(t.container)).toHaveAttribute('aria-live', 'polite');
423+
expect(region(t.container)).toHaveClass('sr-only');
424+
expect(region(t.container)!.textContent).toBe('');
425+
t.typeAndEnter(0, 0, 'Alpha 2');
426+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
427+
// Saving is not said, and the cell's mark is no live region of its own.
428+
expect(region(t.container)!.textContent).toBe('');
429+
expect(t.cell(0, 0).querySelector('[data-slot="cell-save-state"]')).not.toHaveAttribute('role', 'status');
430+
expect(t.container.querySelectorAll('[aria-live], [role="status"], [role="alert"]')).toHaveLength(1);
431+
await act(async () => { calls[0].resolve(); });
432+
expect(region(t.container)).toHaveTextContent('Saved: Name');
433+
const first = region(t.container)!.firstElementChild;
434+
t.typeAndEnter(0, 0, 'Alpha 3');
435+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2));
436+
await act(async () => { calls[1].resolve(); });
437+
expect(region(t.container)).toHaveTextContent('Saved: Name');
438+
expect(region(t.container)!.firstElementChild).not.toBe(first);
439+
});
440+
441+
it("a refused save is said by the cell's alert alone; the region drops the words it held", async () => {
442+
const { onRowSave, calls } = deferredSave();
443+
const t = renderTable(onRowSave);
444+
t.typeAndEnter(0, 0, 'Alpha 2');
445+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
446+
await act(async () => { calls[0].resolve(); });
447+
expect(region(t.container)).toHaveTextContent('Saved: Name');
448+
t.typeAndEnter(0, 1, 'won');
449+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2));
450+
await act(async () => { calls[1].reject(fieldRefusal([{ field: 'stage', message: 'Stage cannot move to won' }])); });
451+
expect(screen.getByTestId('cell-save-failure')).toHaveAttribute('role', 'alert');
452+
expect(screen.getByTestId('cell-save-failure')).toHaveTextContent('Stage cannot move to won');
453+
expect(region(t.container)!.textContent).toBe('');
454+
});
455+
456+
it("cells saved together are named in the locale's list punctuation", async () => {
457+
const { onRowSave, calls } = deferredSave();
458+
const t = renderTable(onRowSave, {}, true, 'zh');
459+
// A refused cell stays pending and travels with the next commit on its row.
460+
t.typeAndEnter(0, 1, 'won');
461+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
462+
await act(async () => { calls[0].reject(fieldRefusal([{ field: 'stage', message: 'Stage cannot move to won' }])); });
463+
t.typeAndEnter(0, 0, 'Alpha 2');
464+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(2));
465+
expect(Object.keys(calls[1].changes)).toEqual(['stage', 'name']);
466+
await act(async () => { calls[1].resolve(); });
467+
expect(region(t.container)!.textContent).toBe('已保存:Stage、Name');
468+
});
469+
470+
it('a column with no header is not named by its key', async () => {
471+
const { onRowSave, calls } = deferredSave();
472+
const t = renderTable(onRowSave, { columns: [{ header: '', accessorKey: 'name' }] });
473+
t.typeAndEnter(0, 0, 'Alpha 2');
474+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
475+
await act(async () => { calls[0].resolve(); });
476+
expect(region(t.container)!.textContent).toBe('Saved');
477+
});
478+
479+
it('CONTROL: a table that does not save per cell draws no region', () => {
480+
const t = renderTable(vi.fn(async () => {}), {}, false);
481+
expect(region(t.container)).toBeNull();
482+
});
483+
});
484+
485+
describe('data-table autosave — checked rows and a cell edit (objectstack#35689)', () => {
486+
it('with two rows checked, a cell edit writes that one cell of that one row, and both checks stay', async () => {
487+
const onRowSave = vi.fn(async (_i: number, _changes: Record<string, unknown>, _row?: unknown) => {});
488+
const onSelectionChange = vi.fn();
489+
const t = renderTable(onRowSave, { selectable: 'multiple', onSelectionChange });
490+
const rowChecks = () => [...t.container.querySelectorAll('tbody tr')].map((tr) => tr.querySelector<HTMLElement>('[role="checkbox"]')!);
491+
fireEvent.click(rowChecks()[0]);
492+
fireEvent.click(rowChecks()[1]);
493+
expect(onSelectionChange).toHaveBeenLastCalledWith([ROWS[0], ROWS[1]]);
494+
const selectionCalls = onSelectionChange.mock.calls.length;
495+
t.typeAndEnter(1, 0, 'Beta 2');
496+
await waitFor(() => expect(onRowSave).toHaveBeenCalledTimes(1));
497+
expect(onRowSave.mock.calls[0][0]).toBe(1);
498+
expect(onRowSave.mock.calls[0][1]).toEqual({ name: 'Beta 2' });
499+
expect(t.cell(0, 0)).toHaveTextContent('Alpha');
500+
await act(async () => {});
501+
for (const check of rowChecks()) expect(check).toHaveAttribute('aria-checked', 'true');
502+
expect(onSelectionChange).toHaveBeenCalledTimes(selectionCalls);
503+
});
504+
});

‎ui/packages/components/src/__tests__/data-table-keys-35687.test.tsx‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
* panel under the cell, which keeps its value drawn; a commit the browser
2828
* or the host refuses keeps the editor and the input, says why under it,
2929
* and Escape discards.
30+
* 5. objectstack#35689: a picker's panel under the cell hands the focus back
31+
* to the cell when it closes, by Esc and by a pick.
3032
*/
3133
import React from 'react';
3234
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
431433
expect(frame(0, 0)).toBeNull();
432434
});
433435
});
436+
437+
describe('data-table select-first keys — the focus after a picker panel closes (objectstack#35689)', () => {
438+
// A picker as a host injects it: options that commit on a pick.
439+
const renderPicker = () => renderTable(
440+
{
441+
renderCellEditor: (ctx: { commit: (v?: unknown) => void }) => (
442+
<div role="group" aria-label="Pick a name">
443+
<button type="button" data-testid="pick-omega" onClick={() => ctx.commit('Omega')}>Omega</button>
444+
<button type="button" onClick={() => ctx.commit('Sigma')}>Sigma</button>
445+
</div>
446+
),
447+
},
448+
{ describeCell: (_row, key) => (key === 'name' ? { editor: 'below' } : null) },
449+
);
450+
const panel = (t: ReturnType<typeof renderTable>) => t.cell(0, 0).querySelector('[data-slot="cell-editor-overlay"]');
451+
452+
it('Esc in the panel closes it, and the focus is back on the cell, still selected', () => {
453+
const t = renderPicker();
454+
t.select(0, 0);
455+
fireEvent.keyDown(t.catcher(), { key: 'Enter' });
456+
expect(panel(t)).toHaveAttribute('data-placement', 'below');
457+
const option = t.container.querySelector<HTMLButtonElement>('[data-testid="pick-omega"]')!;
458+
option.focus();
459+
fireEvent.keyDown(option, { key: 'Escape' });
460+
expect(panel(t)).toBeNull();
461+
expect(t.selected()).toBe('0:0');
462+
expect(document.activeElement).toBe(t.catcher());
463+
expect(t.onCellChange).not.toHaveBeenCalled();
464+
});
465+
466+
it('a pick commits, closes the panel, and the focus is back on the cell', () => {
467+
const t = renderPicker();
468+
t.select(0, 0);
469+
fireEvent.keyDown(t.catcher(), { key: 'Enter' });
470+
const option = t.container.querySelector<HTMLButtonElement>('[data-testid="pick-omega"]')!;
471+
option.focus();
472+
fireEvent.click(option);
473+
expect(t.onCellChange).toHaveBeenLastCalledWith(0, 'name', 'Omega', ROWS[0]);
474+
expect(panel(t)).toBeNull();
475+
expect(t.selected()).toBe('0:0');
476+
expect(document.activeElement).toBe(t.catcher());
477+
});
478+
});

‎ui/packages/components/src/__tests__/data-table-select-first-35684.test.tsx‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@
3434
* chip; the cell draws an edit button, not the open button, and the edit
3535
* button opens the editor through the same gate as double-click
3636
* (objectstack#36015).
37+
* 9. objectstack#35689: a touch tap or double-tap never edits in place, the
38+
* edit button included; in the grid a read-only cell carries
39+
* `aria-readonly`, on the cell and on the focus inside it.
3740
*/
3841
import React from 'react';
3942
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
504507
expect(t.editButton(0, 1)).toBeNull();
505508
});
506509
});
510+
511+
describe('data-table select-first — a touch never edits in place (objectstack#35689)', () => {
512+
it('a touch tap opens the record; a touch double-tap neither selects nor edits', () => {
513+
const t = renderTable();
514+
fireEvent.pointerDown(t.cell(0, 1), { pointerType: 'touch' });
515+
fireEvent.click(t.cell(0, 1), { detail: 1 });
516+
fireEvent.pointerDown(t.cell(0, 1), { pointerType: 'touch' });
517+
fireEvent.click(t.cell(0, 1), { detail: 2 });
518+
fireEvent.doubleClick(t.cell(0, 1));
519+
expect(t.onRowClick).toHaveBeenCalled();
520+
expect(t.editor()).toBeNull();
521+
expect(t.cell(0, 1)).not.toHaveAttribute('data-selected-cell');
522+
expect(t.onCellChange).not.toHaveBeenCalled();
523+
});
524+
525+
it("a tap on a reference cell's edit button, on a cell not selected, edits nothing; a mouse click on it edits", () => {
526+
const openRecord = vi.fn();
527+
const t = renderTable({ selection: { referenceCells: { isReferenceColumn: (key) => key === 'site', openRecord } } });
528+
const button = () => t.cell(0, 3).querySelector<HTMLButtonElement>('[data-testid="cell-edit-button"]')!;
529+
// A finger reaching the cell does not draw the button.
530+
fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'touch' });
531+
expect(button().className).toContain('hidden');
532+
// Drawn for a mouse before, a tap on it is still not an edit.
533+
fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'mouse' });
534+
expect(button().className).toMatch(/(^|\s)flex(\s|$)/);
535+
fireEvent.pointerDown(button(), { pointerType: 'touch' });
536+
fireEvent.click(button());
537+
expect(t.editor()).toBeNull();
538+
expect(t.cell(0, 3)).not.toHaveAttribute('data-selected-cell');
539+
// CONTROL: the mouse's click on the same button edits.
540+
fireEvent.pointerDown(button(), { pointerType: 'mouse' });
541+
fireEvent.click(button());
542+
expect(t.editor()).not.toBeNull();
543+
});
544+
});
545+
546+
describe('data-table select-first — a touch press is read by its own click only (objectstack#35689)', () => {
547+
it('after a tap on the edit button, a click with no pointer of its own (assistive tech) edits', () => {
548+
const t = renderTable({ selection: { referenceCells: { isReferenceColumn: (key) => key === 'site', openRecord: vi.fn() } } });
549+
const button = () => t.cell(0, 3).querySelector<HTMLButtonElement>('[data-testid="cell-edit-button"]')!;
550+
fireEvent.pointerEnter(t.cell(0, 3), { pointerType: 'mouse' });
551+
fireEvent.pointerDown(button(), { pointerType: 'touch' });
552+
fireEvent.click(button());
553+
expect(t.editor()).toBeNull();
554+
fireEvent.click(button());
555+
expect(t.editor()).not.toBeNull();
556+
});
557+
});
558+
559+
describe('data-table select-first — a read-only cell says so in the grid (objectstack#35689)', () => {
560+
it("the selected cell reads the host's facts: aria-readonly on the cell and on its focus; an editable one carries none", () => {
561+
const t = renderTable({
562+
selection: { describeCell: (_row, key) => (key === 'amount' ? { readOnlyReason: 'This value is calculated.' } : null) },
563+
});
564+
expect(t.container.querySelector('table')).toHaveAttribute('role', 'grid');
565+
fireEvent.click(t.cell(0, 1));
566+
expect(t.cell(0, 1)).toHaveAttribute('aria-readonly', 'true');
567+
expect(t.catcher()).toHaveAttribute('aria-readonly', 'true');
568+
expect(document.activeElement).toBe(t.catcher());
569+
fireEvent.keyDown(t.catcher()!, { key: 'ArrowLeft' });
570+
expect(t.cell(0, 0)).not.toHaveAttribute('aria-readonly');
571+
expect(t.catcher()).not.toHaveAttribute('aria-readonly');
572+
});
573+
574+
it("the host's facts are asked as the cell becomes selected, never per render; a new host value is asked again", () => {
575+
const DataTable = ComponentRegistry.get('data-table')!;
576+
let locked = false;
577+
const describeCell = vi.fn((_row: unknown, key: string) => (key === 'amount' && locked ? { readOnlyReason: 'Locked.' } : null));
578+
const schemaOf = () => ({
579+
type: 'data-table',
580+
columns: [{ header: 'Name', accessorKey: 'name' }, { header: 'Amount', accessorKey: 'amount', type: 'number' }],
581+
data: ROWS,
582+
editable: true,
583+
searchable: false,
584+
pagination: false,
585+
});
586+
const Host = ({ value, schema }: { value: GridCellSelection; schema: Record<string, unknown> }) => (
587+
<GridCellSelectionProvider value={value}><DataTable schema={schema} /></GridCellSelectionProvider>
588+
);
589+
const value = { describeCell };
590+
const utils = render(<Host value={value} schema={schemaOf()} />);
591+
const amount = () => utils.container.querySelectorAll('tbody tr')[0].querySelectorAll('td[data-grid-cell]')[1];
592+
fireEvent.click(amount());
593+
expect(amount()).toHaveAttribute('data-selected-cell');
594+
expect(amount()).not.toHaveAttribute('aria-readonly');
595+
const asked = describeCell.mock.calls.length;
596+
expect(asked).toBeGreaterThan(0);
597+
// The table renders again, three times, with nothing the answer reads changed.
598+
for (let i = 0; i < 3; i++) utils.rerender(<Host value={value} schema={schemaOf()} />);
599+
expect(describeCell).toHaveBeenCalledTimes(asked);
600+
// The host's answer changed and it hands a new value: the cell says so
601+
// where it is, without the reader moving.
602+
locked = true;
603+
utils.rerender(<Host value={{ describeCell }} schema={schemaOf()} />);
604+
expect(amount()).toHaveAttribute('data-selected-cell');
605+
expect(amount()).toHaveAttribute('aria-readonly', 'true');
606+
expect(utils.container.querySelector('[data-slot="cell-type-catcher"]')).toHaveAttribute('aria-readonly', 'true');
607+
});
608+
609+
it("every cell of a table that edits nothing is read-only, by the table's own facts", () => {
610+
const t = renderTable({ extra: { editable: false } });
611+
const cells = [...t.container.querySelectorAll('td[data-grid-cell]')];
612+
expect(cells.length).toBe(ROWS.length * 4);
613+
for (const td of cells) expect(td).toHaveAttribute('aria-readonly', 'true');
614+
});
615+
616+
it('CONTROL: outside the grid no cell carries aria-readonly', () => {
617+
const t = renderTable({ selection: null, extra: { editable: false } });
618+
expect(t.container.querySelector('table')).not.toHaveAttribute('role');
619+
expect(t.container.querySelector('[aria-readonly]')).toBeNull();
620+
});
621+
});

‎ui/packages/components/src/context/gridCellSelection.tsx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,15 @@ export interface GridReferenceCells {
109109
}
110110

111111
export interface GridCellSelection {
112-
/** The host's facts for one cell; asked when the reader acts on it, never per render. */
112+
/**
113+
* The host's facts for one cell. The table asks for them when the reader
114+
* acts on a cell (an edit, a key, a paste), and for the selected cell's
115+
* `aria-readonly` (objectstack#35689): once as the cell becomes selected,
116+
* and again when its row is re-read or the provider's value is a new
117+
* object. The value's identity is part of this contract: keep it stable
118+
* across renders (memoise it) and hand a new one only when an answer may
119+
* have changed, or the selected cell is asked on every render.
120+
*/
113121
describeCell?: (row: any, columnKey: string) => GridCellFacts | null | undefined;
114122
/** Called when a cell becomes the selected one (a host may prefetch what an edit will need). */
115123
onCellSelect?: (row: any, columnKey: string) => void;

0 commit comments

Comments
 (0)