Skip to content

Commit 057cedf

Browse files
fix(plugin-detail): a related table in the record preview drawer draws instead of looping on its column cap (#37244)
Part of #37212 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在列表右侧预览抽屉里打开记录时,「详情」中的相关子表(如商机的产品明细)正常显示,不再报「组件渲染失败」;完整记录页不变。 - 为什么做:产品负责人报告的高优先级缺陷。抽屉的详情栏很窄,子表要决定显示几列;它测量时读到的是上一次的表格,于是在「1 列」和「2 列」之间来回切换,直到浏览器报无限更新。该问题只在 18.6.0 之后构建的控制台里出现,所以本合并不直接关卡,待租户实际使用的控制台版本确认后再关。 - 出错会怎样:只影响窄栏子表决定列数的时机;最坏是窄栏里显示的列数不对,或隐藏某列后再缩窄时表格被截断且没有「全部列」提示。数据不受影响,可直接撤回本改动。 - 要你做什么:无 ## What changes **Root cause.** A related list drawn as a record's body table (the 「详情」 section's master-detail table) leaves out the trailing columns that do not fit whole in its column, through the `bodyTableColumnCap` state in `RelatedList`. The layout effect that reads the cap lists the cap itself in its deps ("re-read once the table draws the columns that fit"), so every cap change re-reads synchronously, in the same commit chain. But `data-table` adopts a new `columns` prop one render later: it copies the prop into its own state in an effect. So the re-read measures the table still drawn for the previous cap. The columns already handed away carry no inline min-width there, so the read also falls back to their stale pre-draw estimates. At the preview drawer's default 460 px width, the details column is a 326 px scroll box. Measured in the browser on the CRM example (opportunity, line items with a lookup, a select, a percent and a text column added): - Cap 1 handed, six columns still drawn: the actions cell sits at its natural 66 px, so the read says 2 fit. - Cap 2 handed, one column still drawn: the table stretches and the actions cell is 118 px, so the read says 1 fits. That repeats every commit until React stops it with `Maximum update depth exceeded` (React error 185). data-table's own layout effects run first in each commit, so its error boundary takes the throw and reports `Component "data-table" failed to render`. The full page's details column fits every column, so the cap never moves there. **Fix** (`ui/packages/plugin-detail/src/RelatedList.tsx`, the body-table read): - The list records, in a ref, how many columns the table last drew exactly as handed: the hand-over it has adopted. - A read is skipped only while the table still draws that adopted count (the same leading run of the list's columns), but a different count was handed. That is the one-render adoption lag. The existing cells `MutationObserver` reads again when the table re-draws. - A table that draws a run of its own choosing is still read, for example after "Hide column" from its header menu. So a later narrowing still leaves columns out and shows the overflow cue, as on main. - The adopted count resets with the widths when the list's column set changes. Edited files: `ui/packages/plugin-detail/src/RelatedList.tsx`, `ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx`, `.changeset/37212-drawer-body-table-column-cap.md`. `recordDrawerStack.tsx` and `data-table.tsx` are untouched. **Which builds carry the defect.** The cap and its self-triggering read arrived with `d19d87529d` (2026-11-20). Master-detail children became 「详情」 body tables by default with `9b6db730b2`, and the side preview opened 460 wide with `aad35e6885`. - `@object-ui/*@18.6.0` / `@objectstack/console@18.6.0` resolve to `958ee03594`, which has none of these. `git merge-base --is-ancestor d19d875 958ee03` exits 1. The control leg `958ee03594~5` exits 0. `RelatedList.tsx` there has no `bodyTableColumnCap`, and its one body-table effect has deps `[bodyTableDrawn, isMobile]`. - At `958ee03594` I booted the CRM example and drove the preview drawer with stock line items and with the widened shape, at the default width and at 380 to 800 px. There was no React error 185 at any width: the body table draws every column and scrolls. - The npm `next` build `0.0.0-next-20261125013212` has `gitHead` `a1b26ff907` (2026-11-25T00:16Z) for `@objectstack/console`, `@object-ui/console` and `@object-ui/plugin-detail`. `d19d87529d` is an ancestor of it (exit 0), and its `RelatedList.tsx` and `data-table.tsx` are identical to this PR's base. - Two hotcrm-lane cards filed today, from the same product owner's reports, measured a booted HotCRM on server 18.6.0 with that console. The card's own text does not name the tenant's console build. **Closing arrangement.** This PR is the platform half. The card stays open until a reading on the reporting tenant names its console build (the build's version, or its `gitHead` containing `d19d87529d`). Then, after a console carrying this change is installed there, it needs a second reading that the opportunity line items draw in the preview drawer's 「详情」. The card closes on that reading. **Responsibility.** Whose code: the platform's own console code (the `@object-ui/plugin-detail` related list's body table, drawn by `@object-ui/components` `data-table` inside the `@object-ui/app-shell` record preview drawer). Existing platform path: none, since the full page draws the same table fine. Who reaches it: every user who opens a record with a related body table in the preview drawer, on a console built after 2026-11-20, at a width where the cap sits between column counts (the default 460 px with the line items above). ## Tests Three cases in a top-level `describe` in the existing body-table harness, `RelatedList.bodyTable-27055.test.tsx`: "RelatedList — a body table in the record preview drawer settles its columns (objectstack#37212)". They model the 326 px details column, where a table narrower than its box stretches and the actions cell takes its share. The real data-table is used, so its one-render column lag is the real one, and the rows arrive from the data source as in the drawer. - **Drawer case:** the table draws with no error boundary text and no update-depth error, and settles on a leading run of the columns. Red on the unfixed read, green after. - **Hide then narrow:** - At 1052 px, "Hide column" on the trailing column. The table then draws three columns and omits none. - Narrowed to 326 px, the read still runs: columns are left out and the overflow cue is set. Red with round 0's guard, green after. - **Full-page control** (1052 px): every column drawn, none left out, no error. Green throughout. <details><summary>Readings</summary> - Round 0, red on unfixed main (`35079023b0`): the drawer case failed with the error boundary's text in the DOM, and the control passed. - Both body-table harness files at `e1b242fed2` (after merging `origin/main`, closure rebuilt): `Test Files 2 passed (2)`, `Tests 41 passed (41)`. - Ablation A1, the lag skip removed via `scripts/ablation-replace.mjs`: - The anchor went 1 -> 0, blob `c199589f7aa5` -> `4b691f714dd4`. - Result: `Tests 1 failed | 2 passed | 32 skipped (35)`; the red is the drawer case. - Restored: blob == HEAD `c199589f7aa5`, `git diff HEAD` empty. - Ablation A2, round 0's guard put back: - The anchor went 1 -> 0, blob `c199589f7aa5` -> `09c590c4173a`. - Result: `Tests 1 failed | 2 passed | 32 skipped (35)`; the red is the hide-then-narrow case. - Restored: blob == HEAD `c199589f7aa5`, `git diff HEAD` empty. - `@object-ui/plugin-detail` at `4008830387`: `pnpm --filter @object-ui/plugin-detail type-check` exit 0. Whole package (`pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-detail/`): `Test Files 418 passed | 1 skipped (419)`, `Tests 3949 passed | 18 skipped (3967)`. </details> ## Acceptance notes - **Browser on main** (Console from `ui/` source over Vite against my own CRM backend, line items widened as above), drawer width swept 380 to 800 px: - Before: React error 185 and `failed to render` at 460 px only. - After: every width draws the table, with no console error. The full page draws all six columns. - The stock three-column CRM line item does not reproduce on main. - The widened columns were a temporary local edit, reverted, not part of this PR. - **The 326 px settle is path-dependent, and this PR does not change that.** On open it settles at one column. After a widen-then-narrow it can settle at two, because the read counts the actions cell's stretched width as room the row actions need. The drawer pin asserts a leading run, not a particular count. - **Underlying property, left as is:** data-table adopts a new `columns` prop a render later (its re-seed runs in an effect). Changing that would move every table's column timing. ## Verification Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx -t "settles its columns"` expects `3 passed`. Read first, by risk: 1. `RelatedList.tsx`, the two guard lines at the top of the body-table `read` and the adopted-count ref beside the column widths (the only runtime change). 2. The new `describe` at the end of `RelatedList.bodyTable-27055.test.tsx` (the layout model and the hide-then-narrow case). 3. `.changeset/37212-drawer-body-table-column-cap.md`. Security: none. --- _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>
1 parent 8032d95 commit 057cedf

3 files changed

Lines changed: 189 additions & 2 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-detail': patch
3+
---
4+
5+
fix(plugin-detail): a related table in the record preview drawer draws instead of failing with "Maximum update depth exceeded"
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.

‎ui/packages/plugin-detail/src/RelatedList.tsx‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3665,13 +3665,17 @@ export const RelatedList: React.FC<RelatedListProps> = ({
36653665
// key, so a column left out is still counted when the box grows.
36663666
const [bodyTableColumnCap, setBodyTableColumnCap] = React.useState<number | null>(null);
36673667
const bodyTableColumnWidths = React.useRef(new Map<string, number>());
3668+
// objectstack#37212 — how many columns the table last drew as handed: a
3669+
// hand-over it has adopted. `null` until it has drawn one.
3670+
const bodyTableAdoptedCount = React.useRef<number | null>(null);
36683671
const bodyTableColumnKeysKey = React.useMemo(
36693672
() => JSON.stringify((tableColumns ?? []).map((col: any) => String(col?.accessorKey ?? ''))),
36703673
[tableColumns],
36713674
);
36723675
// A different column set is measured afresh, every column drawn.
36733676
React.useLayoutEffect(() => {
36743677
bodyTableColumnWidths.current.clear();
3678+
bodyTableAdoptedCount.current = null;
36753679
setBodyTableColumnCap(null);
36763680
}, [bodyTableColumnKeysKey]);
36773681
const bodyTableColumnsOmitted = bodyTable && bodyTableColumnCap !== null;
@@ -4077,6 +4081,17 @@ export const RelatedList: React.FC<RelatedListProps> = ({
40774081
const keys = readColumnKeys(bodyTableColumnKeysKey);
40784082
const watch = (box: HTMLElement) => {
40794083
const read = () => {
4084+
// objectstack#37212 — the table adopts the columns it is handed a
4085+
// render later. While it still draws the hand-over it adopted last (the
4086+
// same leading run of these columns), it is measured for that cap, not
4087+
// this one, and judging this cap by it flips the cap on every commit:
4088+
// skip that read; its re-draw reads again. A table that draws a run of
4089+
// its own choosing (a column hidden from its header menu) is read.
4090+
const drawn = Array.from(box.querySelectorAll('thead th[data-column-key]'), (th) => th.getAttribute('data-column-key'));
4091+
const handed = bodyTableColumnCap ?? keys.length;
4092+
const leadingRun = drawn.every((key, index) => key === keys[index]);
4093+
if (leadingRun && drawn.length === handed) bodyTableAdoptedCount.current = handed;
4094+
else if (leadingRun && drawn.length === bodyTableAdoptedCount.current) return;
40804095
// objectstack#35742 — the columns that fit whole: the box's width
40814096
// less the cells that are no column (the row actions), against the
40824097
// width each column asks for.
@@ -4096,7 +4111,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
40964111
setBodyTableOverflows(box.scrollWidth - box.clientWidth > 1);
40974112
};
40984113
read();
4099-
// The table settles its columns a render after it is handed fewer:
4114+
// The table settles its columns a render after it is handed others:
41004115
// read again when its cells change.
41014116
if (typeof MutationObserver !== 'undefined') {
41024117
cells = new MutationObserver(read);

‎ui/packages/plugin-detail/src/__tests__/RelatedList.bodyTable-27055.test.tsx‎

Lines changed: 163 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
* an empty body table draws its headers and one empty row with the add entry.
2626
*/
2727
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
28-
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
28+
import { act, render, screen, waitFor, fireEvent } from '@testing-library/react';
2929
import '@testing-library/jest-dom';
3030
import React from 'react';
3131
import { RecordContextProvider } from '@object-ui/react';
@@ -634,3 +634,165 @@ describe('RelatedList — a body table draws the list\'s dense rows (objectstack
634634
expect(tableRoot()?.className ?? '').not.toContain('[&_tbody_td]:h-8');
635635
});
636636
});
637+
638+
describe('RelatedList — a body table in the record preview drawer settles its columns (objectstack#37212)', () => {
639+
// The preview drawer opens 460 px wide, which leaves its details column a
640+
// 326 px scroll box: the width at which this list's column cap read the
641+
// table data-table drew for the PREVIOUS cap (data-table adopts a new
642+
// `columns` prop a commit later) and flipped 1 -> 2 -> 1 until React gave
643+
// up with "Maximum update depth exceeded" (#185). The full page's details
644+
// column is wide enough that nothing is left out, so it never flipped.
645+
//
646+
// The layout below is the browser's, reduced to what the cap reads: a data
647+
// header cell is as wide as its inline min-width (else its own natural
648+
// width), the row-actions cell is 66 px, and a table narrower than its box
649+
// stretches to fill it, the actions cell taking its share.
650+
const ACTIONS_PX = 66;
651+
const NATURAL_PX: Record<string, number> = { product: 104, tier: 156, quantity: 112, total: 120 };
652+
let boxPx = 326;
653+
const proto = HTMLElement.prototype;
654+
const saved = {
655+
scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'),
656+
clientWidth: Object.getOwnPropertyDescriptor(proto, 'clientWidth'),
657+
getBoundingClientRect: Object.getOwnPropertyDescriptor(proto, 'getBoundingClientRect'),
658+
};
659+
const dataCellPx = (th: HTMLElement) =>
660+
parseFloat(th.style.minWidth) || NATURAL_PX[th.getAttribute('data-column-key') ?? ''] || 0;
661+
const tableOf = (box: HTMLElement) => {
662+
const heads = Array.from(box.querySelectorAll<HTMLElement>('thead th[data-column-key]'));
663+
const data = heads.reduce((sum, th) => sum + dataCellPx(th), 0);
664+
const natural = data + ACTIONS_PX;
665+
const stretch = Math.max(0, boxPx - natural);
666+
return { natural, actionsPx: ACTIONS_PX + (stretch * ACTIONS_PX) / natural };
667+
};
668+
beforeAll(() => {
669+
Object.defineProperty(proto, 'clientWidth', {
670+
configurable: true,
671+
get(this: HTMLElement) {
672+
return this.hasAttribute('data-table-scroll-box') ? boxPx : 0;
673+
},
674+
});
675+
Object.defineProperty(proto, 'scrollWidth', {
676+
configurable: true,
677+
get(this: HTMLElement) {
678+
return this.hasAttribute('data-table-scroll-box') ? Math.max(boxPx, tableOf(this).natural) : 0;
679+
},
680+
});
681+
Object.defineProperty(proto, 'getBoundingClientRect', {
682+
configurable: true,
683+
value(this: HTMLElement) {
684+
const box = this.tagName === 'TH' ? this.closest<HTMLElement>('[data-table-scroll-box]') : null;
685+
const width = !box ? 0 : this.hasAttribute('data-column-key') ? dataCellPx(this) : tableOf(box).actionsPx;
686+
return { x: 0, y: 0, top: 0, left: 0, bottom: 0, right: width, width, height: 0, toJSON() {} } as DOMRect;
687+
},
688+
});
689+
});
690+
afterAll(() => {
691+
for (const [key, descriptor] of Object.entries(saved)) {
692+
if (descriptor) Object.defineProperty(proto, key, descriptor);
693+
else delete (proto as any)[key];
694+
}
695+
});
696+
afterEach(() => {
697+
boxPx = 326;
698+
vi.restoreAllMocks();
699+
});
700+
701+
// The first column's cells store a long value and draw a short label, so the
702+
// table's first estimate of it (from the stored value) is wider than the
703+
// width it asks for once drawn — the move that set the cap flipping.
704+
const lineFields = {
705+
product: {
706+
type: 'select',
707+
label: 'Product',
708+
options: [{ value: 'enterprise_license_annual_plan', label: 'License' }],
709+
},
710+
tier: { type: 'text', label: 'Tier level' },
711+
quantity: { type: 'number', label: 'Quantity' },
712+
total: { type: 'currency', label: 'Total', currencyConfig: { currencyMode: 'fixed', defaultCurrency: 'USD' } },
713+
};
714+
const lineRows = [
715+
{ id: 'l1', product: 'enterprise_license_annual_plan', tier: 'ent', quantity: 2, total: 20 },
716+
{ id: 'l2', product: 'enterprise_license_annual_plan', tier: 'std', quantity: 3, total: 45 },
717+
];
718+
719+
function renderLines() {
720+
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
721+
render(
722+
<RecordBodyTablesContext.Provider value={new Set(['opportunity_line_item.opportunity'])}>
723+
<RelatedEnlargeContext.Provider value={vi.fn()}>
724+
<RelatedList
725+
title="Line items"
726+
type="table"
727+
api="opportunity_line_item"
728+
objectName="opportunity_line_item"
729+
referenceField="opportunity"
730+
parentId="o1"
731+
columns={Object.keys(lineFields).map((field) => ({ field, label: (lineFields as any)[field].label }))}
732+
onRowEdit={vi.fn()}
733+
dataSource={{
734+
// The rows arrive from the data source after the schema, as in
735+
// the drawer: the table first draws them in the commit whose
736+
// read first measures it.
737+
find: vi.fn(() => new Promise((resolve) => setTimeout(() => resolve(lineRows), 20))),
738+
getObjectSchema: vi.fn(async () => ({ name: 'opportunity_line_item', fields: lineFields })),
739+
} as any}
740+
/>
741+
</RelatedEnlargeContext.Provider>
742+
</RecordBodyTablesContext.Provider>,
743+
);
744+
return errors;
745+
}
746+
const headerKeys = () =>
747+
Array.from(document.querySelectorAll('thead th[data-column-key]')).map((th) => th.getAttribute('data-column-key'));
748+
const updateDepthErrors = (errors: { mock: { calls: unknown[][] } }) =>
749+
errors.mock.calls.filter((call: unknown[]) => /Maximum update depth|#185/.test(call.map(String).join(' ')));
750+
751+
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 () => {
752+
const errors = renderLines();
753+
await waitFor(() => expect(document.querySelector('[data-body-table-columns-omitted]')).not.toBeNull());
754+
// Let every read the table's re-draws trigger run out.
755+
await new Promise((resolve) => setTimeout(resolve, 50));
756+
expect(screen.queryByText(/failed to render/i)).toBeNull();
757+
expect(updateDepthErrors(errors)).toEqual([]);
758+
// Settled: what the list hands is what the table draws, a leading run.
759+
const host = document.querySelector('[data-body-table-overflow]') as HTMLElement;
760+
const omitted = Number(host.getAttribute('data-body-table-columns-omitted'));
761+
const keys = Object.keys(lineFields);
762+
expect(headerKeys()).toEqual(keys.slice(0, keys.length - omitted));
763+
expect(screen.getAllByText('License').length).toBeGreaterThan(0);
764+
});
765+
766+
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 () => {
767+
boxPx = 1052;
768+
renderLines();
769+
await waitFor(() => expect(headerKeys()).toEqual(Object.keys(lineFields)));
770+
const total = document.querySelector('thead th[data-column-key="total"]') as HTMLElement;
771+
fireEvent.contextMenu(total);
772+
fireEvent.click(await screen.findByText('Hide column'));
773+
await waitFor(() => expect(headerKeys()).toEqual(['product', 'tier', 'quantity']));
774+
const host = document.querySelector('[data-body-table-overflow]') as HTMLElement;
775+
expect(host.hasAttribute('data-body-table-columns-omitted')).toBe(false);
776+
// Narrowed to the drawer's details column. jsdom reports no resize; a
777+
// change of the box's content asks the read the same question.
778+
boxPx = 326;
779+
const box = document.querySelector('[data-table-scroll-box]') as HTMLElement;
780+
act(() => {
781+
box.appendChild(document.createElement('span'));
782+
});
783+
await waitFor(() => expect(host.getAttribute('data-body-table-columns-omitted')).not.toBeNull());
784+
expect(headerKeys().length).toBeLessThan(3);
785+
expect(host.getAttribute('data-body-table-overflow')).toBe('true');
786+
});
787+
788+
it('CONTROL — the full page\'s wide details column: every column drawn, none left out, no error', async () => {
789+
boxPx = 1052;
790+
const errors = renderLines();
791+
await waitFor(() => expect(screen.getAllByText('License').length).toBeGreaterThan(0));
792+
await new Promise((resolve) => setTimeout(resolve, 50));
793+
expect(screen.queryByText(/failed to render/i)).toBeNull();
794+
expect(updateDepthErrors(errors)).toEqual([]);
795+
expect(document.querySelector('[data-body-table-columns-omitted]')).toBeNull();
796+
expect(headerKeys()).toEqual(Object.keys(lineFields));
797+
});
798+
});

0 commit comments

Comments
 (0)