Skip to content

Commit 647eb92

Browse files
fix(plugin-detail): a record Overview body table keeps the totals of the summed columns it leaves out for width (#36379)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbVF7sWPNE4HmjkgyaVxQYif)_ repo:objectstack#7 · zhuangjianguo · session_01QsR2jRaJbQ4vqdv4J5peqA Fixes #35831 Clause-②: no Metadata-protocol: none ## 维护者速读 - 记录详情「概览」里的子表(如报价明细)放不下所有列时,被收起的金额列的合计现在写在表格下方一行,标着列名、按记录的币种显示;表里看得到的列合计不变,列都放得下的表不多出任何文字。 - 这是记录页概览子表一组工作的后续,解决「金额列因为宽度被收起,合计也跟着从概览上消失」的问题。 - 出错最坏是表格下方那行合计多出或缺少,只影响显示,不碰数据和保存;可直接撤回本改动。 - 无。 ## What changes Arm **(a)** of the card's Done-when: the totals of every left-out summed column stay on screen, labelled with the column's name. Built (a) over (b) because the p1 reason is that money is hidden, (a) keeps the figure visible with no click, and the line it uses is a wrapping flex line (`BodyTableTotalsLine`, the same component the enlarged face already draws its totals with), so it holds any number of labelled totals at the narrowest widths without touching the column measurement. `ui/packages/plugin-detail/src/RelatedList.tsx`, body-table face only: - `bodyOmittedTotals`: the server totals (`useBodyTableTotals`, unchanged) whose column key is in `tableColumns.slice(bodyTableColumnCap)`, the columns `bodyTableColumnsThatFit` left out. Empty whenever nothing is left out, so a table that fits draws nothing new. - Under the table (after the scroll-box host, before the row cap's "Show all N"), `BodyTableTotalsLine` draws those totals: the existing `form.masterDetail.total` lead, then each column's own header label and its figure. The figure is the same `BodyTableTotal.text` the column's summary cell would show, so currency follows exactly what the existing totals follow (fixed code, tenant default, the page record's code for a line amount that follows its parent, grouped `record` codes). The line carries `data-body-table-omitted-totals` instead of `data-body-table-totals`, so the enlarged face's marker keeps its one meaning. - `bodySummaryRow`: unchanged figures, but drawn only while a drawn column has one. With every summed column left out it would be the lead 「合计」 over empty cells; the line then carries all the totals instead. - No new string, no new key, no published export or type change: Clause-② stays `no` as claimed. ## Tests New `RelatedList.bodyTableOmittedTotals-35831.test.tsx` (6), using the stubbed scroll-box widths the body-table face's own pins use: - narrow (680 px): two trailing summed columns left out; the line names `Line amount` (EUR, the page record's currency) and `Tax` (USD) with their totals; the drawn `Unit price` total stays in its column and is not repeated on the line. - a left-out total reads byte-for-byte what the table draws in that column when it fits. - every summed column left out: the line carries them all and no empty totals row is drawn. - CONTROL: a table that leaves nothing out shows no added line and every total in its column. - CONTROL: the drawn columns' totals (and the row's lead) are identical with and without columns left out. - CONTROL: a table that leaves out only unsummed columns shows no added line. On why a new file: AGENTS.md puts a new pin in a component's shared harness file when one exists (ruling record 6583487846). RelatedList has no shared harness file; each `RelatedList.*` test file mounts its own, so this follows the dispatch and the sibling files. <details><summary>Run readings</summary> All readings on objectstack-ai/objectstack, head `51d2c17d` (the code commit `925193b5` plus the changeset commit; no code moved between them), under `scripts/pm/os-verify-lock.sh`, vitest root `ui/`, `--maxWorkers=1`. - New pins plus the body-table face's own and the parent-currency pins (3 files): `Test Files 3 passed (3)`, `Tests 41 passed (41)`, lock `VERDICT command-exit 0`. - Ablation (committed fix first; mutation through `scripts/ablation-replace.mjs`): `bodyOmittedTotals` forced to `[]` (anchor x1 -> x0, marker x0 -> x1, blob 5be8b16 -> 893f3ce8). New file: `Tests 4 failed | 2 passed (6)`. Red: the narrow case, the same-figure case, the every-column-left-out case, and the drawn-totals-unchanged control (it waits for the line first). Green: the fits-whole control and the only-unsummed control. Restored: blob == HEAD 5be8b16, `git diff HEAD` empty. A first attempt was a no-op (the replacement text was inside the anchor) and the tool refused it before running anything. - Every test that mounts `RelatedList` or a body table (85 files: the `RelatedList.*` files in plugin-detail, `RecordDetailView.harness`, `record-related-list.emptyFold-25895`, `buildDefaultPageSchema.bodyTables-27055`): `Test Files 84 passed | 1 skipped (85)`, `Tests 669 passed | 8 skipped (677)`, `VT_EXIT=0`. - `pnpm --filter @object-ui/plugin-detail run type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`): `TC_EXIT=0`. - Not run locally: the rest of the plugin-detail package's 262 test files; `Test UI` runs them. </details> ## Acceptance notes - Not in scope and untouched: the placement order and 33/32 density, and the non-body-table related list. - Docs: no hand-written page under `content/docs/` describes the body table's totals (only the auto-generated references mention body tables), so there is no docs page to update. - Screenshots: NOT MEASURED. No browser run against a dev app in this round; the pins drive the face through jsdom with stubbed widths. ## Verification Read first (by risk): 1. `RelatedList.tsx`, the `bodyOmittedTotals` / `bodySummaryRow` hunk: which totals count as left out, and the summary row's new condition. 2. `RelatedList.tsx`, the `BodyTableTotalsLine` render under the table host. 3. The new test file's narrow case. Two-minute check: `pnpm --dir ui exec vitest run packages/plugin-detail/src/__tests__/RelatedList.bodyTableOmittedTotals-35831.test.tsx`, expect 6 passed. In a running app, open a record whose master-detail body table has more columns than fit in the details column, with a currency column last: under the table a line reads "Total COLUMN-NAME AMOUNT". 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jRaJbQ4vqdv4J5peqA --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 124c934 commit 647eb92

3 files changed

Lines changed: 248 additions & 5 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 record Overview body table keeps the totals of the summed columns it leaves out for width
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On the record page's Overview, a master-detail body table draws only the leading columns that fit whole and leaves the rest behind 「全部列」 / All columns. A summed column left out that way also lost its total, so an amount such as a line total vanished from the Overview only because its column did not fit. The table now draws a line under itself with the total of every summed column it left out, each labelled with the column's name and formatted as that column's own total is (the page record's currency for a line amount that follows its parent). The drawn columns keep their totals in the table's last row, unchanged; when every summed column is left out, that row (which would read 「合计」 over empty cells) is not drawn and the line carries the totals. A table that leaves no summed column out shows no added line. No string is added: the line reuses the existing `form.masterDetail.total` label and the columns' own names.

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

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -979,12 +979,17 @@ function useBodyTableTotals(opts: {
979979
* The totals of a body table as a line under it — the enlarged face's form;
980980
* the table face draws the same figures as the table's own last row, each in
981981
* its column (`summaryRow`). Labelled as the list's total, never as a page's.
982+
* `omitted`: the table face's line for the columns it left out for width
983+
* (objectstack#35831), the same figures under their columns' names.
982984
*/
983-
const BodyTableTotalsLine: React.FC<{ totals: readonly BodyTableTotal[] }> = ({ totals }) => {
985+
const BodyTableTotalsLine: React.FC<{ totals: readonly BodyTableTotal[]; omitted?: boolean }> = ({ totals, omitted }) => {
984986
const { t } = useDetailTranslation();
985987
if (totals.length === 0) return null;
986988
return (
987-
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 border-t pt-2 text-xs" data-body-table-totals="">
989+
<div
990+
className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 border-t pt-2 text-xs"
991+
{...(omitted ? { 'data-body-table-omitted-totals': '' } : { 'data-body-table-totals': '' })}
992+
>
988993
<span className="font-medium text-muted-foreground">{t('form.masterDetail.total', { defaultValue: 'Total' })}</span>
989994
{totals.map((total) => (
990995
<span key={total.key} className="inline-flex items-center gap-1" data-body-table-total={total.key}>
@@ -3557,13 +3562,25 @@ export const RelatedList: React.FC<RelatedListProps> = ({
35573562
refreshKey: `${refreshNonce}:${windowed && total != null ? total : relatedData.length}`,
35583563
});
35593564
const totalLabel = t('form.masterDetail.total', { defaultValue: 'Total' });
3565+
// objectstack#35831 — a summed column the table left out for width
3566+
// (`bodyTableColumnCap`) keeps its total on the Overview: the totals of the
3567+
// columns not drawn go on a line under the table, each labelled with its
3568+
// column's name (`BodyTableTotalsLine`). A table that leaves no column out
3569+
// has none, and the drawn columns keep theirs in the table's last row.
3570+
const bodyOmittedTotals = React.useMemo(() => {
3571+
if (!bodyTableColumnsOmitted || bodyTotals.length === 0) return [];
3572+
const omitted = new Set((tableColumns ?? []).slice(bodyTableColumnCap!).map((col: any) => String(col?.accessorKey ?? '')));
3573+
return bodyTotals.filter((entry) => omitted.has(entry.key));
3574+
}, [bodyTableColumnsOmitted, bodyTableColumnCap, tableColumns, bodyTotals]);
35603575
// The totals as the table's own last row, each under its column
3561-
// (objectstack#35548's `summaryRow`): 「合计行,与列对齐」.
3576+
// (objectstack#35548's `summaryRow`): 「合计行,与列对齐」. Drawn only while
3577+
// a drawn column has a figure in it: with every summed column left out the
3578+
// line under the table carries them all, and an empty 「合计」 row says nothing.
35623579
const bodySummaryRow = React.useMemo(
3563-
() => (bodyTotals.length > 0
3580+
() => (bodyTotals.length > bodyOmittedTotals.length
35643581
? { lead: totalLabel, cells: Object.fromEntries(bodyTotals.map((entry) => [entry.key, entry.text])) }
35653582
: undefined),
3566-
[bodyTotals, totalLabel],
3583+
[bodyTotals, bodyOmittedTotals, totalLabel],
35673584
);
35683585

35693586
// The column headers an empty body table still draws (objectstack#35597).
@@ -4732,6 +4749,9 @@ export const RelatedList: React.FC<RelatedListProps> = ({
47324749
<SchemaRenderer schema={viewSchema} />
47334750
</div>
47344751
)}
4752+
{/* objectstack#35831 — the totals of the summed columns left out for
4753+
width, each named, under the table that left them out. */}
4754+
{bodyTableDrawn && <BodyTableTotalsLine totals={bodyOmittedTotals} omitted />}
47354755

47364756
{/* objectstack#35597 — a body table past its row cap offers
47374757
「显示全部 N 条」, which expands it in place (no pages); a list
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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#35831 — a body table that leaves summed columns out for width
11+
* (objectstack#35742's `bodyTableColumnsThatFit`) keeps their totals on the
12+
* Overview: a line under the table names each left-out column and draws its
13+
* total, formatted as the column's own total is (the record's currency for a
14+
* line amount that follows its parent). The drawn columns keep their figures
15+
* in the table's last row, unchanged; a table that leaves nothing out shows no
16+
* added line.
17+
*
18+
* jsdom lays nothing out, so the scroll box's widths are stubbed as in the
19+
* body-table face's own pins: each drawn column header is 120 px of scroll
20+
* width inside a details column of `detailsPx`. The width each column asks
21+
* for is the inline width the table gives its header.
22+
*/
23+
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest';
24+
import { render, screen, waitFor, cleanup } from '@testing-library/react';
25+
import '@testing-library/jest-dom';
26+
import React from 'react';
27+
import { RecordContextProvider } from '@object-ui/react';
28+
import { LocalizationProvider } from '@object-ui/i18n';
29+
import { RelatedList } from '../RelatedList';
30+
import { RecordBodyTablesContext, RelatedEnlargeContext } from '../relatedListCompact';
31+
32+
beforeAll(() => {
33+
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 });
34+
});
35+
36+
const COLUMN_PX = 120;
37+
const WIDE_PX = 100_000;
38+
let detailsPx = 680;
39+
const proto = HTMLElement.prototype;
40+
const saved = {
41+
scrollWidth: Object.getOwnPropertyDescriptor(proto, 'scrollWidth'),
42+
clientWidth: Object.getOwnPropertyDescriptor(proto, 'clientWidth'),
43+
};
44+
beforeAll(() => {
45+
Object.defineProperty(proto, 'scrollWidth', {
46+
configurable: true,
47+
get(this: HTMLElement) {
48+
return this.hasAttribute('data-table-scroll-box') ? this.querySelectorAll('thead th').length * COLUMN_PX : 0;
49+
},
50+
});
51+
Object.defineProperty(proto, 'clientWidth', {
52+
configurable: true,
53+
get(this: HTMLElement) {
54+
return this.hasAttribute('data-table-scroll-box') ? detailsPx : 0;
55+
},
56+
});
57+
});
58+
afterAll(() => {
59+
for (const [key, descriptor] of Object.entries(saved)) {
60+
if (descriptor) Object.defineProperty(proto, key, descriptor);
61+
else delete (proto as any)[key];
62+
}
63+
});
64+
afterEach(() => {
65+
detailsPx = 680;
66+
});
67+
68+
/** A server-side `aggregate` over every row, as `engine.aggregate` answers it. */
69+
function serverAggregate(rows: readonly Record<string, unknown>[]) {
70+
return vi.fn(async (_resource: string, params: any) => [
71+
Object.fromEntries(
72+
(params.aggregations as Array<{ field: string; alias: string }>).map((a) => [
73+
a.alias,
74+
rows.reduce((n, row) => n + Number(row[a.field] ?? 0), 0),
75+
]),
76+
),
77+
]);
78+
}
79+
80+
const usd = { currencyMode: 'fixed', defaultCurrency: 'USD' };
81+
const FIELDS: Record<string, Record<string, unknown>> = {
82+
name: { type: 'text', label: 'Line' },
83+
quote: { type: 'master_detail', reference: 'quote', label: 'Quote' },
84+
price: { type: 'currency', label: 'Unit price', currencyConfig: usd },
85+
sku: { type: 'text', label: 'SKU' },
86+
description: { type: 'text', label: 'Description' },
87+
owner: { type: 'text', label: 'Business owner' },
88+
status: { type: 'text', label: 'Status' },
89+
region: { type: 'text', label: 'Region' },
90+
note: { type: 'text', label: 'Note' },
91+
// A line amount in the page record's currency (ADR-0144 D2 as amended).
92+
line_amount: { type: 'currency', label: 'Line amount', currencyConfig: { currencyMode: 'record', currencyField: 'quote.currency_code' } },
93+
tax: { type: 'currency', label: 'Tax', currencyConfig: usd },
94+
};
95+
const ROWS = [
96+
{ id: 'l1', name: 'L1', quote: 'q1', price: 10, sku: 'A-1', description: 'Widget', owner: 'Ada', status: 'Open', region: 'EU', note: 'x', line_amount: 1234.5, tax: 12.25 },
97+
{ id: 'l2', name: 'L2', quote: 'q1', price: 20.5, sku: 'B-2', description: 'Gadget', owner: 'Bo', status: 'Done', region: 'US', note: 'y', line_amount: 100, tax: 7.75 },
98+
];
99+
const ALL = ['name', 'price', 'sku', 'description', 'owner', 'status', 'region', 'note', 'line_amount', 'tax'];
100+
101+
function renderLines(keys: readonly string[]) {
102+
const aggregate = serverAggregate(ROWS);
103+
render(
104+
<LocalizationProvider value={{ locale: 'en-US', currency: 'USD' }}>
105+
<RecordContextProvider objectName="quote" recordId="q1" objectSchema={{ name: 'quote', fields: { currency_code: { type: 'text' } } }} data={{ id: 'q1', currency_code: 'EUR' }}>
106+
<RecordBodyTablesContext.Provider value={new Set(['quote_line.quote'])}>
107+
<RelatedEnlargeContext.Provider value={vi.fn()}>
108+
<RelatedList
109+
title="Lines"
110+
type="table"
111+
api="quote_line"
112+
objectName="quote_line"
113+
referenceField="quote"
114+
parentId="q1"
115+
columns={keys.map((field) => ({ field, label: FIELDS[field].label as string }))}
116+
data={ROWS as any[]}
117+
dataSource={{ find: vi.fn(async () => ROWS), aggregate, getObjectSchema: vi.fn(async () => ({ name: 'quote_line', fields: FIELDS })) } as any}
118+
/>
119+
</RelatedEnlargeContext.Provider>
120+
</RecordBodyTablesContext.Provider>
121+
</RecordContextProvider>
122+
</LocalizationProvider>,
123+
);
124+
return { aggregate };
125+
}
126+
127+
const text = (el: Element | null | undefined) => (el?.textContent ?? '').replace(/\u00a0/g, ' ');
128+
const host = () => document.querySelector('[data-body-table-overflow]') as HTMLElement | null;
129+
const headerKeys = () => Array.from(document.querySelectorAll('thead th')).map((th) => th.getAttribute('data-column-key'));
130+
const summaryRow = () => document.querySelector('[data-testid="data-table-summary-row"]');
131+
const summaryOf = (key: string) => document.querySelector(`[data-testid="data-table-summary-${key}"]`)?.textContent ?? null;
132+
const omittedLine = () => document.querySelector('[data-body-table-omitted-totals]') as HTMLElement | null;
133+
const omittedTotal = (key: string) => omittedLine()?.querySelector(`[data-body-table-total="${key}"]`) ?? null;
134+
135+
/** Draws the table at `px` and waits for its totals to settle. */
136+
async function drawAt(px: number, keys: readonly string[] = ALL) {
137+
detailsPx = px;
138+
renderLines(keys);
139+
await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument());
140+
}
141+
142+
describe('RelatedList — the totals of body-table columns left out for width (objectstack#35831)', () => {
143+
it('a narrow table that leaves summed columns out names each one and keeps its total on a line under the table', async () => {
144+
await drawAt(680);
145+
await waitFor(() => expect(host()?.getAttribute('data-body-table-columns-omitted')).not.toBeNull());
146+
// The two summed columns at the end did not fit; the price column did.
147+
expect(headerKeys()).toContain('price');
148+
expect(headerKeys()).not.toContain('line_amount');
149+
expect(headerKeys()).not.toContain('tax');
150+
await waitFor(() => expect(omittedLine()).not.toBeNull());
151+
// Each left-out total, under its column's name, formatted as its column's
152+
// own total: the line amount in the page record's currency.
153+
const lineAmount = omittedTotal('line_amount');
154+
expect(text(lineAmount)).toContain('Line amount');
155+
expect(text(lineAmount)).toContain('€1,334.50');
156+
const tax = omittedTotal('tax');
157+
expect(text(tax)).toContain('Tax');
158+
expect(text(tax)).toContain('$20.00');
159+
// A drawn column's total stays in its column, never repeated on the line.
160+
expect(summaryOf('price')).toContain('$30.50');
161+
expect(omittedTotal('price')).toBeNull();
162+
expect(omittedLine()!.querySelectorAll('[data-body-table-total]')).toHaveLength(2);
163+
});
164+
165+
it('a left-out total reads the same as the one the table draws in its column when it fits (same currency, same figure)', async () => {
166+
await drawAt(WIDE_PX);
167+
await waitFor(() => expect(summaryOf('line_amount')).not.toBeNull());
168+
const wide = { line_amount: text(document.querySelector('[data-testid="data-table-summary-line_amount"]')), tax: summaryOf('tax')!.replace(/\u00a0/g, ' ') };
169+
cleanup();
170+
await drawAt(680);
171+
await waitFor(() => expect(omittedTotal('tax')).not.toBeNull());
172+
expect(text(omittedTotal('line_amount')?.lastElementChild)).toBe(wide.line_amount);
173+
expect(text(omittedTotal('tax')?.lastElementChild)).toBe(wide.tax);
174+
});
175+
176+
it('every summed column left out: the line carries them all and no empty totals row is drawn', async () => {
177+
await drawAt(680, ['name', 'sku', 'description', 'owner', 'status', 'region', 'note', 'line_amount', 'tax']);
178+
await waitFor(() => expect(omittedTotal('tax')).not.toBeNull());
179+
expect(text(omittedTotal('line_amount'))).toContain('€1,334.50');
180+
expect(summaryRow()).toBeNull();
181+
});
182+
183+
it('CONTROL — a table that leaves no column out shows no added line, every total in its column', async () => {
184+
await drawAt(WIDE_PX);
185+
await waitFor(() => expect(summaryOf('tax')).not.toBeNull());
186+
expect(host()?.hasAttribute('data-body-table-columns-omitted')).toBe(false);
187+
expect(headerKeys()).toEqual(ALL);
188+
expect(summaryOf('price')).toContain('$30.50');
189+
expect(text(document.querySelector('[data-testid="data-table-summary-line_amount"]'))).toContain('€1,334.50');
190+
expect(summaryOf('tax')).toContain('$20.00');
191+
expect(omittedLine()).toBeNull();
192+
expect(document.querySelector('[data-body-table-totals]')).toBeNull();
193+
});
194+
195+
it('CONTROL — the drawn columns\' totals are the same with and without columns left out', async () => {
196+
await drawAt(WIDE_PX);
197+
await waitFor(() => expect(summaryOf('price')).not.toBeNull());
198+
const wide = summaryOf('price');
199+
const lead = text(document.querySelector('[data-testid="data-table-summary-lead"]'));
200+
cleanup();
201+
await drawAt(680);
202+
await waitFor(() => expect(omittedLine()).not.toBeNull());
203+
expect(summaryOf('price')).toBe(wide);
204+
expect(text(document.querySelector('[data-testid="data-table-summary-lead"]'))).toBe(lead);
205+
});
206+
207+
it('CONTROL — a table that leaves out only unsummed columns shows no added line', async () => {
208+
await drawAt(680, ['name', 'price', 'sku', 'description', 'owner', 'status', 'region', 'note']);
209+
await waitFor(() => expect(host()?.getAttribute('data-body-table-columns-omitted')).not.toBeNull());
210+
await waitFor(() => expect(summaryOf('price')).toContain('$30.50'));
211+
expect(omittedLine()).toBeNull();
212+
});
213+
});

0 commit comments

Comments
 (0)