Skip to content

Commit 6cfd04d

Browse files
fix(plugin-grid): row menu hides Edit on a row held by a locking approval (#37128)
Fixes #36911 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户在列表页和记录页的关联页签里,对正在审批且被锁定的记录打开行菜单时,不再看到「编辑」,「删除」照旧保留。 - 属于记录页关联列表体验的修补,替用户省掉「点了编辑才被告知已锁定」这一步。 - 出错的话,最坏是锁定行的「编辑」仍然出现,点了会和以前一样弹出拒绝提示;改动可以直接撤回。 - 无 ## What changes The grid's row menu (`@object-ui/plugin-grid`) now follows the approval lock the grid's select-first cells already read. Both the list page and a record page's related tab (the related list's enlarged face, which renders `object-grid`) draw this menu, so both change together. - **The read.** It reuses the existing `useRowApprovalLocks` hook (`POST /api/v1/approvals/records/:object/locks`), which is not exported, and its rule `resolveApprovalLock`. Nothing is copied. The read is made once for the rows on screen, when a row's actions are first reached for: the existing `onActionsDemand` channel (pointer or focus on the actions cell, the "⋮" opening, the row context menu, the page bar's single-row menu). It is never made on first paint (the objectstack#35795 posture). The hook now also runs on a grid whose rows offer Edit, not only on a select-first grid. It still reads nothing until it is asked. - **The verdict.** A row whose lock read answered `locked: true` offers no Edit. That matches the record page, which draws no Edit on an approval-locked record (objectstack#35593). Delete stays for a record held by its own approval, because the server lets such a record be deleted and cancels its request (#13568). The batch read answers only for that case. A line held because its master is held refuses delete too, so if #37041 makes the read report such lines, the read must tell the two apart before this menu uses it. - **Hidden, not disabled.** Hidden follows the record page (objectstack#35593) and the row menu's own record-verdict posture (#4296). The disabled-with-reason alternative was not taken. - **Only an answered lock counts.** The row is handed to the hook without its `approval_status` column, so the column does not stand in for a read. In each of these cases the menu stays as it was: a 501 (no approvals service), a `null` entry (a row the reader cannot read), a failed read, or a read not yet asked. The select-first cells keep their column fallback unchanged. Files: `ui/packages/plugin-grid/src/ObjectGrid.tsx` (hook gate and `demandRowActions`), `ui/packages/plugin-grid/src/objectGridActionsColumn.tsx` (Edit verdict and demand wiring), and the new test `ui/packages/plugin-grid/src/__tests__/rowMenuApprovalLock-36911.test.tsx`. `RowActionMenu.tsx` and `useRowApprovalLocks.ts` are unchanged. ### The reading this card asked for (served state) Tree: objectstack-ai/objectstack at 8e4ac50 (re-read at 1e96009). - **Declared per-row predicates** (`userActions.edit` / `delete` `visibleWhen` / `disabledWhen`): already served, and already followed by both related-list faces. - **The master's approval lock on its master-detail lines:** already followed. The record page withholds New, Edit and Delete on those lists (`withDetailWritesWithheld`, objectstack#35599 ruling A). - **The row's own approval lock:** served by the batch door. Before this PR the list page's row menu read none of it; the lock reached only the cells. This PR makes the row menu follow it. - **Package-hook refusals** (the HotCRM measured case): nothing serves them. The seat ruled for no Feature card. An app that wants the row menu to know declares the rule on the child object's `userActions` predicates. The toast from #36885 covers refusals after the fact. ## Tests - New file `rowMenuApprovalLock-36911.test.tsx`, 7 pins. Five come from the first round: a locked row offers no Edit and keeps Delete, while its unlocked sibling keeps Edit; no lock read before a row's actions are reached for, then one read for the page and none on repeat; a 501 over an `approval_status: pending` row leaves the menu as it was; a `null` entry leaves Edit; a failed or not-yet-asked read leaves Edit. Two were added in fix round 1. **List page:** on the list page, a row's actions come from the single-row selection bar (`SelectionBar.tsx`), not a ⋮ column. With the locked row selected, the bar offers no Edit and still offers Delete; with its unlocked sibling selected, the bar offers Edit, which is the control. The bar already read the lock before this round, because it resolves its actions from the same `rowActionMenuProps` and asks through the same `onActionsDemand` on mount. No wiring was added; only the pin is new. **Read in flight:** the lock answer is held, the ⋮ menu is opened and Edit shows; the answer is released and Edit leaves the open menu while Delete stays. Result at 4c64a0a: 7/7 passed. - Ablation, run once and not kept: `canEdit && rowOps?.update !== false && !approvalLockAnswered(row),` was replaced by `canEdit && rowOps?.update !== false,` through `scripts/ablation-replace.mjs`. The mutation was confirmed on disk (anchor count 1 to 0, blob 2c0f37e to dc3f8dc5). The first pin turned red as predicted (Tests 1 failed, 4 passed). After the restore, the blob matched HEAD and `git diff HEAD` was empty. In fix round 1, the same ablation was run at 4c64a0a (blob c420482 to 2f180f3e) and turned 3 pins red: the ⋮ pin, the list-page bar pin and the in-flight pin (Tests 3 failed, 4 passed; the bar pin received `{ edit: true, delete: true }`). A second ablation changed `approvalLocks.isLocked(rowRecordId(row), null)` to `approvalLocks.isLocked(rowRecordId(row), row)`, which lets the `approval_status` column stand in (blob c420482 to be48f357). It turned the 501-over-pending-column pin red (Tests 1 failed, 6 passed; received `{ edit: false, delete: true }`). Both restores were confirmed: blob == HEAD and `git diff HEAD` empty. - Stale fixtures fixed in this PR. Two existing explain-engine fakes (`rowRecordCrudVerdict.test.tsx`, `inlineEditRecordVerdict-27365.test.tsx`) answered every URL as the explain engine. Once reaching a row's actions also read the lock door, they counted that read as an explain call: 19 tests red on the first full run. Each fake now answers the lock door "unlocked" and leaves it out of its call count. Their assertions are unchanged. Fix round 1 readings, at head `4c64a0a1`: the full plugin-grid suite gave `Test Files 312 passed (312) · Tests 2773 passed (2773)`, VERDICT command-exit 0. `pnpm --dir ui exec vitest run scripts/` gave 172 passed and 2 skipped files, 5130 passed and 2 skipped tests, exit 0. The 39 derived gate families all exited 0. One of them, `check:type-check-debt`, first hit a queue timeout (exit 3, not measured) and then exited 0 on a re-run. Reconciliation with `--ran` gave 39 derived, 39 run, 0 NOT-MEASURED. overlap-check exited 0 and merges cleanly with origin/main and with #37084. The readings below are from the first round, at head `d4f56f4a` (which includes a merge of `origin/main` at 9d70768), unless a line says otherwise. <details><summary>Full plugin-grid suite: 312/312 files, 2771/2771 tests</summary> `cd ui && pnpm exec vitest run --maxWorkers=2 packages/plugin-grid/` under os-verify-lock: `Test Files 312 passed (312) · Tests 2771 passed (2771)`, VERDICT command-exit 0. The earlier run before the fixture fix, at 2f9deb3, was `2 failed | 310 passed` files, with the 19 tests named above. </details> <details><summary>Type-check and the ui scripts suite</summary> - `pnpm exec turbo run type-check --concurrency=2 --filter=@object-ui/plugin-grid` at abbeea2: 54/54 tasks, plugin-grid a cache miss (`tsc --noEmit && tsc -p tsconfig.test.json`), VERDICT command-exit 0. `tsc --listFilesOnly` confirms that `tsconfig.test.json` compiles all three changed test files. - At d4f56f4: `pnpm run type-check` in `ui/packages/plugin-grid`, exit 0. Declared narrowing: this ran without the lock, because the lock was held by a dogfood run past two 540-second budgets and `tsc --noEmit` writes nothing. The dependency type-checks are left to CI. - After building the seven `@objectstack` packages as Test UI does: `pnpm --dir ui exec vitest run --maxWorkers=2 scripts/` gave `Test Files 172 passed | 2 skipped (174) · Tests 5130 passed | 2 skipped`, VERDICT command-exit 0. </details> <details><summary>Derived gate families: 39 of 39 exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands` on this diff derived 39 commands, and every one exited 0 at d4f56f4. `pnpm check:changeset-fixed` was also run (exit 0), because its roster sits under `.changeset`. Reconciliation with `--ran` gave: `39 derived, 39 run, 0 NOT-MEASURED, 0 UNRUN (a DERIVED zero — all 39 recorded an exit code)`. `pnpm check:type-check-debt` exited 3 once on the first pass, at 2f9deb3, and was not measured then; both of its later runs exited 0. </details> <details><summary>overlap-check before each push</summary> Every run exited 0. The last one, at d4f56f4: `merges cleanly` with origin/main 9d70768, with #37084, and with #37079 (both also edit `ObjectGrid.tsx`). </details> ## Acceptance notes - **Not covered: the compact related-list face and the phone gallery.** The compact face is the `components` data-table (`DataTableBuiltinRowActionItem`). Neither can reach the grid's lock hook without a new dependency or export. No card is filed for this, per the seat's ruling. On those surfaces Edit on a locked row stays until it is refused, and the #36885 toast explains the refusal. - **Detail lines read "not locked".** The batch lock door reports detail lines of a locked master as not locked until #37041 lands. Its single-record sibling reports them as locked. On a record page those lines are already withheld (objectstack#35599), but on a detail object's own list page their Edit stays until #37041. - **Edit is not held inert while the read is on the wire.** A click that lands before the answer opens the form as before, and the server's refusal is shown by the existing toast. The in-flight pin above fixes this behaviour. - **Note only: every row locked.** When every row on screen is locked and Delete is not offered (a predicate or a grant withholds it), the ⋮ column is not drawn. The record-grained verdict already behaves this way. - **Deliberate: 501 with a pending column.** On a 501, a row whose `approval_status` column reads pending is read-only in its cells (the cells use the column fallback), while its menu still offers Edit (the menu uses answered locks only). - **Possible follow-up, inherited: stale answers.** Lock answers can go stale while the grid stays mounted. The hook drops them only when the object's data is invalidated. - **Pre-existing: other edit paths.** Staged click-to-edit and the bulk Change owner action do not read the lock. ## Verification Read first (riskiest first): 1. `ui/packages/plugin-grid/src/objectGridActionsColumn.tsx`: `approvalLockAnswered` and the `canEdit` expression in `rowCrudVerdicts`, the one verdict both the column's draw decision and every menu read. 2. `ui/packages/plugin-grid/src/ObjectGrid.tsx`: the `useRowApprovalLocks` gate and `demandRowActions`, which together decide when the read is made. 3. `ui/packages/plugin-grid/src/__tests__/rowMenuApprovalLock-36911.test.tsx`. Two-minute check: `cd ui && pnpm exec vitest run packages/plugin-grid/src/__tests__/rowMenuApprovalLock-36911.test.tsx`. Expect 7 passed. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYmRepQK9DkZeU7F53D --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent e45265e commit 6cfd04d

6 files changed

Lines changed: 412 additions & 7 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/plugin-grid': patch
3+
---
4+
5+
fix(plugin-grid): the row menu offers no Edit on a row held by a locking approval
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A grid row whose record is held by its own pending approval with `lockRecord: true` is refused `RECORD_LOCKED` when it is updated. Its row menu still offered Edit, on the list page and on a record page's related tab. The menu now reads the same lock the grid's cells read (`POST /api/v1/approvals/records/:object/locks`), once per page, when a row's actions are first reached for. A row the lock read answered as locked offers no Edit, as the record page offers none. Delete stays, because a record held by its own approval may be deleted, and the delete cancels the request. The lock read does not report a detail line held because its master is held, so such lines keep both Edit and Delete in this menu, and the server refuses both. When the lock cannot be read, the menu stays as it was: no approvals service (501), a row the reader cannot read, a failed read, or a read not yet asked.

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

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1485,7 +1485,29 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
14851485
// object, an approval lock, the record — `cellReadOnlyKind`), what typing
14861486
// does there and what pasted text stands for. `null` without the host's
14871487
// ask, so every other grid keeps the table it had.
1488-
const approvalLocks = useRowApprovalLocks(hostCellSelection ? objectName : undefined);
1488+
//
1489+
// objectstack#36911 — the row menu reads the same locks: a row an approval
1490+
// locks offers no Edit, as the record page offers none (objectstack#35593).
1491+
// Delete stays for a record held by its own approval: the server deletes it
1492+
// and cancels its request. (The batch read reports only that case today, not
1493+
// a line held because its master is held, which refuses delete too; #37041.) So the hook also runs on a grid whose rows offer Edit. It still
1494+
// reads nothing until it is asked: by a cell being selected, or by a row's
1495+
// actions being reached for (`demandRowActions` below).
1496+
const rowMenuOffersEdit = canEdit && !!onEdit;
1497+
const approvalLocks = useRowApprovalLocks(hostCellSelection || rowMenuOffersEdit ? objectName : undefined);
1498+
/**
1499+
* objectstack#36911 — what reaching for a row's actions asks
1500+
* (`RowActionMenuProps.onActionsDemand`, objectstack#34208): the
1501+
* record-grained verdicts, and the approval locks of the rows on screen in
1502+
* one read (objectstack#35795), never on first paint. A repeat call is free:
1503+
* the hook asks only ids it has not asked yet.
1504+
*/
1505+
const requestRecordVerdicts = recordVerdict.requestVerdicts;
1506+
const probeApprovalLocks = approvalLocks.probe;
1507+
const demandRowActions = useCallback(() => {
1508+
requestRecordVerdicts();
1509+
if (rowMenuOffersEdit) probeApprovalLocks(pageRecordIds);
1510+
}, [requestRecordVerdicts, probeApprovalLocks, rowMenuOffersEdit, pageRecordIds]);
14891511
// objectstack#35956 — a cell change that makes other fields required asks
14901512
// for them first, and saves them with it (`./objectGridRequiredPrompt`).
14911513
const fieldLabelOf = (field: string): string => {
@@ -2418,8 +2440,8 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
24182440
} = resolveObjectGridActionsColumn({
24192441
schema, data, objectSchema, persistedColumns, operations, resolvedRowActionDefs,
24202442
wantEditAction, wantDeleteAction, mayInvokeRowAction, rowOperations, canEdit, canDelete,
2421-
recordVerdict, predicateScope, onEdit, onDelete, editPredicates, deletePredicates, executeAction,
2422-
setRefreshKey, t, foldInlineRowActions: inlineActionFold.folded,
2443+
recordVerdict, approvalLocks, demandRowActions, predicateScope, onEdit, onDelete, editPredicates,
2444+
deletePredicates, executeAction, setRefreshKey, t, foldInlineRowActions: inlineActionFold.folded,
24232445
drawRowControls: !listPageGrid,
24242446
});
24252447

‎ui/packages/plugin-grid/src/__tests__/inlineEditRecordVerdict-27365.test.tsx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,17 @@ const server = {
9494
};
9595

9696
const apiFetch = async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
97+
// objectstack#36911 — reaching a row's actions also reads the page's approval
98+
// locks. This fake serves the explain engine: the lock door answers every row
99+
// unlocked and is not counted among the explain calls these pins count.
100+
if (String(_input).includes('/approvals/records/')) {
101+
const ids: string[] = JSON.parse(String(init?.body ?? '{}')).recordIds ?? [];
102+
return {
103+
ok: true,
104+
status: 200,
105+
json: async () => ({ records: ids.map((recordId) => ({ recordId, locked: false })) }),
106+
} as unknown as Response;
107+
}
97108
const body = JSON.parse(String(init?.body ?? '{}')) as { object?: string; operation?: Operation; recordIds?: string[] };
98109
server.calls.push(body);
99110
if (!server.network) throw new TypeError('Failed to fetch');
Lines changed: 319 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#36911 — the row menu follows the approval lock.
11+
*
12+
* A row held by a locking approval is refused `RECORD_LOCKED` on update. The
13+
* record page offers no Edit on such a record (objectstack#35593) and keeps
14+
* Delete, because the server lets a locked record be deleted and cancels its
15+
* request. The grid's row menu, which the list page and a record page's
16+
* related tab both render, offered Edit on it.
17+
*
18+
* The menu now reads the lock the select-first cells read
19+
* (`useRowApprovalLocks`, the batch door
20+
* `POST /api/v1/approvals/records/:object/locks`), asked when a row's actions
21+
* are reached for, never on first paint (objectstack#35795). Only an ANSWERED
22+
* lock hides Edit: a 501, a `null` entry, a failed read or a read not yet
23+
* asked leaves the menu as it was.
24+
*/
25+
26+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
27+
import { render, screen, waitFor, cleanup, act, fireEvent, within } from '@testing-library/react';
28+
import userEvent from '@testing-library/user-event';
29+
import '@testing-library/jest-dom';
30+
import React from 'react';
31+
32+
// Stable-identity permission stub, as `rowRecordCrudVerdict.test.tsx` has it:
33+
// ObjectGrid carries `perms` in memo dependency arrays.
34+
const { permsStub } = vi.hoisted(() => ({
35+
permsStub: {
36+
isLoaded: false,
37+
checkField: () => true,
38+
getObjectApiOperations: () => ['get', 'list', 'create', 'update', 'delete'],
39+
can: () => true,
40+
},
41+
}));
42+
43+
vi.mock('@object-ui/permissions', async (importOriginal) => {
44+
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
45+
return { ...actual, usePermissions: () => permsStub };
46+
});
47+
48+
import { ObjectGrid } from '../ObjectGrid';
49+
import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts';
50+
import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks';
51+
import { useListPageScope } from '../listPageScope';
52+
import { registerAllFields } from '@object-ui/fields';
53+
import { ActionProvider, SchemaRendererProvider } from '@object-ui/react';
54+
55+
registerAllFields();
56+
57+
const OBJECT = 'showcase_project';
58+
const LOCKS_PATH = `/api/v1/approvals/records/${OBJECT}/locks`;
59+
/** Under an executive review whose node locks the record. */
60+
const LOCKED_ROW = { id: 'p_locked', name: 'Data Centre Build' };
61+
/** Its sibling on the same page, with no approval running. */
62+
const OPEN_ROW = { id: 'p_open', name: 'Office Refresh' };
63+
64+
/** What the lock door answers, per id; `undefined` is the read's `null` entry. */
65+
type LockDoor =
66+
| { kind: 'answers'; locked: Record<string, boolean | null> }
67+
| { kind: 'status'; status: number }
68+
| { kind: 'network' };
69+
70+
const server = {
71+
door: { kind: 'answers', locked: {} } as LockDoor,
72+
lockCalls: [] as Array<{ recordIds: string[] }>,
73+
responses: [] as Promise<unknown>[],
74+
/** Set by {@link hold}: lock answers wait here until `release` is called. */
75+
gate: null as Promise<void> | null,
76+
release: () => {},
77+
hold() {
78+
server.gate = new Promise<void>((resolve) => {
79+
server.release = () => resolve();
80+
});
81+
},
82+
reset() {
83+
server.gate = null;
84+
server.release = () => {};
85+
server.door = { kind: 'answers', locked: { [LOCKED_ROW.id]: true, [OPEN_ROW.id]: false } };
86+
server.lockCalls = [];
87+
server.responses = [];
88+
},
89+
};
90+
91+
const apiFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
92+
const url = String(input);
93+
const body = JSON.parse(String(init?.body ?? '{}'));
94+
const respond = (status: number, payload: unknown) => {
95+
const res = { ok: status >= 200 && status < 300, status, json: async () => payload } as unknown as Response;
96+
const settled = Promise.resolve(res);
97+
server.responses.push(settled);
98+
return settled;
99+
};
100+
if (url === LOCKS_PATH) {
101+
server.lockCalls.push(body);
102+
if (server.gate) await server.gate;
103+
const door = server.door;
104+
if (door.kind === 'network') {
105+
const failed = Promise.reject(new TypeError('Failed to fetch'));
106+
server.responses.push(failed.catch(() => undefined));
107+
return failed;
108+
}
109+
if (door.kind === 'status') return respond(door.status, { success: false });
110+
const ids: string[] = body.recordIds ?? [];
111+
return respond(200, {
112+
success: true,
113+
data: { records: ids.map((recordId) => ({ recordId, locked: door.locked[recordId] ?? null })) },
114+
});
115+
}
116+
// `security/explain`: every row may be written, so only the lock can take Edit away.
117+
const ids: string[] = Array.isArray(body.recordIds) ? body.recordIds : [];
118+
return respond(200, {
119+
allowed: true,
120+
object: body.object,
121+
operation: body.operation,
122+
principal: { userId: 'u_member' },
123+
layers: [],
124+
records: ids.map((recordId) => ({ recordId, visible: true })),
125+
});
126+
};
127+
128+
/** The fixture page bar: it registers its page column as a list page scope. */
129+
const PageBar: React.FC = () => {
130+
const [scope, setScope] = React.useState<HTMLElement | null>(null);
131+
useListPageScope(scope);
132+
return <div ref={(el) => setScope(el?.parentElement ?? null)} data-testid="page-bar" />;
133+
};
134+
135+
function renderGrid(
136+
rows: Array<Record<string, unknown>> = [LOCKED_ROW, OPEN_ROW],
137+
{ listPage = false }: { listPage?: boolean } = {},
138+
) {
139+
const dataSource: any = {
140+
getObjectSchema: async (name: string) => ({
141+
name,
142+
fields: { id: { type: 'text' }, name: { type: 'text', label: 'Name' }, approval_status: { type: 'text' } },
143+
}),
144+
};
145+
const schema: any = {
146+
type: 'object-grid',
147+
objectName: OBJECT,
148+
columns: [{ field: 'name', label: 'Name' }],
149+
data: { provider: 'value', items: rows },
150+
pageSize: 500,
151+
...(listPage ? { selection: { type: 'multiple' } } : {}),
152+
};
153+
return render(
154+
<ActionProvider>
155+
<SchemaRendererProvider dataSource={dataSource} apiFetch={apiFetch}>
156+
<div data-testid="page-column">
157+
{listPage && <PageBar />}
158+
<ObjectGrid schema={schema} dataSource={dataSource} onEdit={() => {}} onDelete={() => {}} />
159+
</div>
160+
</SchemaRendererProvider>
161+
</ActionProvider>,
162+
);
163+
}
164+
165+
/** Reach for the first row's actions the way a pointer does: hover its "⋮". */
166+
async function reachRowActions() {
167+
await userEvent.hover(screen.getAllByTestId('row-action-trigger')[0]);
168+
}
169+
170+
async function settleReads() {
171+
await act(async () => {
172+
await Promise.allSettled(server.responses);
173+
});
174+
}
175+
176+
/** What the "⋮" of the row showing `label` offers. */
177+
async function rowMenu(label: string): Promise<{ edit: boolean; delete: boolean }> {
178+
const row = screen.getByText(label).closest('tr');
179+
const trigger = row?.querySelector('[data-testid="row-action-trigger"]');
180+
if (!trigger) return { edit: false, delete: false };
181+
await userEvent.click(trigger);
182+
const answer = {
183+
edit: screen.queryAllByTestId('row-action-builtin-edit').length > 0,
184+
delete: screen.queryAllByTestId('row-action-builtin-delete').length > 0,
185+
};
186+
await userEvent.keyboard('{Escape}');
187+
return answer;
188+
}
189+
190+
beforeEach(() => {
191+
server.reset();
192+
__clearRecordCrudVerdictCache();
193+
__resetApprovalsServiceLatch();
194+
});
195+
afterEach(() => {
196+
cleanup();
197+
});
198+
199+
describe('objectstack#36911 — the row menu follows the approval lock', () => {
200+
it('a row held by a locking approval offers no Edit and keeps Delete; its unlocked sibling keeps Edit', async () => {
201+
renderGrid();
202+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
203+
await reachRowActions();
204+
await waitFor(() => expect(server.lockCalls.length).toBe(1));
205+
await settleReads();
206+
await waitFor(async () => expect(await rowMenu(LOCKED_ROW.name)).toEqual({ edit: false, delete: true }));
207+
expect(await rowMenu(OPEN_ROW.name)).toEqual({ edit: true, delete: true });
208+
});
209+
210+
it('reads no lock before a row\'s actions are reached for, then the page in one read', async () => {
211+
renderGrid();
212+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
213+
await settleReads();
214+
expect(server.lockCalls).toHaveLength(0);
215+
await reachRowActions();
216+
await waitFor(() => expect(server.lockCalls).toHaveLength(1));
217+
expect([...server.lockCalls[0].recordIds].sort()).toEqual([LOCKED_ROW.id, OPEN_ROW.id].sort());
218+
// Reaching again, and opening the menus, asks nothing more.
219+
await settleReads();
220+
await rowMenu(LOCKED_ROW.name);
221+
await rowMenu(OPEN_ROW.name);
222+
expect(server.lockCalls).toHaveLength(1);
223+
});
224+
225+
it('a 501 (no approvals service) leaves the menu as it was, even over an approval_status column', async () => {
226+
server.door = { kind: 'status', status: 501 };
227+
renderGrid([{ ...LOCKED_ROW, approval_status: 'pending' }, OPEN_ROW]);
228+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
229+
await reachRowActions();
230+
await waitFor(() => expect(server.lockCalls).toHaveLength(1));
231+
await settleReads();
232+
expect(await rowMenu(LOCKED_ROW.name)).toEqual({ edit: true, delete: true });
233+
expect(await rowMenu(OPEN_ROW.name)).toEqual({ edit: true, delete: true });
234+
});
235+
236+
it('a null entry (a row the reader cannot read) leaves Edit where it was', async () => {
237+
server.door = { kind: 'answers', locked: { [LOCKED_ROW.id]: null, [OPEN_ROW.id]: false } };
238+
renderGrid();
239+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
240+
await reachRowActions();
241+
await waitFor(() => expect(server.lockCalls).toHaveLength(1));
242+
await settleReads();
243+
expect(await rowMenu(LOCKED_ROW.name)).toEqual({ edit: true, delete: true });
244+
});
245+
246+
it('a read that fails, or that never answered, leaves Edit where it was', async () => {
247+
server.door = { kind: 'network' };
248+
renderGrid();
249+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
250+
// Not asked yet: the menu is the one it always was.
251+
expect(server.lockCalls).toHaveLength(0);
252+
await reachRowActions();
253+
await waitFor(() => expect(server.lockCalls).toHaveLength(1));
254+
await settleReads();
255+
expect(await rowMenu(LOCKED_ROW.name)).toEqual({ edit: true, delete: true });
256+
});
257+
});
258+
259+
/**
260+
* The list page draws no "⋮" column (objectstack#35554): one selected record's
261+
* actions are offered by the selection bar, which resolves them from the same
262+
* row menu props. Edit is a bar button there; Delete is a button or behind
263+
* 「More」.
264+
*/
265+
async function selectionBarOffers(label: string): Promise<{ edit: boolean; delete: boolean }> {
266+
const row = screen.getByText(label).closest('tr')!;
267+
fireEvent.click(within(row).getByRole('checkbox'));
268+
const bar = await screen.findByTestId('bulk-actions-bar');
269+
await settleReads();
270+
const offers = () => ({
271+
edit: within(bar).queryByTestId('selection-action-edit') !== null
272+
|| screen.queryAllByTestId('row-action-builtin-edit').length > 0,
273+
delete: within(bar).queryByTestId('selection-action-delete') !== null
274+
|| screen.queryAllByTestId('row-action-builtin-delete').length > 0,
275+
});
276+
const more = within(bar).queryByTestId('selection-actions-more');
277+
if (more) await userEvent.click(more);
278+
const answer = offers();
279+
if (more) await userEvent.keyboard('{Escape}');
280+
fireEvent.click(within(row).getByRole('checkbox'));
281+
await waitFor(() => expect(screen.queryByTestId('bulk-actions-bar')).toBeNull());
282+
return answer;
283+
}
284+
285+
describe('objectstack#36911 — the list page selection bar follows the approval lock', () => {
286+
it('a selected locked row offers no Edit and keeps Delete; a selected unlocked sibling keeps Edit', async () => {
287+
const { container } = renderGrid([LOCKED_ROW, OPEN_ROW], { listPage: true });
288+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
289+
// The list page scope: no Actions column, so the bar is the row's actions.
290+
expect(container.querySelector('th[data-column-key="_actions"]')).toBeNull();
291+
expect(server.lockCalls).toHaveLength(0);
292+
// CONTROL first: the unlocked row offers Edit through the bar, so the pin
293+
// below observes the lock, not a bar that never shows Edit.
294+
expect(await selectionBarOffers(OPEN_ROW.name)).toEqual({ edit: true, delete: true });
295+
expect(server.lockCalls).toHaveLength(1);
296+
expect(await selectionBarOffers(LOCKED_ROW.name)).toEqual({ edit: false, delete: true });
297+
expect(server.lockCalls).toHaveLength(1);
298+
});
299+
});
300+
301+
describe('objectstack#36911 — the read in flight', () => {
302+
it('Edit shows while the lock read is on the wire, and leaves the open menu when it answers locked', async () => {
303+
server.hold();
304+
renderGrid();
305+
await waitFor(() => expect(screen.getByText(LOCKED_ROW.name)).toBeInTheDocument());
306+
const row = screen.getByText(LOCKED_ROW.name).closest('tr')!;
307+
await userEvent.click(row.querySelector('[data-testid="row-action-trigger"]')!);
308+
await waitFor(() => expect(server.lockCalls).toHaveLength(1));
309+
// Unanswered: the menu is the one it always was.
310+
expect(screen.getAllByTestId('row-action-builtin-edit').length).toBeGreaterThan(0);
311+
expect(screen.getAllByTestId('row-action-builtin-delete').length).toBeGreaterThan(0);
312+
await act(async () => {
313+
server.release();
314+
await Promise.allSettled(server.responses);
315+
});
316+
await waitFor(() => expect(screen.queryAllByTestId('row-action-builtin-edit')).toHaveLength(0));
317+
expect(screen.getAllByTestId('row-action-builtin-delete').length).toBeGreaterThan(0);
318+
});
319+
});

0 commit comments

Comments
 (0)