Skip to content

Commit 8243694

Browse files
perf(plugin-detail,app-shell): the record page's related column loads counts first, then rows only for the cards in view, and never blocks the details (#27636)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu4U7UrS1BhTKoR1NK6q6Qvx)_ Fixes #27056 Clause-②: yes (widening: three new exports on the published `@object-ui/plugin-detail` main entry, a public-surface addition; no accept set moves) Metadata-protocol: none ## 维护者速读 - 改了什么:记录页右侧关联列改为分步加载。打开记录时,所有关联卡的计数作为一组请求一起发出(每个只取总数和 1 条 id),到齐前卡片是占位;计数为 0 的卡只剩标题行,不取行;有数的卡进入视口(下方 200 px 内也算)才取前 3 行,只取名称字段加一个状态或日期字段;关掉时间线后折叠的「动态」卡打开前什么都不读;抽屉里 ↑ ↓ 会预取下一条记录的计数。 - 为什么改:落实裁决「关联都放在右侧,记录打开时是不是会很慢」。原来打开记录时每个子表各取 5 行、带一串 populate,和记录本身的读取抢时间。 - 风险与回滚:只改 plugin-detail 和 app-shell 前端的读取顺序,不动协议和服务端。计数失败的卡回到自己取行,没有 IntersectionObserver 的环境立即取行,两种都有测试。回滚就是 revert 本 PR。新增三个导出(Clause-② yes),纯增量。 - 先看:① `ui/packages/plugin-detail/src/useRelatedCounts.ts` 里的 `useRelatedCounts`(一组计数、统一占位、在 transition 里放行卡片);② `RelatedList.tsx` 的 compact 分支(`rowsWanted`、`compactSelect`、`countAnswers`);③ `app-shell/src/views/recordDrawerStack.tsx` 的 `PrefetchUpcomingRelatedCounts`。 - 两分钟验证:在 `ui/` 下跑 `pnpm exec vitest run packages/app-shell/src/views/RecordDetailView.relatedCountsFirst-27056.test.tsx`。预期 2 个测试通过:6 个关联列表先一起发 6 个计数,之后只有视口内且有数的 2 张卡各取 3 行。 - 需要你做的:无,席位落地。 ## What changes The record page's related column (the column tiers, from 1024 px) loads in steps, and the details column never waits for it. - **Counts first** (`useRelatedCounts`, new). `RelatedCardStack` counts every card it places in one request set, sent beside the record read through the existing count store (`RelatedCountStore`, the store the tab badges read, invalidated by the data-change bus). Each probe asks for the total and one row's `id` (`top=1&select=id` on the wire). Every card shows one placeholder (`data-related-card-pending`) until the whole set has answered, so there is one loading state. The faces then mount in a React transition: a record read that lands at the same moment renders the details first. A card counted at 0 folds to its title row and never reads rows. A failed count leaves its card to read for itself, as before. - **Rows on demand** (`RelatedList`, compact branch). A card reads at most three rows, in its inherited sort. It asks only for `id`, the name field (declared or derived) and one chip field. The chip field comes from the authored `relatedListColumns` when they are declared, else the object's status field, else its first date field. A card reads only once it has been in view (`useSeenOnce`, an `IntersectionObserver` latch, `rootMargin` 200 px below the fold). While the count answers a card, its header draws from that count. The folded 「动态」 card (timeline switched off) is closed until opened, and its feed is not mounted until then. - **Details first.** The details column renders from the record read alone. The related column's placeholders hold their place until the counts land. - **Prefetch on step** (`recordDrawerStack`). The drawer works out the record that ↑ / ↓ would show next. Once the current record has loaded, `PrefetchUpcomingRelatedCounts` warms that record's counts (`relatedCountTargetsIn` over the page drawn now), so the next page's cards draw their counts from the store. - **Shape stays independent of the card face.** `useRelatedCounts` returns per-card states (`pending` / `counted` / `uncounted`). The card face is not part of that shape, so #27524 can read the same hook. Additive API: `prefetchRelatedCounts`, `relatedCountTargetsIn`, `relatedCountTargetOf` and the types `RelatedCountTarget` and `RelatedCountsSource` are exported for the drawer prefetch. `RecordPageColumns` also takes an optional `relatedFieldsOf`, which lets the host pass the child field definitions it already holds so the counts read no schema first. ## Tests - `app-shell/.../RecordDetailView.relatedCountsFirst-27056.test.tsx` renders the real page at 1440 px over a data source that holds every related read, for a record with 6 related lists: - The details (name, highlight, details column) draw while every related read is still out, with 6 placeholders. - The 6 counts go out as one set before any answers, with no row read. - After they answer, rows are read only for the 2 counted cards in view (`$top` 3, `$select ['id','name','status']`). Nothing is read for the 0-count card in view or for the 3 cards below the fold. That is 8 reads in total, in 2 round trips. - `plugin-detail/.../useRelatedCounts-27056.test.tsx` (8 tests): - one request set with id-only probes - one loading state until all answer - the store filling up does not release a first set - stepping back to a settled record draws its counts at once, with no placeholder flash - a failed count leaves its card uncounted - no source counts nothing - a prefetched parent draws on its first render with no read - a declared scope is resolved - the `relatedCountTargetsIn` walk skips gated and bound nodes - `plugin-detail/.../RelatedList.compactLazy-27056.test.tsx`: - a 0-count card never queries rows and reports itself empty - a card out of view holds 3 row placeholders and reads nothing - a card in view reads `$top` 3, `$skip` 0 with the projection - without `IntersectionObserver` the card reads at once - `app-shell/.../recordDrawerStack.prefetch-27056.test.tsx`: the next record follows the step direction, and the prefetch fires only once the current record is ready and the object matches. - `RecordPageColumns.switches-27052.test.tsx`: updated so that the folded 「动态」 card starts closed with nothing mounted, and opening it mounts the feed. Ablations, each run against the tests above: | Ablation | Result | |---|---| | `stateOf` forced to `uncounted` | 2 acceptance tests fail | | `useSeenOnce` forced to `true` | 3 tests fail | | the first-ask rule dropped | "the store answering is not the set settling" fails | | the settled-parent clear dropped | "stepping back" fails | ## Acceptance notes - **"One counts call"** is one request set. There is no batched read door on `main` (`/batch` takes writes only), and adding one is a server and protocol change outside this card. The set is N `$count` probes of one id each, all sent together before any answers, behind one loading state. On HotCRM they go out within 8 ms of each other, in parallel with the record read (waterfall below). - **"Primary cards first."** On the synthesized page the primary lists are body tables in the details column, so the related column holds no primary cards. Its cards are counted and read in page order, and only the ones in view read rows. - **Request count vs round trips.** On HotCRM a cold open sends 14–16 related requests where `main` sent 10, in the same 2 round trips. Each count carries one id, and each row read carries 3 projected rows. On `main` each read carried 5 rows with up to 9 populated lookups. The trade-off is that a card's first rows land 260–380 ms after the record read (the last card's by 330–490 ms), where on `main` they landed before it. Meanwhile each card shows its count in its header. - **Details time** is dominated by one render of the page when the record lands: a single 100–200 ms long task on both builds (`longtask` entries). The transition keeps the card faces out of that render. Without it, Acme measured 302–312 ms on this branch, where the faces had mounted just before the record landed. ## Verification ### Budget (HotCRM, measured) | Budget | Target | `main` (6892888) | this PR | | |---|---|---|---|---| | Details interactive, after the record read returns | ≤ 300 ms | median 189 ms, max 326 ms (2 of 12 opens over) | median 217 ms, max 260 ms (0 of 12 over) | ✅ | | All card headers drawn, after the record read returns | ≤ 500 ms | median −20 ms, max 28 ms (the headers come from the 5-row reads) | median 181 ms, max 235 ms (the headers come from the counts, after the details) | ✅ | | Related round trips on open | ≤ 2 | 2: 9 row reads, then a lookup-label read | 2: 9 counts, then 5–7 three-row reads | ✅ | | Related requests on open | — | 10 | 16 / 15 / 16 at 1600×1000; 14 at 1600×700 (fewer cards in view) | | <details><summary>How it was measured</summary> - **Backend.** HotCRM on a fresh DB (`objectstack dev --fresh`). The `crm_account` record page has 9 related lists in the related column: contacts, contracts, quotes, child accounts, events, leads, opportunities, tasks and cases. - **Console.** Production builds (`vite build`) of `main` at 6892888 and of this branch, served by `vite preview`, which proxies to the backend. Measured in headless Chromium at 1600×1000 (the three-column tier) and once at 1600×700. - **Opens.** A warm-up open of a fourth account (Wayne) first, so modules and metadata are loaded, as for a reader arriving from the list. Then an SPA navigation to each of Acme, Globex and Stark. Three alternating `main`/branch rounds plus the 700 px round give 12 opens per build. - **Numbers.** Every number comes from the Resource Timing entries (the entries DevTools' network panel draws), relative to the `responseEnd` of the record read. - "Details interactive": the details column shows the record's phone and the main thread has run a task after the next frame. - "Headers": every card in the related column is past its placeholder and loading state. - "Round trip": a related read that went out after an earlier related response had landed starts a new round. | Account | `main` details ms (3 rounds · 700 px) | this PR details ms | this PR headers ms | this PR requests (counts + rows) | |---|---|---|---|---| | Acme | 303 / 195 / 188 · 326 | 197 / 237 / 227 · 198 | 178 / 212 / 204 · 176 | 9+7 · 9+5 | | Globex | 170 / 232 / 162 · 177 | 215 / 219 / 215 · 225 | 30 / 194 / 196 · 31 | 9+6 · 9+5 | | Stark | 130 / 189 / 195 · 179 | 260 / 205 / 114 · 232 | 183 / 121 / 235 · 37 | 9+7 · 9+5 | </details> <details><summary>Network waterfall, Acme, round 1 (ms from navigation; record read 178→465 on main, 122→316 on this PR)</summary> `main`: | Round | Object | Query | Start → end | |---|---|---|---| | 1 | `crm_contact` | `top=5` + populate of 5 lookups | 172 → 217 | | 1 | `crm_contract` | `top=5` + populate of 7 lookups | 173 → 238 | | 1 | `crm_quote` | `top=5 select=id,quote_number,name,status,total_price` | 174 → 255 | | 1 | `crm_account` | `top=5 select=id,account_number,name,type,owner_id populate=owner_id` | 175 → 267 | | 1 | `crm_event` | `top=5` + populate of 9 lookups | 175 → 306 | | 1 | `crm_lead` | `top=5` + populate of 9 lookups | 175 → 322 | | 1 | `crm_opportunity` | `top=5` + populate of 7 lookups | 176 → 341 | | 1 | `crm_task` | `top=5` + populate of 9 lookups | 176 → 376 | | 1 | `crm_case` | `top=5` + populate of 8 lookups | 176 → 389 | | 2 | `crm_account` | `top=1` lookup label | 422 → 564 | This PR. Details are interactive at 513 and headers draw at 494: | Round | Object | Query | Start → end | |---|---|---|---| | 1 | `crm_contact` | `top=1 select=id` | 119 → 198 | | 1 | `crm_contract` | `top=1 select=id` | 119 → 209 | | 1 | `crm_quote` | `top=1 select=id` | 119 → 224 | | 1 | `crm_account` | `top=1 select=id` (child accounts: 0) | 120 → 245 | | 1 | `crm_event` | `top=1 select=id` | 120 → 253 | | 1 | `crm_lead` | `top=1 select=id` (0) | 120 → 275 | | 1 | `crm_opportunity` | `top=1 select=id` | 120 → 286 | | 1 | `crm_task` | `top=1 select=id` | 121 → 295 | | 1 | `crm_case` | `top=1 select=id` | 122 → 304 | | 2 | `crm_contact` | `top=3 select=id,full_name,title,created_at` | 615 → 651 | | 2 | `crm_contract` | `top=3 select=id,contract_number,signed_by,status` | 616 → 660 | | 2 | `crm_quote` | `top=3 select=id,display_title,name,status` | 616 → 672 | | 2 | `crm_event` | `top=3 select=id,subject,status` | 617 → 682 | | 2 | `crm_opportunity` | `top=3 select=id,name,stage` | 618 → 695 | | 2 | `crm_task` | `top=3 select=id,subject,status` | 618 → 712 | | 2 | `crm_case` | `top=3 select=id,display_title,subject,status` | 619 → 724 | At 1600×700 the `crm_task` and `crm_case` cards sit below the fold, and their row reads are not sent. </details> ### Local checks (head 5d85c50) - `pnpm --dir ui exec vitest run packages/plugin-detail`: 336 files passed (1 skipped), 3070 tests passed (18 skipped). - `app-shell`: the 180 test files that reference `RecordDetailView` or `recordDrawerStack` all passed (1357 tests). This is a declared narrowing: the full app-shell suite is 1880 files and runs longer than an hour here, so CI runs all of it. - `type-check` passed for `@object-ui/plugin-detail` and `@object-ui/app-shell`, and `@object-ui/plugin-detail` builds. - `node scripts/pm/dispatch-gates.mjs --ran`: 66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN. Three gates were run a second time, and the table records the second runs: - `vitest run scripts/` had one 15 s test time out while a locked app-shell run held the box. - `check:skill-examples` exited 3 because the client dists were not built yet. - `check:type-check-debt` exited 3 after queueing on the lock. All three exited 0 on the rerun. <details><summary>Gate record (exit · command)</summary> ```text 0 node scripts/check-adr-0087-registration.mjs --base origin/main 0 node scripts/check-adr-0087-registration.mjs --self-test 0 node scripts/check-adr-links.mjs 0 node scripts/check-adr-links.mjs --self-test 0 node scripts/check-changeset-no-major.mjs --base origin/main 0 node scripts/check-closing-keyword-parity.mjs 0 node scripts/check-closing-keyword-parity.mjs --self-test 0 node scripts/check-comment-mask-corpus.mjs 0 node scripts/check-doc-route-spelling.mjs --advisory 0 node scripts/check-doc-route-spelling.mjs --self-test 0 node scripts/check-docs-section-name.mjs 0 node scripts/check-docs-section-name.mjs --self-test 0 node scripts/check-empty-changeset.mjs --base origin/main 0 node scripts/check-empty-changeset.mjs --self-test 0 node scripts/check-sdui-manifest.mjs 0 node scripts/check-sdui-manifest.mjs --self-test 0 node scripts/check-section-landing-index.mjs 0 node scripts/check-section-landing-index.mjs --self-test 0 node scripts/ci/plan-test-core-shards.mjs --self-test 0 node scripts/pm/release-rehearsal-clone.mjs --self-test 0 node scripts/release-pending-publish.mjs --self-test 0 pnpm --dir ui exec vitest run scripts/ 0 pnpm --filter @objectstack/lint run check:doc-formula-expressions 0 pnpm --filter @objectstack/lint run check:doc-security-posture 0 pnpm --filter @objectstack/spec run check:docs 0 pnpm --filter @objectstack/spec run check:duration-unit-keys 0 pnpm --filter @objectstack/spec run check:empty-state 0 pnpm --filter @objectstack/spec run check:liveness 0 pnpm --filter @objectstack/spec run check:skill-examples 0 pnpm --filter @objectstack/spec run check:strictness-ledger 0 pnpm --filter @objectstack/spec run check:variant-docs 0 pnpm --filter @objectstack/spec run check:yaml-examples 0 pnpm check:changeset-gate-self-tests 0 pnpm check:ci-filter-parity 0 pnpm check:closed-ceremony-text 0 pnpm check:corpus-claim-drift 0 pnpm check:cross-package-test-inputs 0 pnpm check:dispatcher-error-vocabulary 0 pnpm check:doc-anchors 0 pnpm check:doc-authoring 0 pnpm check:doc-frontmatter 0 pnpm check:docs-audit-scope 0 pnpm check:docs-redirects 0 pnpm check:docs-single-h1 0 pnpm check:docs-spec-enumerations 0 pnpm check:docs-transcript-drift 0 pnpm check:driver-memory-census 0 pnpm check:engine-double-contract 0 pnpm check:gitlink-declared 0 pnpm check:nul-bytes 0 pnpm check:pm-changeset-deadline-census 0 pnpm check:published-files 0 pnpm check:published-readme-links 0 pnpm check:query-options-erasure 0 pnpm check:react-page-adapter-contract 0 pnpm check:refd-timer-probe 0 pnpm check:role-word 0 pnpm check:skill-identifier-liveness 0 pnpm check:test-source-alias 0 pnpm check:tier-file-adoption 0 pnpm check:type-check-coverage 0 pnpm check:type-check-debt 0 pnpm check:undeclared-dep-imports 0 pnpm check:vendor-version-stamps 0 pnpm check:watch-hint-literal 0 pnpm check:where-matcher ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgVDURMCgpQ3vtrchrM)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2140821 commit 8243694

