Skip to content
Merged
10 changes: 10 additions & 0 deletions .changeset/37212-drawer-body-table-column-cap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/plugin-detail': patch
---

fix(plugin-detail): a related table in the record preview drawer draws instead of failing with "Maximum update depth exceeded"

Clause-②: no
Metadata-protocol: none

A record's related table drawn in the details of the record preview drawer (for example an opportunity's line items) could fail with `Component "data-table" failed to render` and React error #185, while the record's full page drew the same table. The table leaves out the columns that do not fit whole in its column, and re-reads that choice when it changes. The re-read measured the table still drawn for the previous choice, because the table adopts a new set of columns a render later. In the drawer's narrow details column that read changed its answer on every render: one column, then two, then one again. The read now skips the table while it still draws the columns it was handed before, and reads again when the table draws the new ones. A column the reader hid from the table's header menu does not stop the read, so a later narrowing still leaves columns out and shows the overflow cue. A table wide enough for every column, as on the full page, is unchanged.
17 changes: 16 additions & 1 deletion ui/packages/plugin-detail/src/RelatedList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3665,13 +3665,17 @@ export const RelatedList: React.FC<RelatedListProps> = ({
// key, so a column left out is still counted when the box grows.
const [bodyTableColumnCap, setBodyTableColumnCap] = React.useState<number | null>(null);
const bodyTableColumnWidths = React.useRef(new Map<string, number>());
// objectstack#37212 — how many columns the table last drew as handed: a
// hand-over it has adopted. `null` until it has drawn one.
const bodyTableAdoptedCount = React.useRef<number | null>(null);
const bodyTableColumnKeysKey = React.useMemo(
() => JSON.stringify((tableColumns ?? []).map((col: any) => String(col?.accessorKey ?? ''))),
[tableColumns],
);
// A different column set is measured afresh, every column drawn.
React.useLayoutEffect(() => {
bodyTableColumnWidths.current.clear();
bodyTableAdoptedCount.current = null;
setBodyTableColumnCap(null);
}, [bodyTableColumnKeysKey]);
const bodyTableColumnsOmitted = bodyTable && bodyTableColumnCap !== null;
Expand Down Expand Up @@ -4077,6 +4081,17 @@ export const RelatedList: React.FC<RelatedListProps> = ({
const keys = readColumnKeys(bodyTableColumnKeysKey);
const watch = (box: HTMLElement) => {
const read = () => {
// objectstack#37212 — the table adopts the columns it is handed a
// render later. While it still draws the hand-over it adopted last (the
// same leading run of these columns), it is measured for that cap, not
// this one, and judging this cap by it flips the cap on every commit:
// skip that read; its re-draw reads again. A table that draws a run of
// its own choosing (a column hidden from its header menu) is read.
const drawn = Array.from(box.querySelectorAll('thead th[data-column-key]'), (th) => th.getAttribute('data-column-key'));
const handed = bodyTableColumnCap ?? keys.length;
const leadingRun = drawn.every((key, index) => key === keys[index]);
if (leadingRun && drawn.length === handed) bodyTableAdoptedCount.current = handed;
else if (leadingRun && drawn.length === bodyTableAdoptedCount.current) return;
// objectstack#35742 — the columns that fit whole: the box's width
// less the cells that are no column (the row actions), against the
// width each column asks for.
Expand All @@ -4096,7 +4111,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setBodyTableOverflows(box.scrollWidth - box.clientWidth > 1);
};
read();
// The table settles its columns a render after it is handed fewer:
// The table settles its columns a render after it is handed others:
// read again when its cells change.
if (typeof MutationObserver !== 'undefined') {
cells = new MutationObserver(read);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
* an empty body table draws its headers and one empty row with the add entry.
*/
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
import { RecordContextProvider } from '@object-ui/react';
Expand Down Expand Up @@ -634,3 +634,165 @@ describe('RelatedList — a body table draws the list\'s dense rows (objectstack
expect(tableRoot()?.className ?? '').not.toContain('[&_tbody_td]:h-8');
});
});

describe('RelatedList — a body table in the record preview drawer settles its columns (objectstack#37212)', () => {
// The preview drawer opens 460 px wide, which leaves its details column a
// 326 px scroll box: the width at which this list's column cap read the
// table data-table drew for the PREVIOUS cap (data-table adopts a new
// `columns` prop a commit later) and flipped 1 -> 2 -> 1 until React gave
// up with "Maximum update depth exceeded" (#185). The full page's details
// column is wide enough that nothing is left out, so it never flipped.
//
// The layout below is the browser's, reduced to what the cap reads: a data
// header cell is as wide as its inline min-width (else its own natural
// width), the row-actions cell is 66 px, and a table narrower than its box
// stretches to fill it, the actions cell taking its share.
const ACTIONS_PX = 66;
const NATURAL_PX: Record<string, number> = { product: 104, tier: 156, quantity: 112, total: 120 };
let boxPx = 326;
const proto = HTMLElement.prototype;
const saved = {
scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'),
clientWidth: Object.getOwnPropertyDescriptor(proto, 'clientWidth'),
getBoundingClientRect: Object.getOwnPropertyDescriptor(proto, 'getBoundingClientRect'),
};
const dataCellPx = (th: HTMLElement) =>
parseFloat(th.style.minWidth) || NATURAL_PX[th.getAttribute('data-column-key') ?? ''] || 0;
const tableOf = (box: HTMLElement) => {
const heads = Array.from(box.querySelectorAll<HTMLElement>('thead th[data-column-key]'));
const data = heads.reduce((sum, th) => sum + dataCellPx(th), 0);
const natural = data + ACTIONS_PX;
const stretch = Math.max(0, boxPx - natural);
return { natural, actionsPx: ACTIONS_PX + (stretch * ACTIONS_PX) / natural };
};
beforeAll(() => {
Object.defineProperty(proto, 'clientWidth', {
configurable: true,
get(this: HTMLElement) {
return this.hasAttribute('data-table-scroll-box') ? boxPx : 0;
},
});
Object.defineProperty(proto, 'scrollWidth', {
configurable: true,
get(this: HTMLElement) {
return this.hasAttribute('data-table-scroll-box') ? Math.max(boxPx, tableOf(this).natural) : 0;
},
});
Object.defineProperty(proto, 'getBoundingClientRect', {
configurable: true,
value(this: HTMLElement) {
const box = this.tagName === 'TH' ? this.closest<HTMLElement>('[data-table-scroll-box]') : null;
const width = !box ? 0 : this.hasAttribute('data-column-key') ? dataCellPx(this) : tableOf(box).actionsPx;
return { x: 0, y: 0, top: 0, left: 0, bottom: 0, right: width, width, height: 0, toJSON() {} } as DOMRect;
},
});
});
afterAll(() => {
for (const [key, descriptor] of Object.entries(saved)) {
if (descriptor) Object.defineProperty(proto, key, descriptor);
else delete (proto as any)[key];
}
});
afterEach(() => {
boxPx = 326;
vi.restoreAllMocks();
});

// The first column's cells store a long value and draw a short label, so the
// table's first estimate of it (from the stored value) is wider than the
// width it asks for once drawn — the move that set the cap flipping.
const lineFields = {
product: {
type: 'select',
label: 'Product',
options: [{ value: 'enterprise_license_annual_plan', label: 'License' }],
},
tier: { type: 'text', label: 'Tier level' },
quantity: { type: 'number', label: 'Quantity' },
total: { type: 'currency', label: 'Total', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } },
};
const lineRows = [
{ id: 'l1', product: 'enterprise_license_annual_plan', tier: 'ent', quantity: 2, total: 20 },
{ id: 'l2', product: 'enterprise_license_annual_plan', tier: 'std', quantity: 3, total: 45 },
];

function renderLines() {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<RecordBodyTablesContext.Provider value={new Set(['opportunity_line_item.opportunity'])}>
<RelatedEnlargeContext.Provider value={vi.fn()}>
<RelatedList
title="Line items"
type="table"
api="opportunity_line_item"
objectName="opportunity_line_item"
referenceField="opportunity"
parentId="o1"
columns={Object.keys(lineFields).map((field) => ({ field, label: (lineFields as any)[field].label }))}
onRowEdit={vi.fn()}
dataSource={{
// The rows arrive from the data source after the schema, as in
// the drawer: the table first draws them in the commit whose
// read first measures it.
find: vi.fn(() => new Promise((resolve) => setTimeout(() => resolve(lineRows), 20))),
getObjectSchema: vi.fn(async () => ({ name: 'opportunity_line_item', fields: lineFields })),
} as any}
/>
</RelatedEnlargeContext.Provider>
</RecordBodyTablesContext.Provider>,
);
return errors;
}
const headerKeys = () =>
Array.from(document.querySelectorAll('thead th[data-column-key]')).map((th) => th.getAttribute('data-column-key'));
const updateDepthErrors = (errors: { mock: { calls: unknown[][] } }) =>
errors.mock.calls.filter((call: unknown[]) => /Maximum update depth|#185/.test(call.map(String).join(' ')));

it('in the 326 px details column of the 460 px preview: the table draws, and the cap settles on a leading run of the columns', async () => {
const errors = renderLines();
await waitFor(() => expect(document.querySelector('[data-body-table-columns-omitted]')).not.toBeNull());
// Let every read the table's re-draws trigger run out.
await new Promise((resolve) => setTimeout(resolve, 50));
expect(screen.queryByText(/failed to render/i)).toBeNull();
expect(updateDepthErrors(errors)).toEqual([]);
// Settled: what the list hands is what the table draws, a leading run.
const host = document.querySelector('[data-body-table-overflow]') as HTMLElement;
const omitted = Number(host.getAttribute('data-body-table-columns-omitted'));
const keys = Object.keys(lineFields);
expect(headerKeys()).toEqual(keys.slice(0, keys.length - omitted));
expect(screen.getAllByText('License').length).toBeGreaterThan(0);
});

it('a column hidden from the header menu is the table\'s own choice: a later narrowing is still read (cap and overflow cue)', async () => {
boxPx = 1052;
renderLines();
await waitFor(() => expect(headerKeys()).toEqual(Object.keys(lineFields)));
const total = document.querySelector('thead th[data-column-key="total"]') as HTMLElement;
fireEvent.contextMenu(total);
fireEvent.click(await screen.findByText('Hide column'));
await waitFor(() => expect(headerKeys()).toEqual(['product', 'tier', 'quantity']));
const host = document.querySelector('[data-body-table-overflow]') as HTMLElement;
expect(host.hasAttribute('data-body-table-columns-omitted')).toBe(false);
// Narrowed to the drawer's details column. jsdom reports no resize; a
// change of the box's content asks the read the same question.
boxPx = 326;
const box = document.querySelector('[data-table-scroll-box]') as HTMLElement;
act(() => {
box.appendChild(document.createElement('span'));
});
await waitFor(() => expect(host.getAttribute('data-body-table-columns-omitted')).not.toBeNull());
expect(headerKeys().length).toBeLessThan(3);
expect(host.getAttribute('data-body-table-overflow')).toBe('true');
});

it('CONTROL — the full page\'s wide details column: every column drawn, none left out, no error', async () => {
boxPx = 1052;
const errors = renderLines();
await waitFor(() => expect(screen.getAllByText('License').length).toBeGreaterThan(0));
await new Promise((resolve) => setTimeout(resolve, 50));
expect(screen.queryByText(/failed to render/i)).toBeNull();
expect(updateDepthErrors(errors)).toEqual([]);
expect(document.querySelector('[data-body-table-columns-omitted]')).toBeNull();
expect(headerKeys()).toEqual(Object.keys(lineFields));
});
});
Loading