From 357796101d983761c547470b78d3bc77ba4fbe57 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:14:05 +0000 Subject: [PATCH 1/3] fix(grid): a grouped row moves to its new group once its row is left, and group and footer figures follow a cell save (#35689 slice B) Claude-Session: https://claude.ai/code/session_01QsR2jUc3qp6bHKSWijbjds Co-authored-by: Claude --- ui/packages/plugin-grid/src/ObjectGrid.tsx | 64 ++++- .../ObjectGrid.autosave-35685.test.tsx | 230 ++++++++++++++++++ .../plugin-grid/src/objectGridGrouping.ts | 18 +- .../plugin-grid/src/objectGridRowPatch.ts | 29 +++ 4 files changed, 333 insertions(+), 8 deletions(-) diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 32f63644ac2..0153964c5ea 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -103,7 +103,8 @@ import { useGridTranslation } from './objectGridTranslations'; import { inlineEditRuleRefusals, inlineRuleRefusalError } from './objectGridInlineRules'; import { DEFAULT_DISPLAY_PAGE_SIZE, DEFAULT_SELECTION_TYPE, type RowHeightMode, resolvePageSize, resolveRowHeightMode } from './objectGridDefaults'; import { type BatchSaveOutcome, type RowConflictChoice, type WrittenRowVersion, rowVersionOf, rowVersionToSend } from './objectGridRowVersion'; -import { type RowPatch, mergeSavedRow } from './objectGridRowPatch'; +import { type RowPatch, mergeSavedRow, rowsAsSaved } from './objectGridRowPatch'; +import { usableGroupingFields } from './useGroupedData'; import { type CellSaveUndo, createCellUndoStack, isCellUndoKey, undoKeyCellOf } from './objectGridCellUndo'; import { type ObjectGridExternalPaginationProps, type ObjectGridFooterSummary, type ObjectGridRowGroup } from './objectGridProps'; import { FooterSummaryReport } from './objectGridFooterSummaryReport'; @@ -852,6 +853,9 @@ function cellEditorWidthClass(type: string): string { } } +/** objectstack#35689 — no record waits in its group. */ +const NO_HELD_RECORDS: ReadonlySet = new Set(); + export const ObjectGrid: React.FC = ({ schema, dataSource, @@ -959,6 +963,25 @@ export const ObjectGrid: React.FC = ({ // which `writeRowInPlace` sets together with the state it renders from. const cellUndoRef = React.useRef(createCellUndoStack()); const rowPatchesRef = React.useRef(rowPatches); + // objectstack#35689 — the records a select-first save moved to another + // group while the reader is still on their row: each stays in the group it + // was read in, counted and summed there, until a cell of another row is + // selected. Then the groups are read again (`regroupNonce`), and a grid + // that buckets in the browser buckets the saved row. Any other save is in + // the figures at once (`savedFigureNonce` re-asks the server's headers). + const [heldInGroup, setHeldInGroup] = useState>(NO_HELD_RECORDS); + const heldInGroupRef = React.useRef(heldInGroup); + const [regroupNonce, setRegroupNonce] = useState(0); + const [savedFigureNonce, setSavedFigureNonce] = useState(0); + const leaveHeldRows = useCallback((selectedRecordId: unknown) => { + const held = heldInGroupRef.current; + const stay = selectedRecordId === undefined || selectedRecordId === null ? undefined : String(selectedRecordId); + if (held.size === 0 || (held.size === 1 && stay !== undefined && held.has(stay))) return; + const next = stay !== undefined && held.has(stay) ? new Set([stay]) : NO_HELD_RECORDS; + heldInGroupRef.current = next; + setHeldInGroup(next); + setRegroupNonce((n) => n + 1); + }, []); const [showExport, setShowExport] = useState(false); const [exportBusy, setExportBusy] = useState(false); const [exportError, setExportError] = useState(null); @@ -1443,6 +1466,8 @@ export const ObjectGrid: React.FC = ({ }; }, onCellSelect: (row) => { + // objectstack#35689 — a row held in its group is left. + leaveHeldRows(rowRecordId(row)); recordVerdict.requestVerdicts(); // objectstack#35795 — one lock read for the page, not one per row selected. approvalLocks.probe([rowRecordId(row), ...pageRecordIds]); @@ -1468,7 +1493,7 @@ export const ObjectGrid: React.FC = ({ } : null), [ hostCellSelection, opensReferencedRecords, objectFields, objectSchema, objectName, perms, - gridEditable, objectInlineEditable, approvalLocks, recordVerdict, pageRecordIds, t, + gridEditable, objectInlineEditable, approvalLocks, recordVerdict, pageRecordIds, t, leaveHeldRows, ]); // objectstack#35685 — the state-machine confirm, the grid's next question // when the required-fields prompt has nothing to ask. @@ -1846,13 +1871,18 @@ export const ObjectGrid: React.FC = ({ // The grouping: the group value formatter and date faces, the server group // headers and rows, and the grouped data, in hook order (`./objectGridGrouping`). + // objectstack#35689 — the rows the figures read: each saved row in place of + // the row read (the footer), and, for the groups, a row still held in its + // group (`heldInGroup`) as it was read. + const savedData = useMemo(() => rowsAsSaved(data, rowPatches), [data, rowPatches]); + const groupedData = useMemo(() => rowsAsSaved(data, rowPatches, heldInGroup), [data, rowPatches, heldInGroup]); const { temporalGroupFaces, groupWhere, groupHeaders, groups, isGrouped, toggleGroup, groupRows, } = useObjectGridGrouping({ - schema, dataSource, objectName, objectFields, objectTypesPending, data, setData, + schema, dataSource, objectName, objectFields, objectTypesPending, data: groupedData, setData, setTotalMatching, t, translateOptions, groupedPage, setGroupedPage, groupedPageSize, refreshKey, serverPageSize, groupRowQuery, groupingKeyReadable, groupingRefusesNothing, - unmaskedGroupingFields, serverGroupedFetch, invalidationNonce, + unmaskedGroupingFields, serverGroupedFetch, invalidationNonce, savedFigureNonce, regroupNonce, }); // objectstack#35685 — the rows the grid read, as an undo finds its record // among them when it runs: the page's rows, and a server-grouped group's. @@ -1869,7 +1899,7 @@ export const ObjectGrid: React.FC = ({ const { bulkFanoutParams, resolvedTotalMatching, summaries, hasSummary, summaryTypes, } = useObjectGridSummaries({ - schema, dataSource, objectName, objectSchema, objectFields, objectTypesPending, data, hasInlineData, + schema, dataSource, objectName, objectSchema, objectFields, objectTypesPending, data: savedData, hasInlineData, externalManualPagination, hostFindParams, hostRowCount, lastFindParamsRef, totalMatching, refreshKey, serverPage, fetchWindow, serverGroupedFetch, isGrouped, summaryPicks, }); @@ -3053,12 +3083,36 @@ export const ObjectGrid: React.FC = ({ next.set(id, { base: held && held.row === row ? held.base : row, row: mergeSavedRow(row, shown, answer) }); rowPatchesRef.current = next; setRowPatches(next); + noteSavedPlace(id, Object.keys(changes)); return { outcome: 'saved', result: answer }; } finally { releaseOwnWrite(); } }; + /** + * objectstack#35689 — where a landed select-first save of `fields` on + * record `id` leaves it in a grouped grid: a save that wrote a grouping + * field, or any save on a row already held, keeps the row in the group it + * was read in until the reader leaves the row (`leaveHeldRows`); any other + * save is in its group's figures at once, which a server-grouped grid asks + * its headers for again. + */ + const noteSavedPlace = (id: string, fields: readonly string[]): void => { + if (!isGrouped) return; + const groupingFields = usableGroupingFields(schema.grouping?.fields).map((gf) => gf.field); + const held = heldInGroupRef.current; + if (held.has(id)) return; + if (fields.some((field) => groupingFields.includes(field))) { + const next = new Set(held); + next.add(id); + heldInGroupRef.current = next; + setHeldInGroup(next); + return; + } + if (serverGroupedFetch) setSavedFigureNonce((n) => n + 1); + }; + /** * objectstack#35685 — the row an undo of record `id` is drawn over: the row * the grid draws for it now (a later save's patch over the row it read, or diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index ceff6fbdaa8..b265e129dc7 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -53,6 +53,7 @@ import { ActionProvider, notifyDataChanged, createOwnWrites, OwnWritesContext } import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; import { installExplainDouble } from './explainDouble'; +import { withinBand } from './groupBandScope'; beforeEach(() => { __clearRecordCrudVerdictCache(); @@ -689,3 +690,232 @@ describe('ObjectGrid — a state-machine field is confirmed before a list cell s expect(ds.update).not.toHaveBeenCalled(); }); }); + +describe('ObjectGrid — groups, subtotals and the footer total after a cell save (objectstack#35689)', () => { + /** + * Deals by stage (Prospect / Won) with an amount: Prospect holds Acme 100 + * and Bolt 50, Won holds Cord 30. One store serves every read the grid + * makes: the group header query (grouped, or ungrouped for the footer's + * whole-set figure), each group's row page, a flat window, and the write, + * which is announced on the data-invalidation bus as the console's + * mutation bridge announces it. + */ + type Deal = { id: string; name: string; stage: string; amount: number; updated_at: string }; + type Agg = { function: string; field?: string; alias: string }; + function matchesWhere(row: Record, cond: unknown): boolean { + if (cond === undefined || cond === null) return true; + return Object.entries(cond as Record).every(([key, value]) => { + if (key === '$and') return (value as unknown[]).every((c) => matchesWhere(row, c)); + if (value && typeof value === 'object' && !Array.isArray(value)) { + const op = value as Record; + if ('$eq' in op) return row[key] === op.$eq; + if ('$null' in op) return op.$null ? row[key] == null : row[key] != null; + throw new Error(`double: unsupported operator ${JSON.stringify(op)}`); + } + return row[key] === value; + }); + } + function makeDealSource() { + const store: Record = { + o1: { id: 'o1', name: 'Acme', stage: 'prospect', amount: 100, updated_at: '2026-11-20T10:00:00.000Z' }, + o2: { id: 'o2', name: 'Bolt', stage: 'prospect', amount: 50, updated_at: '2026-11-20T10:00:00.000Z' }, + o3: { id: 'o3', name: 'Cord', stage: 'won', amount: 30, updated_at: '2026-11-20T10:00:00.000Z' }, + }; + let clock = 0; + const rows = () => Object.values(store); + const ds = { + store, + queryGroupHeaders: vi.fn(async (_object: string, query: { where?: unknown; groupBy?: string[]; aggregations?: Agg[] }) => { + const groupBy = query.groupBy ?? []; + const buckets = new Map(); + for (const row of rows().filter((r) => matchesWhere(r, query.where))) { + const key = JSON.stringify(groupBy.map((f) => (row as any)[f] ?? null)); + if (!buckets.has(key)) buckets.set(key, []); + buckets.get(key)!.push(row); + } + return [...buckets.entries()].map(([key, members]) => { + const values = JSON.parse(key) as unknown[]; + const out: Record = Object.fromEntries(groupBy.map((f, i) => [f, values[i]])); + for (const agg of query.aggregations ?? []) { + out[agg.alias] = agg.function === 'count' + ? members.length + : agg.function === 'sum' + ? members.reduce((a, m) => a + Number((m as any)[agg.field!]), 0) + : null; + } + return out as { count: number }; + }); + }), + find: vi.fn(async (_object: string, params: Record = {}) => { + const where = Array.isArray(params.$filter) ? undefined : params.$filter; + const matching = rows().filter((r) => matchesWhere(r, where)).sort((a, b) => a.name.localeCompare(b.name)); + const skip = (params.$skip as number | undefined) ?? 0; + const top = (params.$top as number | undefined) ?? matching.length; + return { data: matching.slice(skip, skip + top).map((r) => ({ ...r })), total: matching.length }; + }), + findOne: vi.fn(), + create: vi.fn(), + delete: vi.fn(), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes, updated_at: `2026-11-20T11:00:0${++clock}.000Z` }; + notifyDataChanged({ objectName: OBJECT, recordId: id }); + return { ...store[id] }; + }), + getObjectSchema: vi.fn(async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { type: 'select', label: 'Stage', options: [{ value: 'prospect', label: 'Prospect' }, { value: 'won', label: 'Won' }] }, + amount: { type: 'number', label: 'Amount' }, + updated_at: { type: 'datetime' }, + }, + })), + }; + return ds; + } + type DealSource = ReturnType; + + const COLUMNS = [ + { field: 'name', label: 'Name' }, + { field: 'stage', label: 'Stage' }, + { field: 'amount', label: 'Amount', type: 'number' }, + ]; + /** + * The grid grouped by stage with an amount subtotal: on the server + * (`server`, the grid reads its own groups) or bucketed in the browser over + * the rows a host hands it (`browser`). + */ + function renderGrouped(ds: DealSource, path: 'server' | 'browser', cellSelection = true) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + columns: COLUMNS, + grouping: { fields: [{ field: 'stage' }] }, + aggregations: [{ field: 'amount', type: 'sum' }], + pagination: { pageSize: 50 }, + }; + return render( + + ({ ...r })) } : {})} + /> + , + ); + } + const bands = () => [...document.querySelectorAll('[data-testid^="group-row-"]')]; + const bandOf = (label: string) => bands().find((b) => b.querySelector('.group-label')?.textContent === label)!; + /** Each group as 「count · sum」, by its label. */ + const groupFigures = () => Object.fromEntries(bands().map((b) => [ + b.querySelector('.group-label')?.textContent ?? '', + `${b.querySelector('.group-count')?.textContent} · ${b.querySelector('.group-aggregations')?.textContent?.replace(/^\s*sum:\s*/, '')}`, + ])); + const namesIn = (label: string) => withinBand(bandOf(label)).queryAllByText(/^(Acme|Bolt|Cord)$/).map((n) => n.textContent); + const cellOf = (container: HTMLElement, text: string) => + Array.from(container.querySelectorAll('tbody td')).find((td) => td.textContent === text)!; + const cellIn = (container: HTMLElement, rowName: string, text: string) => { + const row = cellOf(container, rowName).closest('tr')!; + return Array.from(row.querySelectorAll('td')).find((td) => td.textContent === text)!; + }; + function pasteInto(container: HTMLElement, cell: HTMLElement, text: string) { + fireEvent.click(cell); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => text } }); + } + + describe.each(['server', 'browser'] as const)('%s grouping', (path) => { + it("a row whose stage changed stays in its group until another row is selected, then counts and sums in its new one", async () => { + const ds = makeDealSource(); + const { container } = renderGrouped(ds, path); + await waitFor(() => expect(namesIn('Won')).toEqual(['Cord'])); + expect(groupFigures()).toEqual({ Prospect: '2 · 150', Won: '1 · 30' }); + pasteInto(container, cellIn(container, 'Bolt', 'Prospect'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + // Still on the row: it keeps its place, and the groups their figures. + await waitFor(() => expect(cellIn(container, 'Bolt', 'Won')).toBeTruthy()); + expect(namesIn('Prospect')).toEqual(['Acme', 'Bolt']); + expect(groupFigures()).toEqual({ Prospect: '2 · 150', Won: '1 · 30' }); + // Another cell of the same row is not leaving it. + fireEvent.click(cellOf(container, 'Bolt')); + expect(namesIn('Prospect')).toEqual(['Acme', 'Bolt']); + expect(groupFigures()).toEqual({ Prospect: '2 · 150', Won: '1 · 30' }); + // Leaving it: a cell of another row is selected. + fireEvent.click(cellOf(container, 'Acme')); + await waitFor(() => expect(namesIn('Won')).toEqual(['Bolt', 'Cord'])); + expect(namesIn('Prospect')).toEqual(['Acme']); + await waitFor(() => expect(groupFigures()).toEqual({ Prospect: '1 · 100', Won: '2 · 80' })); + }); + + it('an amount saved is in its group subtotal at once', async () => { + const ds = makeDealSource(); + const { container } = renderGrouped(ds, path); + await waitFor(() => expect(namesIn('Won')).toEqual(['Cord'])); + const reads = ds.find.mock.calls.length; + const headerReads = ds.queryGroupHeaders.mock.calls.length; + await editSelectFirst(container, cellIn(container, 'Bolt', '50'), '70'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(groupFigures()).toEqual({ Prospect: '2 · 170', Won: '1 · 30' })); + expect(namesIn('Prospect')).toEqual(['Acme', 'Bolt']); + // The figures, and no row, are read again: a server-grouped grid asks + // its headers once more; a grid bucketing in the browser asks nothing. + expect(ds.find.mock.calls.length).toBe(reads); + expect(ds.queryGroupHeaders.mock.calls.length).toBe(headerReads + (path === 'server' ? 1 : 0)); + }); + }); + + it('control: without cellSelection a write announced on the bus re-reads the grouped grid at once', async () => { + const ds = makeDealSource(); + renderGrouped(ds, 'server', false); + await waitFor(() => expect(namesIn('Won')).toEqual(['Cord'])); + ds.store.o2 = { ...ds.store.o2, stage: 'won' }; + notifyDataChanged({ objectName: OBJECT, recordId: 'o2' }); + await waitFor(() => expect(namesIn('Won')).toEqual(['Bolt', 'Cord'])); + expect(groupFigures()).toEqual({ Prospect: '1 · 100', Won: '2 · 80' }); + }); + + /** A column's footer figure (the table's own summary row). */ + const footerOf = (field: string) => screen.queryByTestId(`data-table-summary-${field}`)?.textContent ?? null; + const FOOTER_COLUMNS = [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount', type: 'number', summary: 'sum' }, + ]; + + it('the footer total of a grid whose rows are the set follows an amount saved', async () => { + const ds = makeDealSource(); + const { container } = render( + + + , + ); + await waitFor(() => expect(footerOf('amount')).toMatch(/180/)); + await editSelectFirst(container, cellIn(container, 'Bolt', '50'), '70'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(footerOf('amount')).toMatch(/200/)); + }); + + it('the footer total read from the server for a paged grid is read again after an amount saved', async () => { + const ds = makeDealSource(); + const { container } = render( + + + , + ); + await waitFor(() => expect(footerOf('amount')).toMatch(/180/)); + await editSelectFirst(container, cellIn(container, 'Bolt', '50'), '70'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + await waitFor(() => expect(footerOf('amount')).toMatch(/200/)); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridGrouping.ts b/ui/packages/plugin-grid/src/objectGridGrouping.ts index 96e1a18b237..c6f489a5c99 100644 --- a/ui/packages/plugin-grid/src/objectGridGrouping.ts +++ b/ui/packages/plugin-grid/src/objectGridGrouping.ts @@ -86,7 +86,7 @@ export function useObjectGridGrouping({ schema, dataSource, objectName, objectFields, objectTypesPending, data, setData, setTotalMatching, t, translateOptions, groupedPage, setGroupedPage, groupedPageSize, refreshKey, serverPageSize, groupRowQuery, groupingKeyReadable, groupingRefusesNothing, unmaskedGroupingFields, - serverGroupedFetch, invalidationNonce, + serverGroupedFetch, invalidationNonce, savedFigureNonce, regroupNonce, }: { schema: ObjectGridSchema; dataSource: DataSource | undefined; @@ -109,6 +109,17 @@ export function useObjectGridGrouping({ unmaskedGroupingFields: GroupingDecisions['unmaskedGroupingFields']; serverGroupedFetch: GroupingDecisions['serverGroupedFetch']; invalidationNonce: RowLoad['invalidationNonce']; + /** + * objectstack#35689 — bumped when a select-first save changed a figure but + * no group: the server's headers are asked again, the rows on screen stay. + */ + savedFigureNonce: number; + /** + * objectstack#35689 — bumped when the reader left a row whose save moved it + * to another group: the server's headers and the open groups' rows are + * asked again. + */ + regroupNonce: number; }) { // --- Grouping support --- // Build a per-field value formatter so group headers display the human @@ -290,7 +301,8 @@ export function useObjectGridGrouping({ return { error: err instanceof Error ? err : new Error(String(err)) }; } }, [groupRowQueryKey]); - const groupReloadKey = `${refreshKey}:${invalidationNonce}`; + const groupReloadKey = `${refreshKey}:${invalidationNonce}:${regroupNonce}`; + const groupHeaderReloadKey = `${groupReloadKey}:${savedFigureNonce}`; // [ADR-0144 D6, ADR-0158 U7 R1] A measure aggregate over a `record`-mode // amount or quantity stands only in groups bucketed by its code or unit // field; elsewhere it would add amounts in different currencies or @@ -335,7 +347,7 @@ export function useObjectGridGrouping({ ...groupSearchOf(groupRowQuery), aggregations: groupAggregations, objectFields, - reloadKey: groupReloadKey, + reloadKey: groupHeaderReloadKey, }); // Keyed on the hook's STATE values (a stable identity React promises), so // the group tree is rebuilt when the server answers, not on every render. diff --git a/ui/packages/plugin-grid/src/objectGridRowPatch.ts b/ui/packages/plugin-grid/src/objectGridRowPatch.ts index 276cb66b829..8d624262375 100644 --- a/ui/packages/plugin-grid/src/objectGridRowPatch.ts +++ b/ui/packages/plugin-grid/src/objectGridRowPatch.ts @@ -79,3 +79,32 @@ export interface RowPatch { base: unknown; row: Record; } + +const NO_RECORDS: ReadonlySet = new Set(); + +/** + * objectstack#35689 — `rows` with every saved row in place of the row the + * grid read (while that read is the one held), as the grid's figures read + * them: the footer total, and the groups a grid buckets in the browser with + * their counts and subtotals. A record in `waiting` keeps the row it was read + * as: its save moved it to another group, and it stays where it is, counted + * and summed there, until the reader leaves its row. The same array when no + * saved row applies. + */ +export function rowsAsSaved( + rows: any[], + patches: ReadonlyMap, + waiting: ReadonlySet = NO_RECORDS, +): any[] { + if (patches.size === 0) return rows; + let changed = false; + const next = rows.map((row) => { + const id = row?._id ?? row?.id; + if (id === undefined || id === null || waiting.has(String(id))) return row; + const patch = patches.get(String(id)); + if (!patch || patch.base !== row) return row; + changed = true; + return patch.row; + }); + return changed ? next : rows; +} From a49cc566e078524ad1ccba43f9c494a59b2a5b4c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 12:15:12 +0000 Subject: [PATCH 2/3] fix(grid): key the row leave as the save keys it; changeset and docs (#35689 slice B) Claude-Session: https://claude.ai/code/session_01QsR2jUc3qp6bHKSWijbjds Co-authored-by: Claude --- .changeset/35689-group-refresh.md | 16 ++++++++++++++++ content/docs/frontend/plugins/plugin-grid.mdx | 6 ++++++ ui/packages/plugin-grid/src/ObjectGrid.tsx | 5 +++-- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 .changeset/35689-group-refresh.md diff --git a/.changeset/35689-group-refresh.md b/.changeset/35689-group-refresh.md new file mode 100644 index 00000000000..10442329f16 --- /dev/null +++ b/.changeset/35689-group-refresh.md @@ -0,0 +1,16 @@ +--- +'@object-ui/plugin-grid': patch +--- + +fix(grid): after a cell save in a list that selects a cell first, a grouped row moves to its new group once the user leaves the row, and group subtotals and the footer total follow the save + +Clause-②: no +Metadata-protocol: none + +A list that selects a cell first (the list page) saves each cell and redraws only that row. Until now the groups and the footer did not follow that save: + +- **A changed group field.** The row stays where it is while the user is still on it. Once a cell of another row is selected, the row shows in its new group, and both groups' counts and subtotals are correct. A grid grouped on the server reads its group headers and the open groups' rows again at that moment. A grid that groups the rows it was handed puts the saved row in its new group. +- **Any other field.** The group subtotals include the saved value straight away. A grid grouped on the server reads its group headers again and reads no row. A grid that groups the rows it was handed recounts them. +- **The footer total.** A flat grid whose rows are the whole set totals the saved value straight away. A grid paged on the server already read its whole-set figures again after a write, and still does. + +A grid that is not select-first still reads everything again after each save, as before. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 90d060c9782..249d317d6c8 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -463,6 +463,12 @@ value a server hook rewrote shows as stored); the list is not read again, so a row whose new value would sort it elsewhere stays in place until the next load (a refresh, a sort, a filter or a page change). +- **Groups and totals follow the save** (objectstack#35689). A save that + changes the grouping field leaves the row in its group while the user is on + it; once a cell of another row is selected, the row shows in its new group + and both groups' counts and subtotals are correct (a server-grouped grid + reads its group headers and open groups' rows again then). Any other save is + in its group's subtotals at once, and in the footer total of a flat grid. - **A refused save** keeps the typed value and shows the server's reason on the cell. Escape puts the stored value back. A later edit on the same row is sent together with the refused one, as one update. When the reason names a field diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 0153964c5ea..f5aebf14609 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1466,8 +1466,9 @@ export const ObjectGrid: React.FC = ({ }; }, onCellSelect: (row) => { - // objectstack#35689 — a row held in its group is left. - leaveHeldRows(rowRecordId(row)); + // objectstack#35689 — a row held in its group is left. Keyed as + // the save keys it (`resolveRecordId`). + leaveHeldRows(row?._id ?? row?.id); recordVerdict.requestVerdicts(); // objectstack#35795 — one lock read for the page, not one per row selected. approvalLocks.probe([rowRecordId(row), ...pageRecordIds]); From 1285fe44a5bdfac2894eb5f2955cb003e7efa501 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:12:23 +0000 Subject: [PATCH 3/3] test(grid): place the group refresh pins before the state-machine block (#35689 slice B) Claude-Session: https://claude.ai/code/session_01QsR2jUc3qp6bHKSWijbjds Co-authored-by: Claude --- .../ObjectGrid.autosave-35685.test.tsx | 242 +++++++++--------- 1 file changed, 121 insertions(+), 121 deletions(-) diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index b265e129dc7..1b286b8c488 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -570,127 +570,6 @@ describe("ObjectGrid — a grid without cellSelection re-reads on the host list' }); }); -describe('ObjectGrid — a state-machine field is confirmed before a list cell saves it (objectstack#35685)', () => { - /** Deals whose `stage` a state machine governs, and whose `priority` none does. */ - function makeMachineDataSource(rule: Record = {}) { - const ds = makeDataSource(); - ds.store.d1.stage = 'new'; - ds.store.d1.priority = 'low'; - ds.getObjectSchema = async (name: string) => ({ - name, - fields: { - id: { type: 'text' }, - name: { type: 'text', label: 'Name' }, - stage: { - type: 'select', - label: 'Stage', - options: [ - { value: 'new', label: 'New' }, - { value: 'qualified', label: 'Qualified' }, - { value: 'won', label: 'Won' }, - ], - }, - priority: { type: 'select', label: 'Priority', options: [{ value: 'low', label: 'Low' }, { value: 'high', label: 'High' }] }, - updated_at: { type: 'datetime' }, - }, - validations: [{ - name: 'stage_flow', - type: 'state_machine', - field: 'stage', - transitions: { new: ['qualified', 'won'], qualified: ['won'] }, - ...rule, - }], - }); - return ds; - } - - function renderMachineGrid(ds: any) { - const schema: any = { - type: 'object-grid', - objectName: OBJECT, - editable: true, - columns: [ - { field: 'name', label: 'Name' }, - { field: 'stage', label: 'Stage' }, - { field: 'priority', label: 'Priority' }, - ], - pagination: { pageSize: 50 }, - }; - return render( - - - , - ); - } - - /** Select a cell and paste `text` into it (a commit made without an editor). */ - function pasteInto(container: HTMLElement, cell: HTMLElement, text: string) { - fireEvent.click(cell); - const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; - fireEvent.paste(catcher, { clipboardData: { getData: () => text } }); - } - - it('names the field and both values, says automation may run, and Cancel saves nothing', async () => { - const ds = makeMachineDataSource(); - const { container } = renderMachineGrid(ds); - await screen.findByText('beta'); - pasteInto(container, dataCell(container, 0, 'New'), 'Won'); - const dialog = await screen.findByRole('alertdialog'); - expect(dialog).toHaveTextContent('Change Stage?'); - expect(dialog).toHaveTextContent('Stage changes from New to Won. Saving may trigger related automation.'); - expect(ds.update).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); - await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); - await act(async () => {}); - expect(ds.update).not.toHaveBeenCalled(); - expect(dataCell(container, 0, 'New')).toBeTruthy(); - }); - - it('Change sends the move as one guarded update', async () => { - const ds = makeMachineDataSource(); - const { container } = renderMachineGrid(ds); - await screen.findByText('beta'); - pasteInto(container, dataCell(container, 0, 'New'), 'Won'); - await screen.findByRole('alertdialog'); - fireEvent.click(screen.getByRole('button', { name: 'Change' })); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - expect(ds.update).toHaveBeenCalledWith(OBJECT, 'd1', { stage: 'won' }, { ifMatch: '2026-11-20T10:00:00.000Z' }); - await waitFor(() => expect(dataCell(container, 0, 'Won')).toBeTruthy()); - }); - - it('a field no state machine governs, and an inactive machine, save without asking', async () => { - const ds = makeMachineDataSource({ active: false }); - const { container } = renderMachineGrid(ds); - await screen.findByText('beta'); - pasteInto(container, dataCell(container, 0, 'Low'), 'High'); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - expect(ds.update.mock.calls[0][2]).toEqual({ priority: 'high' }); - pasteInto(container, dataCell(container, 0, 'New'), 'Won'); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(2)); - expect(screen.queryByRole('alertdialog')).toBeNull(); - }); - - it('a machine bound to insert alone does not govern an update: the move saves without asking', async () => { - const ds = makeMachineDataSource({ events: ['insert'] }); - const { container } = renderMachineGrid(ds); - await screen.findByText('beta'); - pasteInto(container, dataCell(container, 0, 'New'), 'Won'); - await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); - expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); - expect(screen.queryByRole('alertdialog')).toBeNull(); - }); - - it('an advisory (warning-severity) machine still asks: the move is what automation listens for', async () => { - const ds = makeMachineDataSource({ severity: 'warning', events: ['update'] }); - const { container } = renderMachineGrid(ds); - await screen.findByText('beta'); - pasteInto(container, dataCell(container, 0, 'New'), 'Won'); - const dialog = await screen.findByRole('alertdialog'); - expect(dialog).toHaveTextContent('Stage changes from New to Won.'); - expect(ds.update).not.toHaveBeenCalled(); - }); -}); - describe('ObjectGrid — groups, subtotals and the footer total after a cell save (objectstack#35689)', () => { /** * Deals by stage (Prospect / Won) with an amount: Prospect holds Acme 100 @@ -919,3 +798,124 @@ describe('ObjectGrid — groups, subtotals and the footer total after a cell sav await waitFor(() => expect(footerOf('amount')).toMatch(/200/)); }); }); + +describe('ObjectGrid — a state-machine field is confirmed before a list cell saves it (objectstack#35685)', () => { + /** Deals whose `stage` a state machine governs, and whose `priority` none does. */ + function makeMachineDataSource(rule: Record = {}) { + const ds = makeDataSource(); + ds.store.d1.stage = 'new'; + ds.store.d1.priority = 'low'; + ds.getObjectSchema = async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'new', label: 'New' }, + { value: 'qualified', label: 'Qualified' }, + { value: 'won', label: 'Won' }, + ], + }, + priority: { type: 'select', label: 'Priority', options: [{ value: 'low', label: 'Low' }, { value: 'high', label: 'High' }] }, + updated_at: { type: 'datetime' }, + }, + validations: [{ + name: 'stage_flow', + type: 'state_machine', + field: 'stage', + transitions: { new: ['qualified', 'won'], qualified: ['won'] }, + ...rule, + }], + }); + return ds; + } + + function renderMachineGrid(ds: any) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'stage', label: 'Stage' }, + { field: 'priority', label: 'Priority' }, + ], + pagination: { pageSize: 50 }, + }; + return render( + + + , + ); + } + + /** Select a cell and paste `text` into it (a commit made without an editor). */ + function pasteInto(container: HTMLElement, cell: HTMLElement, text: string) { + fireEvent.click(cell); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => text } }); + } + + it('names the field and both values, says automation may run, and Cancel saves nothing', async () => { + const ds = makeMachineDataSource(); + const { container } = renderMachineGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + const dialog = await screen.findByRole('alertdialog'); + expect(dialog).toHaveTextContent('Change Stage?'); + expect(dialog).toHaveTextContent('Stage changes from New to Won. Saving may trigger related automation.'); + expect(ds.update).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + await act(async () => {}); + expect(ds.update).not.toHaveBeenCalled(); + expect(dataCell(container, 0, 'New')).toBeTruthy(); + }); + + it('Change sends the move as one guarded update', async () => { + const ds = makeMachineDataSource(); + const { container } = renderMachineGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await screen.findByRole('alertdialog'); + fireEvent.click(screen.getByRole('button', { name: 'Change' })); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update).toHaveBeenCalledWith(OBJECT, 'd1', { stage: 'won' }, { ifMatch: '2026-11-20T10:00:00.000Z' }); + await waitFor(() => expect(dataCell(container, 0, 'Won')).toBeTruthy()); + }); + + it('a field no state machine governs, and an inactive machine, save without asking', async () => { + const ds = makeMachineDataSource({ active: false }); + const { container } = renderMachineGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'Low'), 'High'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ priority: 'high' }); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(2)); + expect(screen.queryByRole('alertdialog')).toBeNull(); + }); + + it('a machine bound to insert alone does not govern an update: the move saves without asking', async () => { + const ds = makeMachineDataSource({ events: ['insert'] }); + const { container } = renderMachineGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ stage: 'won' }); + expect(screen.queryByRole('alertdialog')).toBeNull(); + }); + + it('an advisory (warning-severity) machine still asks: the move is what automation listens for', async () => { + const ds = makeMachineDataSource({ severity: 'warning', events: ['update'] }); + const { container } = renderMachineGrid(ds); + await screen.findByText('beta'); + pasteInto(container, dataCell(container, 0, 'New'), 'Won'); + const dialog = await screen.findByRole('alertdialog'); + expect(dialog).toHaveTextContent('Stage changes from New to Won.'); + expect(ds.update).not.toHaveBeenCalled(); + }); +});