16 files changed

Lines changed: 1634 additions & 76 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/plugin-detail': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
perf(plugin-detail,app-shell): the record page's related column loads counts first, then rows only for the cards in view, and never blocks the details
7+
8+
Clause-②: yes (widening: three new exports on the published `@object-ui/plugin-detail` main entry, a public-surface addition; no accept set moves)
9+
Metadata-protocol: none
10+
11+
Opening a record with many related lists used to read every list's rows as the page opened. The related column now loads in three steps, and the details column never waits for it:
12+
13+
- **Counts first.** When the page opens, every card in the related column is counted in one request set, sent beside the record read. Each count reads the total and one row's id, nothing more. Until the whole set has answered, each card shows a placeholder. Then each card's header draws from its count. A card counted at 0 is its title row alone and reads no rows. The counts share the store the tab strip's badges read, so a write to a child counts it again.
14+
- **Rows on demand.** A card reads at most three rows, in its inherited sort, and asks only for the fields it draws: the record's name field and one status or date field. That field comes from the relationship's `relatedListColumns` when declared, else the object's status field, else its first date field. A card reads its rows only once it comes into view (`IntersectionObserver`; cards just below the fold count as in view). The folded 「动态」 card (the timeline switched off) is closed until the reader opens it, and its feed reads nothing until then.
15+
- **Details first.** The details column draws from the record read alone. The related column's placeholders hold their place until the counts land, and the cards then draw in a transition, so a record read landing at the same moment draws the details first.
16+
- **Drawer prefetch.** In the record drawer, the record that `↑` / `↓` would show next has its related counts read once the current record has loaded, so the next record's badges draw from the store.
17+
18+
Additive API (`@object-ui/plugin-detail`): `prefetchRelatedCounts`, `relatedCountTargetsIn` and `relatedCountTargetOf` are exported with their types `RelatedCountTarget` and `RelatedCountsSource`, for the app-shell record drawer's prefetch. `RecordPageColumns` takes an optional `relatedFieldsOf`, the child objects' field definitions the host already holds, so the counts read no child schema first.

