Skip to content

Commit 2e22264

Browse files
committed
fix(plugin-dashboard): drop a drilled record's open once the drill closes; read its step set in a stable order
Review round 2 on the drill's whole-result step set: - The deferred open checks that the drill is still open and mounted and that no later click started another open; otherwise it is dropped, so Esc or an outside click while the ids are read navigates nowhere. - The id read appends `id` as the last tiebreaker to the list's sort (`id` alone when there is none) and deduplicates the ids, so parallel windows over a sort with ties neither repeat nor skip a record. - A failed read is warned once. Claude-Session: https://claude.ai/code/session_01JQwxbZkNEjKLHtTo4edMVH Co-authored-by: Claude <noreply@anthropic.com>
1 parent dc1c6c8 commit 2e22264

5 files changed

Lines changed: 165 additions & 19 deletions

File tree

‎ui/packages/app-shell/src/views/drillDialogStandardList-36256.test.tsx‎

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,13 @@ describe('a record opened from a drill steps through the whole drill (#36554)',
119119
amount: i + 1,
120120
}));
121121

122-
function mountPaged(rows: typeof ALL, pageSize: number) {
122+
function mountPaged(rows: typeof ALL, pageSize: number, { holdIdReads = false } = {}) {
123+
// With `holdIdReads`, the drill's id reads wait until `releaseIdReads()`.
124+
let releaseIdReads = () => {};
125+
const idReadsHeld = new Promise<void>((resolve) => { releaseIdReads = resolve; });
123126
const ds = {
124127
find: vi.fn(async (_object: string, params: { $top?: number; $skip?: number; $select?: string[] } = {}) => {
128+
if (holdIdReads && JSON.stringify(params.$select) === '["id"]') await idReadsHeld;
125129
const skip = params.$skip ?? 0;
126130
const top = params.$top ?? rows.length;
127131
const page = rows.slice(skip, skip + top);
@@ -139,13 +143,14 @@ describe('a record opened from a drill steps through the whole drill (#36554)',
139143
getObjectSchema: vi.fn(async () => structuredClone(DEFINITION)),
140144
};
141145
const openRecord = vi.fn();
142-
render(
146+
const onClose = vi.fn();
147+
const drill = (open: boolean) => (
143148
<SchemaRendererProvider dataSource={ds as any}>
144149
<DrillNavigationProvider value={{ openRecord }}>
145150
<DrillDownDrawer
146-
open
151+
open={open}
147152
target="dialog"
148-
onClose={vi.fn()}
153+
onClose={onClose}
149154
title="Negotiation"
150155
objectName="deal_36256"
151156
filter={{ stage: 'negotiation' }}
@@ -154,9 +159,10 @@ describe('a record opened from a drill steps through the whole drill (#36554)',
154159
dataSource={ds}
155160
/>
156161
</DrillNavigationProvider>
157-
</SchemaRendererProvider>,
162+
</SchemaRendererProvider>
158163
);
159-
return { ds, openRecord };
164+
const view = render(drill(true));
165+
return { ds, openRecord, onClose, releaseIdReads, close: () => view.rerender(drill(false)), unmount: view.unmount };
160166
}
161167

162168
const idReads = (ds: { find: ReturnType<typeof vi.fn> }) =>
@@ -187,6 +193,50 @@ describe('a record opened from a drill steps through the whole drill (#36554)',
187193
for (const write of [ds.create, ds.update, ds.delete, ds.bulk]) expect(write).not.toHaveBeenCalled();
188194
});
189195

196+
it('opens no record when the drill is closed while its result is read', async () => {
197+
const { ds, openRecord, onClose, releaseIdReads, close } = mountPaged(ALL, 2, { holdIdReads: true });
198+
const dialog = await screen.findByTestId('drill-down-dialog');
199+
await within(dialog).findByText('Acme');
200+
await act(async () => fireEvent.click(within(dialog).getByText('Acme')));
201+
await waitFor(() => expect(idReads(ds).length).toBeGreaterThan(0));
202+
203+
// The reader closes the drill (Esc, an outside click) before the ids come back.
204+
act(() => close());
205+
await waitFor(() => expect(screen.queryByTestId('drill-down-dialog')).toBeNull());
206+
await act(async () => { releaseIdReads(); await Promise.resolve(); });
207+
await new Promise((resolve) => setTimeout(resolve, 0));
208+
expect(openRecord).not.toHaveBeenCalled();
209+
expect(onClose).not.toHaveBeenCalled();
210+
});
211+
212+
it('opens no record when the drill is gone while its result is read', async () => {
213+
const { ds, openRecord, onClose, releaseIdReads, unmount } = mountPaged(ALL, 2, { holdIdReads: true });
214+
const dialog = await screen.findByTestId('drill-down-dialog');
215+
await within(dialog).findByText('Acme');
216+
await act(async () => fireEvent.click(within(dialog).getByText('Acme')));
217+
await waitFor(() => expect(idReads(ds).length).toBeGreaterThan(0));
218+
219+
unmount();
220+
await act(async () => { releaseIdReads(); await Promise.resolve(); });
221+
await new Promise((resolve) => setTimeout(resolve, 0));
222+
expect(openRecord).not.toHaveBeenCalled();
223+
expect(onClose).not.toHaveBeenCalled();
224+
});
225+
226+
it('opens the record clicked last when a second record is clicked while the first is read', async () => {
227+
const { openRecord, releaseIdReads } = mountPaged(ALL, 2, { holdIdReads: true });
228+
const dialog = await screen.findByTestId('drill-down-dialog');
229+
await within(dialog).findByText('Deal 2');
230+
await act(async () => fireEvent.click(within(dialog).getByText('Acme')));
231+
await act(async () => fireEvent.click(within(dialog).getByText('Deal 2')));
232+
await act(async () => { releaseIdReads(); await Promise.resolve(); });
233+
await waitFor(() => expect(openRecord).toHaveBeenCalled());
234+
await new Promise((resolve) => setTimeout(resolve, 0));
235+
expect(openRecord).toHaveBeenCalledTimes(1);
236+
expect(openRecord.mock.calls[0][1]).toBe('d2');
237+
expect(openRecord.mock.calls[0][2]).toEqual({ siblings: ALL.map((row) => row.id), total: 40 });
238+
});
239+
190240
it('control: a drill whose result is all drawn hands those rows and reads nothing more', async () => {
191241
const { ds, openRecord } = mountPaged(ALL.slice(0, 3), 10);
192242
const dialog = await screen.findByTestId('drill-down-dialog');

‎ui/packages/plugin-dashboard/src/DrillDownDrawer.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ export const DrillDownDrawer: React.FC<DrillDownDrawerProps> = ({
257257
maxRows={maxRows}
258258
dataSource={dataSource}
259259
onNavigate={onClose}
260+
open={open}
260261
/>
261262
)
262263
: (

‎ui/packages/plugin-dashboard/src/DrillRecordList.tsx‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,11 @@ export interface DrillRecordListProps {
6464
dataSource?: any;
6565
/** Called after the host opened a record's page. */
6666
onNavigate?: () => void;
67+
/**
68+
* Whether the drill's dialog is open (default: open). A record whose step
69+
* set is still being read when it closes is not opened.
70+
*/
71+
open?: boolean;
6772
}
6873

6974
type Summary = string | Record<string, unknown>;
@@ -84,6 +89,7 @@ export const DrillRecordList: React.FC<DrillRecordListProps> = ({
8489
maxRows,
8590
dataSource: ownDataSource,
8691
onNavigate,
92+
open: dialogOpen = true,
8793
}) => {
8894
const context = React.useContext(SchemaRendererContext);
8995
const dataSource = ownDataSource ?? context?.dataSource;
@@ -124,8 +130,14 @@ export const DrillRecordList: React.FC<DrillRecordListProps> = ({
124130
total?: number;
125131
findParams?: Readonly<Record<string, unknown>> | null;
126132
}>({ ids: [] });
127-
// One record page at a time: a second click while the step set is read is dropped.
128-
const opening = React.useRef(false);
133+
// The record a click asks for while its step set is read: the last click
134+
// wins, and none opens once the drill is closed or gone (objectstack#36554).
135+
const lastOpen = React.useRef(0);
136+
const live = React.useRef(dialogOpen);
137+
React.useLayoutEffect(() => {
138+
live.current = dialogOpen;
139+
return () => { live.current = false; };
140+
}, [dialogOpen]);
129141
const [opened, setOpened] = React.useState<Record<string, unknown> | null>(null);
130142

131143
const baseColumns = React.useMemo(() => {
@@ -189,16 +201,17 @@ export const DrillRecordList: React.FC<DrillRecordListProps> = ({
189201
onRowClick={(record: Record<string, unknown>) => {
190202
if (!openRecord) return setOpened(record);
191203
const id = rowId(record);
192-
if (!id || opening.current) return;
204+
if (!id) return;
205+
const click = ++lastOpen.current;
193206
const open = (origin: DrillRecordOrigin) => {
207+
if (click !== lastOpen.current || !live.current) return;
194208
openRecord(objectName, id, origin);
195209
onNavigate?.();
196210
};
197211
const { ids, total, findParams } = shown.current;
198212
const origin = drillRecordOrigin({ dataSource, objectName, recordId: id, drawn: ids, total, findParams });
199-
if (!(origin instanceof Promise)) return open(origin);
200-
opening.current = true;
201-
void origin.then(open).finally(() => { opening.current = false; });
213+
if (origin instanceof Promise) void origin.then(open);
214+
else open(origin);
202215
}}
203216
/>
204217
{!openRecord && (

‎ui/packages/plugin-dashboard/src/__tests__/drillRecordSteps-36554.test.ts‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ describe('drillRecordOrigin (#36554)', () => {
4242
expect(object).toBe('deal');
4343
expect(params).toEqual({
4444
$filter: QUERY.$filter,
45-
$orderby: QUERY.$orderby,
45+
// The list's sort, with the record id as the last tiebreaker.
46+
$orderby: [...QUERY.$orderby, { field: 'id', order: 'asc' }],
4647
$search: 'acme',
4748
$searchFields: ['name'],
4849
$select: ['id'],
@@ -78,6 +79,57 @@ describe('drillRecordOrigin (#36554)', () => {
7879
expect(ds.find.mock.calls.map(([, params]) => (params as { $top?: number }).$top)).toEqual([250, 250]);
7980
});
8081

82+
it('reads a sort with ties in a stable order: every record once, across windows', async () => {
83+
// 150 deals that all tie on the list's sort, so the result spans two
84+
// windows. Like a database, the source answers ties in no fixed order
85+
// unless the sort settles them: here a later window sees the ties reversed.
86+
const rows = Array.from({ length: 150 }, (_, i) => ({ id: `d${String(i + 1).padStart(3, '0')}`, amount: 1 }));
87+
const ds = {
88+
find: vi.fn(async (_object: string, params: { $top: number; $skip?: number; $orderby?: Array<{ field: string }> }) => {
89+
const skip = params.$skip ?? 0;
90+
const settled = params.$orderby?.[params.$orderby.length - 1]?.field === 'id';
91+
const ordered = settled || skip === 0 ? rows : [...rows].reverse();
92+
return { data: ordered.slice(skip, skip + params.$top).map(({ id }) => ({ id })), total: rows.length };
93+
}),
94+
};
95+
const origin = await drillRecordOrigin({
96+
dataSource: ds, objectName: 'deal', recordId: 'd002', drawn: ['d001', 'd002'], total: 150, findParams: QUERY,
97+
});
98+
expect(ds.find).toHaveBeenCalledTimes(2);
99+
for (const [, params] of ds.find.mock.calls) {
100+
expect(params.$orderby).toEqual([{ field: 'amount', order: 'desc' }, { field: 'id', order: 'asc' }]);
101+
}
102+
expect(origin.siblings).toEqual(rows.map(({ id }) => id));
103+
});
104+
105+
it('sorts by the record id alone when the list has no sort, and keeps an id sort as written', async () => {
106+
const ds = source(40);
107+
const { $orderby: _unsorted, ...noSort } = QUERY;
108+
await drillRecordOrigin({ dataSource: ds, objectName: 'deal', recordId: 'd1', drawn: ['d1', 'd2'], total: 40, findParams: noSort });
109+
expect(ds.find.mock.calls[0][1]).toMatchObject({ $orderby: [{ field: 'id', order: 'asc' }] });
110+
111+
const byId = [{ field: 'id', order: 'desc' }];
112+
await drillRecordOrigin({
113+
dataSource: ds, objectName: 'deal', recordId: 'd1', drawn: ['d1', 'd2'], total: 40, findParams: { ...QUERY, $orderby: byId },
114+
});
115+
expect(ds.find.mock.calls[1][1]).toMatchObject({ $orderby: byId });
116+
});
117+
118+
it('counts a record once when two windows both answer it', async () => {
119+
// A source whose second window starts one row early: the boundary row comes back twice.
120+
const ids = Array.from({ length: 150 }, (_, i) => `d${i + 1}`);
121+
const ds = {
122+
find: vi.fn(async (_object: string, params: { $top: number; $skip?: number }) => {
123+
const skip = Math.max(0, (params.$skip ?? 0) - 1);
124+
return { data: ids.slice(skip, skip + params.$top).map((id) => ({ id })), total: ids.length };
125+
}),
126+
};
127+
const origin = await drillRecordOrigin({
128+
dataSource: ds, objectName: 'deal', recordId: 'd1', drawn: ['d1', 'd2'], total: 150, findParams: QUERY,
129+
});
130+
expect(origin.siblings).toEqual(ids);
131+
});
132+
81133
it('control: a result all drawn reads nothing and hands the rows drawn with the count, at once', () => {
82134
const ds = source(3);
83135
const origin = drillRecordOrigin({
@@ -102,6 +154,7 @@ describe('drillRecordOrigin (#36554)', () => {
102154
});
103155

104156
it('keeps the rows drawn when the read fails or no longer holds the record opened', async () => {
157+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
105158
const failing = { find: vi.fn(async () => { throw new Error('offline'); }) };
106159
expect(await drillRecordOrigin({
107160
dataSource: failing, objectName: 'deal', recordId: 'd1', drawn: ['d1', 'd2'], total: 40, findParams: QUERY,
@@ -111,5 +164,11 @@ describe('drillRecordOrigin (#36554)', () => {
111164
expect(await drillRecordOrigin({
112165
dataSource: moved, objectName: 'deal', recordId: 'gone', drawn: ['gone', 'd2'], total: 40, findParams: QUERY,
113166
})).toEqual({ siblings: ['gone', 'd2'], total: 40 });
167+
// The failure is said once, not on every click.
168+
await drillRecordOrigin({
169+
dataSource: failing, objectName: 'deal', recordId: 'd1', drawn: ['d1', 'd2'], total: 40, findParams: QUERY,
170+
});
171+
expect(warn).toHaveBeenCalledTimes(1);
172+
warn.mockRestore();
114173
});
115174
});

‎ui/packages/plugin-dashboard/src/drillRecordSteps.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ export const DRILL_RECORD_STEP_CAP = 1000;
3434
* The fewest rows one id read asks for: the list's own fetch batch
3535
* (`DEFAULT_LIST_FETCH_BATCH_SIZE` in `@object-ui/plugin-list`), which a host
3636
* already serves to the list itself. A list paged wider asks for its own page.
37+
* A deployment that caps a read's page size or row budget below a window
38+
* (`OS_DATA_MAX_PAGE_SIZE`, `OS_DATA_QUERY_ROW_BUDGET`; neither is set by
39+
* default) refuses the read, and the rows drawn stay the step set.
3740
*/
3841
const MIN_STEP_WINDOW = 100;
3942

@@ -67,6 +70,20 @@ const rowsOf = (result: unknown): Row[] => {
6770
return Array.isArray(data) ? (data as Row[]) : [];
6871
};
6972

73+
/**
74+
* The read's sort with the record id last: the windows are read side by side,
75+
* so a sort with ties (or none) would let a row land in two windows, or in
76+
* none. A sort the list did not write as a field list is kept as written.
77+
*/
78+
const stableOrder = (orderby: unknown): unknown => {
79+
if (orderby == null) return [{ field: 'id', order: 'asc' }];
80+
if (!Array.isArray(orderby)) return orderby;
81+
const last = orderby[orderby.length - 1] as { field?: unknown } | undefined;
82+
return last?.field === 'id' ? orderby : [...orderby, { field: 'id', order: 'asc' }];
83+
};
84+
85+
let failureLogged = false;
86+
7087
const positiveInt = (value: unknown): number | undefined =>
7188
typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined;
7289

@@ -103,6 +120,7 @@ async function readWholeResult(
103120
): Promise<DrillRecordOrigin> {
104121
const query: Record<string, unknown> = { ...findParams };
105122
for (const key of ['$top', '$skip', '$select', '$expand', '$count']) delete query[key];
123+
query.$orderby = stableOrder(findParams.$orderby);
106124
const window = Math.max(positiveInt(findParams.$top) ?? 0, MIN_STEP_WINDOW);
107125
const wanted = Math.min(total, DRILL_RECORD_STEP_CAP);
108126
const windows = Math.ceil(wanted / window);
@@ -111,14 +129,19 @@ async function readWholeResult(
111129
Array.from({ length: windows }, (_, w) =>
112130
ds.find(objectName, { ...query, $select: ['id'], $top: window, ...(w > 0 ? { $skip: w * window } : {}) })),
113131
);
114-
const ids = answers
115-
.flatMap(rowsOf)
116-
.map(idOf)
117-
.filter((id): id is string => !!id)
118-
.slice(0, DRILL_RECORD_STEP_CAP);
132+
const ids = [...new Set(
133+
answers
134+
.flatMap(rowsOf)
135+
.map(idOf)
136+
.filter((id): id is string => !!id),
137+
)].slice(0, DRILL_RECORD_STEP_CAP);
119138
if (!ids.includes(recordId)) return drawnOrigin;
120139
return { siblings: ids, total: Math.max(total, ids.length) };
121-
} catch {
140+
} catch (error) {
141+
if (!failureLogged) {
142+
failureLogged = true;
143+
console.warn('[drill] the drill\'s whole result could not be read; the record steps through the rows drawn.', error);
144+
}
122145
return drawnOrigin;
123146
}
124147
}

0 commit comments

Comments
 (0)