Skip to content

Commit 1733276

Browse files
committed
wip(grid): ask the selected cell's host facts at selection, re-render on a lock answer (#35689)
Claude-Session: https://claude.ai/code/session_01QsR2jUc3qp6bHKSWijbjds Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2c776b4 commit 1733276

6 files changed

Lines changed: 195 additions & 24 deletions

File tree

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

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import '../renderers';
4040
// at collection, never inside a case's clocked window (`check:test-source-alias`).
4141
import '@object-ui/react-runtime';
4242
import { GridCellSelectionProvider } from '../context/gridCellSelection';
43+
import { I18nProvider } from '@object-ui/i18n';
4344

4445
afterEach(cleanup);
4546

@@ -79,11 +80,14 @@ function schemaOf(onRowSave: Save, extra: Record<string, unknown> = {}) {
7980
};
8081
}
8182

82-
function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true) {
83+
function renderTable(onRowSave: Save, extra: Record<string, unknown> = {}, withProvider = true, language?: string) {
8384
const DataTable = ComponentRegistry.get('data-table')!;
84-
const tree = (schema: any) => (withProvider
85+
const table = (schema: any) => (withProvider
8586
? <GridCellSelectionProvider value={{}}><DataTable schema={schema} /></GridCellSelectionProvider>
8687
: <DataTable schema={schema} />);
88+
const tree = (schema: any) => (language
89+
? <I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>{table(schema)}</I18nProvider>
90+
: table(schema));
8791
const utils = render(tree(schemaOf(onRowSave, extra)));
8892
const cell = (row: number, col: number) =>
8993
utils.container.querySelectorAll('tbody tr')[row].querySelectorAll('td[data-grid-cell]')[col] as HTMLElement;
@@ -449,6 +453,29 @@ describe('data-table autosave — the result is said to assistive tech (objectst
449453
expect(region(t.container)!.textContent).toBe('');
450454
});
451455

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+
452479
it('CONTROL: a table that does not save per cell draws no region', () => {
453480
const t = renderTable(vi.fn(async () => {}), {}, false);
454481
expect(region(t.container)).toBeNull();

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

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -543,6 +543,19 @@ describe('data-table select-first — a touch never edits in place (objectstack#
543543
});
544544
});
545545

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+
546559
describe('data-table select-first — a read-only cell says so in the grid (objectstack#35689)', () => {
547560
it("the selected cell reads the host's facts: aria-readonly on the cell and on its focus; an editable one carries none", () => {
548561
const t = renderTable({
@@ -558,6 +571,41 @@ describe('data-table select-first — a read-only cell says so in the grid (obje
558571
expect(t.catcher()).not.toHaveAttribute('aria-readonly');
559572
});
560573

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+
561609
it("every cell of a table that edits nothing is read-only, by the table's own facts", () => {
562610
const t = renderTable({ extra: { editable: false } });
563611
const cells = [...t.container.querySelectorAll('td[data-grid-cell]')];

‎ui/packages/components/src/renderers/complex/data-table.tsx‎

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,9 @@ const TABLE_DEFAULT_TRANSLATIONS: Record<string, string> = {
376376
'table.cellSaved': 'Saved',
377377
// objectstack#35689 — what the table's live region says when cells saved.
378378
'table.cellSavedAnnouncement': 'Saved: {{fields}}',
379+
// The pack's list punctuation the announcement joins column names with
380+
// (`、` in ja and zh), the key the form's field lists use.
381+
'validation.formInvalidJoiner': ', ',
379382
'table.openRecordToFinish': 'Open the record to finish this change',
380383
'common.actions': 'Actions',
381384
// objectui#10625 — the inline date editors' notice for a stored value
@@ -1491,9 +1494,10 @@ function CellEditButton({
14911494
editableRef.current = editable;
14921495
const selectedRef = useRef(selected);
14931496
selectedRef.current = selected;
1494-
// objectstack#35689 — the pointer that pressed the button last. A touch never
1495-
// selects the cell, so on a cell not selected the button is never drawn for
1496-
// it, and one it lands on anyway (drawn for a mouse before) edits nothing.
1497+
// objectstack#35689 — the pointer that pressed the button for the click that
1498+
// follows, cleared by that click. A touch never selects the cell, so on a
1499+
// cell not selected the button is never drawn for it, and one it lands on
1500+
// anyway (drawn for a mouse before) edits nothing.
14971501
const pressedByRef = useRef('');
14981502
const [allowed, setAllowed] = useState(false);
14991503
useLayoutEffect(() => {
@@ -1524,9 +1528,14 @@ function CellEditButton({
15241528
onMouseDown={(e) => e.preventDefault()}
15251529
onDoubleClick={(e) => e.stopPropagation()}
15261530
onClick={(e) => {
1527-
// objectstack#35689 — a tap on an unselected cell is the row's: it opens
1528-
// the record and edits nothing in place, wherever on the cell it lands.
1529-
const pointer = (e.nativeEvent as PointerEvent).pointerType || pressedByRef.current;
1531+
// objectstack#35689 — a tap on an unselected cell edits nothing in
1532+
// place. On the button it does nothing at all: the row's click ignores
1533+
// a click on a button, so the tap opens no record either (a tap beside
1534+
// the button opens it). The press is read once: a later click with no
1535+
// pointer of its own (assistive tech) is not taken for this touch.
1536+
const pressedBy = pressedByRef.current;
1537+
pressedByRef.current = '';
1538+
const pointer = (e.nativeEvent as PointerEvent).pointerType || pressedBy;
15301539
if (!selected && pointer === 'touch') return;
15311540
e.stopPropagation();
15321541
onEdit();
@@ -3438,11 +3447,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
34383447
});
34393448
setFailureNotice((prev) => (prev?.rowKey === rowKey ? null : prev));
34403449
flashSaved(rowKey, sentKeys);
3441-
const fields = sentKeys.map((key) => {
3450+
// Each saved cell by its column's header, in the locale's list
3451+
// punctuation; a column with no header is never named by its key.
3452+
const fields = sentKeys.flatMap((key) => {
34423453
const header = columns.find((c) => c.accessorKey === key)?.header;
3443-
return typeof header === 'string' && header !== '' ? header : key;
3454+
return typeof header === 'string' && header !== '' ? [header] : [];
34443455
});
3445-
setSaveAnnouncement((prev) => ({ seq: prev.seq + 1, text: t('table.cellSavedAnnouncement', { fields: fields.join(', ') }) }));
3456+
const said = fields.length > 0
3457+
? t('table.cellSavedAnnouncement', { fields: fields.join(t('validation.formInvalidJoiner')) })
3458+
: t('table.cellSaved');
3459+
setSaveAnnouncement((prev) => ({ seq: prev.seq + 1, text: said }));
34463460
} catch (error) {
34473461
// The edits stay pending and the cells keep what was typed. Each cell the
34483462
// refusal names shows its own reason; a cell it does not name shows them
@@ -3715,6 +3729,22 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
37153729
const selectedPos = selectedRowIndex >= 0 && selectedColIndex >= 0
37163730
? { rowIndex: selectedRowIndex, colIndex: selectedColIndex }
37173731
: null;
3732+
// objectstack#35689 — whether the host holds the selected cell read-only
3733+
// (`GridCellSelection.describeCell`), for its `aria-readonly`. Asked as a
3734+
// cell becomes selected, and again only when what the answer reads changes:
3735+
// the row is re-read, or the host hands the grid a new value (an answer it
3736+
// was waiting on arrived). Never asked per render; every render reads this.
3737+
const selectedRow = selectedPos ? paginatedData[selectedPos.rowIndex] : undefined;
3738+
const selectedColumnKey = selectedPos ? columns[selectedPos.colIndex].accessorKey : undefined;
3739+
const [selectedHostReadOnly, setSelectedHostReadOnly] = useState<{ row: any; columnKey: string } | null>(null);
3740+
useLayoutEffect(() => {
3741+
const readOnly = selectedRow !== undefined && selectedColumnKey !== undefined
3742+
&& !!cellSelection?.describeCell?.(selectedRow, selectedColumnKey)?.readOnlyReason;
3743+
setSelectedHostReadOnly((prev) => {
3744+
if (!readOnly) return null;
3745+
return prev?.row === selectedRow && prev.columnKey === selectedColumnKey ? prev : { row: selectedRow, columnKey: selectedColumnKey! };
3746+
});
3747+
}, [selectedRow, selectedColumnKey, cellSelection]);
37183748
const setSelectedCell = (pos: { rowIndex: number; colIndex: number } | null) =>
37193749
setSelectedCellKey(pos ? { rowKey: pendingRowKeyOf(paginatedData[pos.rowIndex]), columnKey: columns[pos.colIndex].accessorKey } : null);
37203750
// objectstack#35688 — a selected cell whose content is cut off shows it in
@@ -5184,11 +5214,12 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => {
51845214
const isSelectedCell = selectFirst && selectedPos?.rowIndex === rowIndex && selectedPos.colIndex === colIndex;
51855215
const showsPreview = isSelectedCell && !isEditing && previewKey === `${rowIndex}:${colIndex}`;
51865216
// objectstack#35689 — a read-only cell says so to assistive tech, in the
5187-
// grid only. The host's facts are asked of the selected cell alone (the
5188-
// `describeCell` contract: never per render); the cell a reader moves to
5189-
// is the selected one, and every other cell reads the table's own facts.
5217+
// grid only, from the table's own facts. The selected cell (the one a
5218+
// reader moves to) adds the host's, asked when it became selected
5219+
// (`selectedHostReadOnly`: `describeCell` is never asked per render).
51905220
const cellReadOnly = keyboardNavigation
5191-
&& (isSelectedCell ? readOnlyReasonOf(row, col) !== null : !isEditable);
5221+
&& (!isEditable || (isSelectedCell && selectedHostReadOnly?.row === row
5222+
&& selectedHostReadOnly.columnKey === col.accessorKey));
51925223
// What the cell draws; the preview layer draws the same, unclipped.
51935224
const drawCell = (): React.ReactNode => (typeof col.cell === 'function'
51945225
? col.cell(cellValue, row)

‎ui/packages/plugin-grid/src/ObjectGrid.tsx‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,17 +1371,31 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
13711371
}
13721372
: undefined,
13731373
});
1374-
const gridCellSelection: GridCellSelection | null = hostCellSelection
1374+
// objectstack#35689 — the value is new only when what `describeCell`
1375+
// answers from changed (the object, its fields, the reader's permissions,
1376+
// a verdict or an approval lock landing, the language): the table asks the
1377+
// selected cell's facts again on a new value, so one new on every render
1378+
// would ask on every render. The commit question and the chip opener read
1379+
// what this render holds through `latestCellHooks`.
1380+
const gridEditable = schema.editable ?? false;
1381+
const latestCellHooks = React.useRef({ requiredPrompt, askStateMove, openReferencedRecord });
1382+
latestCellHooks.current = { requiredPrompt, askStateMove, openReferencedRecord };
1383+
const opensReferencedRecords = !!openReferencedRecord;
1384+
const gridCellSelection = useMemo((): GridCellSelection | null => (hostCellSelection
13751385
? {
13761386
describeCell: (row, columnKey) => {
13771387
const fieldDef = objectFields?.[columnKey];
13781388
const recordId = rowRecordId(row);
13791389
const kind = cellReadOnlyKind({
13801390
fieldDef,
13811391
fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey),
1382-
gridEditable: schema.editable ?? false,
1392+
gridEditable,
13831393
objectEditable: objectInlineEditable,
1384-
canUpdate: resolveAffordanceGrant('listInlineEdit', affordanceSource),
1394+
canUpdate: resolveAffordanceGrant('listInlineEdit', {
1395+
objectSchema: objectSchema as SchemaLike | null | undefined,
1396+
objectName,
1397+
perms,
1398+
}),
13851399
approvalLocked: approvalLocks.isLocked(recordId, row),
13861400
recordUpdate: recordVerdict(recordId, 'update'),
13871401
});
@@ -1409,19 +1423,25 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
14091423
// before anything is written (`./objectGridStateConfirm`). A move that
14101424
// needs fields filled asks for them first; that dialog is the
14111425
// confirmation, so a state-machine move does not ask twice.
1412-
confirmCommit: (row, columnKey, value) =>
1413-
requiredPrompt.ask(row, columnKey, value, () => askStateMove(row, columnKey, value)),
1426+
confirmCommit: (row, columnKey, value) => {
1427+
const { requiredPrompt: prompt, askStateMove: askMove } = latestCellHooks.current;
1428+
return prompt.ask(row, columnKey, value, () => askMove(row, columnKey, value));
1429+
},
14141430
// objectstack#36015 — a lookup cell's chip opens its record in place.
1415-
...(openReferencedRecord
1431+
...(opensReferencedRecords
14161432
? {
14171433
referenceCells: {
14181434
isReferenceColumn: (columnKey: string) => opensReferenceInPlace(objectFields?.[columnKey]),
1419-
openRecord: openReferencedRecord,
1435+
openRecord: (target: string, recordId: string) =>
1436+
latestCellHooks.current.openReferencedRecord?.(target, recordId),
14201437
},
14211438
}
14221439
: {}),
14231440
}
1424-
: null;
1441+
: null), [
1442+
hostCellSelection, opensReferencedRecords, objectFields, objectSchema, objectName, perms,
1443+
gridEditable, objectInlineEditable, approvalLocks, recordVerdict, t,
1444+
]);
14251445
// objectstack#35685 — the state-machine confirm, the grid's next question
14261446
// when the required-fields prompt has nothing to ask.
14271447
function askStateMove(row: any, columnKey: string, value: unknown): Promise<boolean> | null {

‎ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,19 +74,23 @@ const FIELDS = {
7474
let lockedIds = new Set<string>();
7575
let lockStatus = 200;
7676
let lockReads: string[] = [];
77+
// While set, a lock read answers only once it settles (objectstack#35689).
78+
let lockGate: Promise<void> | null = null;
7779

7880
beforeEach(() => {
7981
__clearRecordCrudVerdictCache();
8082
__resetApprovalsServiceLatch();
8183
lockedIds = new Set();
8284
lockStatus = 200;
8385
lockReads = [];
86+
lockGate = null;
8487
// The explain engine permits every row; the approvals service answers the lock.
8588
vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => {
8689
const href = String(url);
8790
const lock = /\/api\/v1\/approvals\/records\/probe\/([^/]+)\/lock$/.exec(href);
8891
if (lock) {
8992
lockReads.push(decodeURIComponent(lock[1]));
93+
if (lockGate) await lockGate;
9094
return { ok: lockStatus < 300, status: lockStatus, json: async () => ({ success: true, data: { locked: lockedIds.has(lock[1]) } }) };
9195
}
9296
const body = init?.body ? JSON.parse(String(init.body)) : {};
@@ -200,6 +204,33 @@ describe('ObjectGrid cellSelection — why a cell opens no editor', () => {
200204
});
201205
});
202206

207+
describe('ObjectGrid cellSelection — the selected cell says a lock that answers after it was selected (objectstack#35689)', () => {
208+
it('aria-readonly follows the lock answer where the selection is, both ways', async () => {
209+
lockedIds = new Set(['3']);
210+
let answer!: () => void;
211+
lockGate = new Promise<void>((resolve) => { answer = resolve; });
212+
const g = await renderGrid();
213+
const catcher = () => g.container.querySelector('[data-slot="cell-type-catcher"]');
214+
// Gamma: no approval_status, so editable until the service answers locked.
215+
fireEvent.click(g.cell(2, 0));
216+
await waitFor(() => expect(lockReads).toEqual(['3']));
217+
expect(g.cell(2, 0)).not.toHaveAttribute('aria-readonly');
218+
answer();
219+
await waitFor(() => expect(g.cell(2, 0)).toHaveAttribute('aria-readonly', 'true'));
220+
expect(catcher()).toHaveAttribute('aria-readonly', 'true');
221+
expect(g.cell(2, 0)).toHaveAttribute('data-selected-cell');
222+
// Beta: its approval_status stands in as locked until the service says it is not.
223+
lockGate = new Promise<void>((resolve) => { answer = resolve; });
224+
fireEvent.click(g.cell(1, 0));
225+
await waitFor(() => expect(lockReads).toEqual(['3', '2']));
226+
expect(g.cell(1, 0)).toHaveAttribute('aria-readonly', 'true');
227+
answer();
228+
await waitFor(() => expect(g.cell(1, 0)).not.toHaveAttribute('aria-readonly'));
229+
expect(catcher()).not.toHaveAttribute('aria-readonly');
230+
expect(g.cell(1, 0)).toHaveAttribute('data-selected-cell');
231+
});
232+
});
233+
203234
describe('ObjectGrid cellSelection — a click on a link a cell draws only selects (objectstack#36015)', () => {
204235
const opened: Array<[string, string | number]> = [];
205236
const host: RelatedRecordActionsValue = {

0 commit comments

Comments
 (0)