‎content/docs/ui/pages.mdx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,15 @@ related lists as cards with Approvals, Attachments and the created/updated line.
199199
1024 px the related column folds into a rail behind a **Related (N)** toggle. Below that, and
200200
always in a drawer or split pane, the tab strip is drawn. `?tab=` selects a tab in the strip.
201201

202+
In the column tiers the related column loads in steps, and the details column never waits for
203+
it. The page asks every card's count in one request set, sent beside the record read, and the
204+
cards show placeholders until those counts land. A card counted at 0 is its title row alone
205+
and reads no rows. A card above 0 reads its first three rows once it scrolls into view, asking
206+
only for the record's name field and one status or date field. When the timeline column is
207+
switched off, its **Activity** card in the related column stays closed, and reads nothing, until
208+
it is opened. In a drawer, the record that **↑** / **↓** would show next has its related counts
209+
read ahead.
210+
202211
### Slotted pages
203212

204213
`kind: 'slotted'` overrides only the parts of the synthesized page you name, and the
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
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#27056 — the record page's related column loads counts first,
11+
* then the first rows of only the cards in view, and never blocks the details.
12+
*
13+
* The REAL page, at a desktop width (the column tiers), over a data source
14+
* that holds every related read until the test answers it. The record has six
15+
* related lists. Measured:
16+
*
17+
* - the details draw from the record read alone, while every related read is
18+
* still out, and the related column shows one placeholder per card;
19+
* - the six counts go out as ONE request set, before any of them answers;
20+
* - once they answer, rows are read for the two counted cards in view only,
21+
* three rows each — never for a card counted at 0 (in view too), never for
22+
* the cards below the fold.
23+
*/
24+
import * as React from 'react';
25+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
26+
import { render, cleanup, act } from '@testing-library/react';
27+
import { MemoryRouter } from 'react-router-dom';
28+
import { MetadataCtx } from '@object-ui/react';
29+
import { RelatedCountStore } from '@object-ui/components';
30+
31+
vi.mock('@object-ui/auth', async (importOriginal) => ({
32+
...(await importOriginal<Record<string, unknown>>()),
33+
useAuth: () => ({ user: { id: 'u1', name: 'Ada', image: null }, activeOrganization: null }),
34+
createAuthenticatedFetch: () => vi.fn(),
35+
}));
36+
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
37+
...(await importOriginal<Record<string, unknown>>()),
38+
useRecordPresence: () => [],
39+
PresenceAvatars: () => null,
40+
}));
41+
vi.mock('sonner', () => ({
42+
toast: Object.assign(vi.fn(), {
43+
success: vi.fn(), error: vi.fn(), info: vi.fn(),
44+
warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),
45+
}),
46+
}));
47+
// Orthogonal chrome — stubbed so the only asynchrony here is the page's own.
48+
vi.mock('./ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null }));
49+
vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null }));
50+
vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null }));
51+
vi.mock('./FlowRunner', () => ({ FlowRunner: () => null }));
52+
vi.mock('./MetadataInspector', () => ({
53+
MetadataPanel: () => null,
54+
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
55+
}));
56+
57+
import { RecordDetailView } from './RecordDetailView';
58+
59+
const PARENT = 'os_27056_account';
60+
const RECORD_ID = 'acc-1';
61+
const CHILDREN = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6'].map((n) => `os_27056_${n}`);
62+
const [C1, C2, C3] = CHILDREN;
63+
/** What each child's count answers: the second is empty. */
64+
const TOTALS: Record<string, number> = Object.fromEntries(CHILDREN.map((c, i) => [c, [5, 0, 2, 4, 4, 4][i]]));
65+
/** The cards on screen at open: the first three; the rest are below the fold. */
66+
const IN_VIEW = new Set([C1, C2, C3].map((c) => `${c}.account`));
67+
68+
const OBJECTS = [
69+
{
70+
name: PARENT,
71+
label: 'Account',
72+
pluralLabel: 'Accounts',
73+
managedBy: 'platform',
74+
fields: {
75+
id: { type: 'text', label: 'Id' },
76+
name: { type: 'text', label: 'Name' },
77+
industry: { type: 'text', label: 'Industry' },
78+
},
79+
},
80+
...CHILDREN.map((name, i) => ({
81+
name,
82+
label: `Child ${i + 1}`,
83+
pluralLabel: `Children ${i + 1}`,
84+
managedBy: 'platform',
85+
fields: {
86+
id: { type: 'text', label: 'Id' },
87+
name: { type: 'text', label: 'Name' },
88+
status: { type: 'select', label: 'Status', options: [{ value: 'open', label: 'Open' }] },
89+
account: { type: 'lookup', reference: PARENT, label: 'Account' },
90+
},
91+
})),
92+
];
93+
94+
interface HeldRead {
95+
object: string;
96+
query: Record<string, any>;
97+
answered: boolean;
98+
answer: () => void;
99+
}
100+
101+
let reads: HeldRead[] = [];
102+
let dataSource: Record<string, any>;
103+
104+
function makeDataSource() {
105+
return {
106+
find: vi.fn((object: string, query: Record<string, any> = {}) => {
107+
if (!CHILDREN.includes(object)) return Promise.resolve({ data: [], total: 0 });
108+
return new Promise((resolve) => {
109+
const read: HeldRead = {
110+
object,
111+
query,
112+
answered: false,
113+
answer: () => {
114+
read.answered = true;
115+
const total = TOTALS[object];
116+
const top = typeof query.$top === 'number' ? query.$top : total;
117+
const rows = Array.from({ length: Math.min(top, total) }, (_, i) => ({
118+
id: `${object}-${i}`,
119+
name: `${object} row ${i}`,
120+
status: 'open',
121+
}));
122+
resolve({ data: rows, total });
123+
},
124+
};
125+
reads.push(read);
126+
});
127+
}),
128+
findOne: vi.fn(async (_o: string, id: string) => ({ id, name: 'Acme', industry: 'Retail' })),
129+
getObjectSchema: vi.fn(async (name: string) => OBJECTS.find((o) => o.name === name) ?? null),
130+
create: vi.fn(async (_o: string, row: unknown) => row),
131+
update: vi.fn(async () => ({})),
132+
delete: vi.fn(async () => ({})),
133+
};
134+
}
135+
136+
/** The viewport: a card's root intersects when its relationship is on screen. */
137+
class ViewportObserver {
138+
constructor(private readonly cb: (entries: Array<{ isIntersecting: boolean }>) => void) {}
139+
observe(el: Element) {
140+
const id = el.getAttribute('data-related-card-id');
141+
if (id && IN_VIEW.has(id)) queueMicrotask(() => this.cb([{ isIntersecting: true }]));
142+
}
143+
unobserve() {}
144+
disconnect() {}
145+
}
146+
147+
function renderPage() {
148+
dataSource = makeDataSource();
149+
const metadata = {
150+
objects: OBJECTS,
151+
pages: [],
152+
loading: false,
153+
error: null,
154+
refresh: async () => {},
155+
invalidate: () => {},
156+
ensureType: async () => [],
157+
getItem: async () => null,
158+
getItemsByType: () => [],
159+
} as never;
160+
return render(
161+
<MemoryRouter initialEntries={[`/app/demo/${PARENT}/${RECORD_ID}`]}>
162+
<MetadataCtx.Provider value={metadata}>
163+
<RecordDetailView
164+
dataSource={dataSource as never}
165+
objects={OBJECTS}
166+
onEdit={() => {}}
167+
objectNameOverride={PARENT}
168+
recordIdOverride={RECORD_ID}
169+
/>
170+
</MetadataCtx.Provider>
171+
</MemoryRouter>,
172+
);
173+
}
174+
175+
async function idle() {
176+
await act(async () => {
177+
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
178+
});
179+
}
180+
181+
const isCount = (r: HeldRead) => r.query.$count === true && r.query.$skip === undefined;
182+
const isRows = (r: HeldRead) => r.query.$skip !== undefined;
183+
const column = (container: HTMLElement, name: string) =>
184+
container.querySelector(`[data-record-column="${name}"]`) as HTMLElement | null;
185+
186+
beforeEach(() => {
187+
cleanup();
188+
reads = [];
189+
RelatedCountStore._reset();
190+
window.localStorage.clear();
191+
vi.stubGlobal('IntersectionObserver', ViewportObserver);
192+
vi.stubGlobal(
193+
'fetch',
194+
vi.fn(async () =>
195+
new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }),
196+
),
197+
);
198+
const measure = HTMLElement.prototype.getBoundingClientRect;
199+
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
200+
if (!this.hasAttribute('data-record-page-root')) return measure.call(this);
201+
return { x: 0, y: 0, top: 0, left: 0, right: 1440, bottom: 900, width: 1440, height: 900, toJSON: () => ({}) } as DOMRect;
202+
});
203+
});
204+
205+
afterEach(() => {
206+
vi.unstubAllGlobals();
207+
vi.restoreAllMocks();
208+
});
209+
210+
describe('RecordDetailView — the related column loads counts first (objectstack#27056)', () => {
211+
it('draws the details before any related read answers, with one placeholder per card', async () => {
212+
const { container } = renderPage();
213+
await idle();
214+
expect(reads.length).toBeGreaterThan(0);
215+
expect(reads.every((r) => !r.answered)).toBe(true);
216+
// The record's own values — its name, its highlight, its details — are on
217+
// screen from the record read alone.
218+
expect(container.textContent).toContain('Acme');
219+
expect(container.textContent).toContain('Retail');
220+
expect(column(container, 'details')?.textContent).toContain(RECORD_ID);
221+
const related = column(container, 'related')!;
222+
expect(related.querySelectorAll('[data-related-card-pending]')).toHaveLength(CHILDREN.length);
223+
expect(related.querySelector('[data-related-card-row]')).toBeNull();
224+
});
225+
226+
it('asks the six counts as one request set, then the rows of the two counted cards in view only', async () => {
227+
const { container } = renderPage();
228+
await idle();
229+
// One request set: every list's count, all out before any answered, and
230+
// nothing else of theirs.
231+
expect(reads.filter(isCount).map((r) => r.object).sort()).toEqual([...CHILDREN].sort());
232+
expect(reads.filter(isRows)).toEqual([]);
233+
expect(reads.filter(isCount).every((r) => r.query.$top === 1)).toBe(true);
234+
235+
await act(async () => {
236+
for (const r of reads.filter((read) => !read.answered)) r.answer();
237+
});
238+
await idle();
239+
const rowReads = reads.filter(isRows);
240+
// The counted cards in view: the first and the third. The second is in
241+
// view but counted at 0; the last three are below the fold.
242+
expect(rowReads.map((r) => r.object).sort()).toEqual([C1, C3].sort());
243+
for (const r of rowReads) {
244+
expect(r.query.$top).toBe(3);
245+
expect(r.query.$select).toEqual(['id', 'name', 'status']);
246+
}
247+
// Two round trips in all: the counts, then the rows.
248+
expect(reads).toHaveLength(CHILDREN.length + 2);
249+
250+
await act(async () => {
251+
for (const r of reads.filter((read) => !read.answered)) r.answer();
252+
});
253+
await idle();
254+
const related = column(container, 'related')!;
255+
expect(related.querySelector(`[data-related-card-id="${C1}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(3);
256+
expect(related.querySelector(`[data-related-card-id="${C3}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(2);
257+
expect(related.querySelector('[data-related-card-pending]')).toBeNull();
258+
// Still nothing for the empty card, nor for the cards out of view.
259+
expect(reads.filter(isRows).map((r) => r.object).sort()).toEqual([C1, C3].sort());
260+
expect(reads.some((r) => r.object === C2 && isRows(r))).toBe(false);
261+
});
262+
});

‎ui/packages/app-shell/src/views/RecordDetailView.tsx‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import { ActionResultDialog, type ResultDialogState } from './ActionResultDialog
3333
import { FlowRunner, type ScreenFlowState, type ScreenSpec } from './FlowRunner.js';
3434
import { FlowRefusalNotice, type FlowRefusalState } from './FlowRefusalNotice.js';
3535
import { RelatedRecordActionsBridge } from './RelatedRecordActionsBridge.js';
36-
import { RecordDrawerReturnLink, RecordPageDrawerHost } from './recordDrawerStack.js';
36+
import { PrefetchUpcomingRelatedCounts, RecordDrawerReturnLink, RecordPageDrawerHost } from './recordDrawerStack.js';
3737
import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js';
3838
import { RECORD_DETAIL_TAB_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js';
3939

@@ -3431,10 +3431,12 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
34313431
// `buildDefaultPageSchema`'s `related` shape. `relationshipField` is
34323432
// the FK field on the child pointing back to this record — passed so
34333433
// the related-list renderer can hide the redundant parent-ID column.
3434-
// Each list's `record:related_list` renderer self-fetches lazily when
3435-
// its tab is shown (nothing is preloaded here), and header/row
3436-
// affordances (+ New / View All / row navigation) are wired
3437-
// downstream by `RelatedRecordActionsBridge`.
3434+
// Nothing is preloaded here: in the tabbed tier each list reads when its
3435+
// tab is shown; in the column tiers the related column counts its cards
3436+
// up front, in one request set, and a card reads its first rows once it
3437+
// is in view (`RelatedCardStack`, objectstack#27056). Header/row
3438+
// affordances (+ New / View All / row navigation) are wired downstream
3439+
// by `RelatedRecordActionsBridge`.
34383440
// The DEFAULT order of the related lists (objectstack#27055,
34393441
// objectstack#27069): `relatedList: 'primary'` lists first, then the rest,
34403442
// each group in `deriveRelatedLists`' order — the object's declared
@@ -3977,6 +3979,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
39773979
// included). `null` in the tabbed tier, and for a page whose strip the
39783980
// partition cannot read, which then keeps its tabs.
39793981
const pageColumns = pageInColumnTier ? buildDefaultPageColumns(renderedPage) : null;
3982+
// The child objects' field definitions this view already holds, for the
3983+
// related counts asked up front (objectstack#27056): the relationship's
3984+
// arity is read off them instead of a schema read first.
3985+
const childFieldsOf = (childObject: string) =>
3986+
(objects?.find((o: any) => o?.name === childObject) as { fields?: any } | undefined)?.fields;
39803987
// objectstack#27055, Target 8 — the related lists the synthesized page
39813988
// places in its Details tab are the record's body tables (the tabbed tier;
39823989
// the column tiers read the same off their details column).
@@ -4325,6 +4332,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
43254332
enlargedRelated={enlargedRelatedParam}
43264333
onEnlargeRelated={openEnlargedRelated}
43274334
onCloseEnlargedRelated={closeEnlargedRelated}
4335+
relatedFieldsOf={childFieldsOf}
43284336
footer={
43294337
<RecordMetaFooter
43304338
data={readablePageRecord}
@@ -4492,7 +4500,22 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
44924500
// A drawer draws this view embedded and is its own host. A page is the host
44934501
// of the drawer its related rows and lookups open over it
44944502
// (objectstack#26679): the same in-place stack, drawn by this same view.
4495-
if (embedded) return pageTree;
4503+
// In a drawer, the record ↑ ↓ shows next has its related counts warmed
4504+
// once this one has loaded (objectstack#27056, Target 4).
4505+
if (embedded) {
4506+
return (
4507+
<>
4508+
{pageTree}
4509+
<PrefetchUpcomingRelatedCounts
4510+
page={renderedPage}
4511+
objectName={objectName}
4512+
dataSource={dataSource}
4513+
fieldsOf={childFieldsOf}
4514+
ready={pageRecordStatus === 'loaded'}
4515+
/>
4516+
</>
4517+
);
4518+
}
44964519
return (
44974520
<RecordPageDrawerHost
44984521
appName={appName}

0 commit comments

Comments
 (0)