diff --git a/.changeset/35595-35596-record-tabs-rail.md b/.changeset/35595-35596-record-tabs-rail.md new file mode 100644 index 00000000000..91d03e8737f --- /dev/null +++ b/.changeset/35595-35596-record-tabs-rail.md @@ -0,0 +1,24 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +'@object-ui/plugin-detail': patch +--- + +feat(record-page): one tab per related list, and an Overview rail that sums up the other tabs + +Clause-②: no +Metadata-protocol: none + +The record page's tab row and its right column are redrawn (supersedes objectstack#28469): + +- **Tabs.** Overview, then one tab per related list in its order, then Attachments, Approvals and Activity last. Every tab is there at first paint and none moves when the counts land. A list with no records keeps its place, greyed, with no number. The width is the row's only fold: the tabs that do not fit go into 「更多 N ▾」, whose items keep their counts. Approvals carries a dot while a request waits, not a count. A tab that merges several tables (only an explicit page can write one) carries no count. +- **Overview.** The stage path and the key fields sit across the whole width on Overview only; every other tab draws its block in full in their place. +- **Right rail.** On Overview, the right column sums up the other tabs, in this order: Approvals, Attachments, Recent activity, then 「其他相关」 with a card for each related list that has records. Each card has a title (which opens its tab), a grey count and at most three rows. A card with nothing to show is not drawn, and there is no 「还有 N 个空关联」 line. Nothing in the rail is editable. A rail with no cards folds away. A drawer draws no rail and no right-column switch. The rail's rows come from the page's one read: it reads nothing more. +- **No band at the foot.** A page drawn as written that places no approvals or attachments panel gets them as tabs of its first tab strip, not as bands under the page. The header's approval tag opens the Approvals tab. +- **One approval band.** A page drawn as written whose details are split into several `record:details` nodes draws the record's approval band once, on the first body that reaches it, recall included. + +- **Reader arrangement leaves with the cards.** The related cards' ⠿ handle, ⌥↑ / ⌥↓ and 「隐藏」 are gone with the cards, so a reader can no longer reorder or hide a related list on the page. An order or hides already stored still apply, and 「恢复默认顺序」 / 「显示」 still undo them. +- **`?tab=related` is retired.** The single 「Related」 tab is gone, so a saved link carrying `?tab=related` opens Overview. + +`@object-ui/plugin-detail` adds `ApprovalBandOnceScope`. `@object-ui/i18n` adds the 「更多 N」 trigger and the rail's labels in every pack. Nothing an app authors changes. diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 9bd0e37d541..e551324e089 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -187,7 +187,7 @@ "title": "Create → read → update → delete a record through the console UI", "since": "v15", "status": "active", - "revision": 20, + "revision": 21, "priority": "P0", "surface": "browser", "personas": [ @@ -213,7 +213,7 @@ "capture the create request/response (expect POST /api/v1/data/showcase_account). The payload also carries the select defaults of fields the step leaves untouched — sales_region:'amer' (its AMER option is default:true, examples/app-showcase/src/data/objects/account.object.ts) — so expect that key in the body you diff (QA run #24556)", "re-read server-side: GET /api/v1/data/showcase_account?$filter=[[\"name\",\"=\",\"os-qa-\"]] — field-by-field vs the submitted payload", "open the record detail; edit exactly one field, annual_revenue, to a new positive number; submit it (an edit form's button reads 'Update'); capture the PATCH /api/v1/data/showcase_account/; re-read the full row via GET /api/v1/data/showcase_account/. annual_revenue is the field because showcase_account has no rule-free TEXT field the later steps can spare: `name` is the key steps[3] and steps[8] filter on, and tax_id, billing_email and churn_reason are each judged by a validation rule (account.object.ts: tax_id_format, billing_email_format, churn_reason_consistency); annual_revenue carries none (its only constraint is the field's min 0). ⛔ Not `hq`: it is a location field (Field.location), whose input takes 'latitude, longitude', and text that is not a coordinate pair clears the stored value while the save still reports success (#32139) — a defect of its own, not this clause's subject", - "read the record's field-change history on the record page's timeline stream, under its Changes chip (变更). Record page v3 draws no tab named History at any width (#27055). The stream's whole face, with its chips, is the 动态 (Activity) tab: open it from the header of the 动态 panel, the first panel of the record page's right column (below the details in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor), or by ?related=timeline (#27524). At 1440 px the page also draws a top-level tab row — Overview, Activity (动态) with its count, then one tab for each related panel that has records, while an empty panel's tab waits in the row's '+N' dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row, partitionRecordTabsByRecords), so on the fresh account this item creates the row reads just 'Overview / Activity N' (QA run #33784) — and its Activity tab is the same door as ?related=timeline. The panel itself shows only the newest lines, with no chips, and can lag the update line until a fresh read (QA run #28545): read the change lines on the Activity tab after a reload, not off the panel. Screenshot first, then read the change lines", + "read the record's field-change history on the record page's timeline stream, under its Changes chip (变更). Record page v3 draws no tab named History at any width (#27055). The stream's whole face, with its chips, is the Activity (动态) tab of the record's tab row — Overview (概览), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595). Open it from that tab, from the title of the Overview tab's 最近动态 (Recent activity) card, in the right rail beside the details (below them in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor; ui/packages/plugin-detail/src/RecordSummaryRail.tsx, #35596), or by ?related=timeline (#27524). The rail card shows only the newest three lines, read-only, with no chips, and can lag the update line until a fresh read (QA run #28545): read the change lines on the Activity tab after a reload, not off the card. Screenshot first, then read the change lines", "clone the record: POST /api/v1/data/showcase_account//clone (optionally with {overrides:{name:'os-qa--clone'}}); capture the 201 result (new id ≠ source, sourceId, record); re-read the clone via GET /api/v1/data/showcase_account/", "RLS probe on clone: as a persona WITHOUT read on the source row (a permission-zoo persona, or a non-owner under owner-RLS), POST the same clone route and capture the refusal — expect 404 RECORD_NOT_FOUND, never a silent duplicate (record blocked(fixture) if no non-reading persona is bound on this boot)", "delete via the record header's 'More actions' (⋯) menu → Delete (the menu also holds Refresh / Add to favorites / Share; detail.moreActions), or the list row's menu; confirm the dialog; re-read via the filtered GET. ⚠️ If clause 7's recipe gave the member an own-row invoice pointing at THIS account, the delete answers 409 DELETE_RESTRICTED: the invoice's account lookup is required, and the engine turns a required set_null into restrict (packages/objectql/src/engine.ts). Point that invoice at a seeded account instead (the recipe's step 5 says so)", @@ -247,7 +247,7 @@ { "clause": "the record's field-change history (the record page's sys_audit_log read, shown as the timeline stream's Changes chip) reflects the create and the update with display values (option labels, localized dates, real actor), not raw audit payloads or phantom value→null rows", "oracle": "dom", - "verify": "after a fresh read of the page (the right column's 动态 panel can lag the update line, QA run #28545), open the stream by the Activity tab, the 动态 panel header or ?related=timeline (steps[5]); after a screenshot confirms the Changes chip is selected on the account's timeline stream, read its change lines — same contract ui/e2e/live/record-history-display.spec.ts pins on showcase_account, the showcase's enable.trackHistory object, at 1440×900 (its option labels, the localized Customer Since date and the resolved owner). The page reads sys_audit_log only for an object whose enable.trackHistory is true (ui/packages/app-shell/src/views/RecordDetailView.tsx, historyEnabled), and the rows reach the stream as field_change items (ui/packages/plugin-detail/src/recordTimelineStream.ts#auditEntriesToFeedItems). The chip also lists the stream's sys_activity created/updated rows, so attribute a line to the audit read before scoring it. ⛔ Never look for a tab named History: record page v3 removed it at every width (#27055; buildDefaultPageSchema.test.ts asserts the default tabs carry neither Activity nor History), so its absence fails a working product. The spec is a live Playwright spec in this checkout, run from ui/ with `pnpm test:e2e:live` against a backend on port 3000 and the console dev server on port 5180", + "verify": "after a fresh read of the page (the Overview rail's 最近动态 card can lag the update line, QA run #28545), open the stream by the Activity tab, the 最近动态 card's title or ?related=timeline (steps[5]); after a screenshot confirms the Changes chip is selected on the account's timeline stream, read its change lines — same contract ui/e2e/live/record-history-display.spec.ts pins on showcase_account, the showcase's enable.trackHistory object, at 1440×900 (its option labels, the localized Customer Since date and the resolved owner). The page reads sys_audit_log only for an object whose enable.trackHistory is true (ui/packages/app-shell/src/views/RecordDetailView.tsx, historyEnabled), and the rows reach the stream as field_change items (ui/packages/plugin-detail/src/recordTimelineStream.ts#auditEntriesToFeedItems). The chip also lists the stream's sys_activity created/updated rows, so attribute a line to the audit read before scoring it. ⛔ Never look for a tab named History: record page v3 removed it at every width (#27055; buildDefaultPageSchema.test.ts asserts the default tabs carry neither Activity nor History), so its absence fails a working product. The spec is a live Playwright spec in this checkout, run from ui/ with `pnpm test:e2e:live` against a backend on port 3000 and the console dev server on port 5180", "evidence": "screenshot + entries" }, { @@ -403,6 +403,12 @@ "date": "2026-11-15", "change": "steps[5]'s tab row re-pointed: QA run #33784 (at a557fa38) read 'Overview / Activity 2' at 1440 px with no panel tabs, because a related panel takes a row tab only once it has records and an empty one waits in the '+N' dropdown (RecordPageColumns.tsx partitionRecordTabsByRecords, ui/packages/plugin-detail/src/synth/recordTabRow.ts). Ledger row 9. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 21, + "date": "2026-11-20", + "change": "steps[5] and acceptance[4].verify re-pointed to the record page's tab rules and right rail (#35595, #35596): every related list is a tab of its own in its order, an empty one muted with no number, the width the row's only fold ('More N'), Activity last; the 动态 panel of the right column became the Overview rail's 最近动态 card (newest three, read-only), whose title opens the Activity tab. Supersedes the records-first row of #28469 (partitionRecordTabsByRecords is retired). No clause changed: the change lines are still read on the Activity tab after a reload. Read from source at the PR's head.", + "ref": "#35595" } ] }, @@ -1671,7 +1677,7 @@ "title": "Related lists derive from the relationship and page on the server — never fetch every child row — and are read-gated on both ends", "since": "v16", "status": "active", - "revision": 13, + "revision": 14, "priority": "P1", "surface": "browser", "personas": [ @@ -1693,7 +1699,7 @@ }, "steps": [ "open the Northwind account's full record page: from /_console/apps/com.example.showcase/showcase_account, clicking Northwind opens a ~720 px record DRAWER (the console's default record-open mode, ui/packages/app-shell/src/views/ObjectView.tsx), not the column-tier page steps[1] reads — open it full page with the drawer's 'Open as full page' (↗), or load /_console/apps/com.example.showcase/showcase_account/record/ID directly", - "screenshot at a column-tier width (a record view of 760 px or wider, which a 1440×900 window gives; ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor); enumerate the related lists. At 1440 px the page also draws its top-level tab row over the columns (Overview, Activity N, then one tab per related list that has records, e.g. Contacts 26; the empty ones in its '+N' dropdown; ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; QA run #33861), so a role=tab strip there is expected: enumerate the lists from the column layout under it. The primary lists (relatedList: 'primary' — Invoices on showcase_invoice.account, Projects on showcase_project.account) are body tables in the details column, and the non-primary children — Contacts among them — are compact cards in the related column, each naming at most 3 rows with no pager (packages/spec/src/data/field.zod.ts relatedList: 'true/absent = shown as a supporting list, a side card in the record's related column (the shared \"Related\" tab on the tabbed page)'). Only below 760 px is the page tabbed, with those cards under one 'Related' tab (?tab=related)", + "screenshot at a column-tier width (a record view of 760 px or wider, which a 1440×900 window gives; ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor); enumerate the related lists. The page draws the record's tab row — Overview (概览), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595) over the columns, so a role=tab strip is expected: enumerate the lists from it (QA run #33861 read the earlier records-first row). The primary lists (relatedList: 'primary' — Invoices on showcase_invoice.account, Projects on showcase_project.account) are body tables in the Overview tab's details column, and every non-primary child — Contacts among them — is a tab of its own whose face is the whole list with its pager; on Overview, the right rail's 其他相关 (Other related) group draws a card for each such list that HAS records, naming at most 3 rows with no pager (ui/packages/plugin-detail/src/RecordSummaryRail.tsx, #35596) (packages/spec/src/data/field.zod.ts relatedList: 'true/absent = shown as a supporting list, a side card in the record's related column (the shared \"Related\" tab on the tabbed page)'). Below 760 px the same tab row draws over one column: the details, then the rail", "open Contacts' whole list: its card's header or count chip enlarges it in place (?related=showcase_contact.account); capture the page-1 data request. An enlarged list whose block names no limit pages 25 rows (ui/packages/plugin-detail/src/RecordPageColumns.tsx, ENLARGED_PAGE_SIZE), so the pager reads 'Page 1 of 2' for Northwind's 26 contacts (QA run #27438)", "click next-page; capture the page-2 request; note the pager text ('Page 2 of 2', one row)", "diff page-1 and page-2 row ids for overlap", @@ -1832,6 +1838,12 @@ "date": "2026-11-15", "change": "steps[1] re-pointed: it said record page v3 draws no tab strip at the column tier, but at 1440 px QA run #33861 met both the two-column layout and the top-level tab row (Overview, Activity 0, Contacts 26, Field Zoo …), which RecordPageColumns draws over the columns. Ledger row 150. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 14, + "date": "2026-11-20", + "change": "steps[1] re-pointed (#35595, #35596): every related list is a tab of its own, empty or not, and the non-primary children are no longer compact cards in a related column — the Overview rail's 其他相关 group draws a 3-row card for each list with records, and the list's tab is its whole face with the pager. The shared Related tab below 760 px is gone: the same tab row draws over one column. No clause changed. Read from source at the PR's head.", + "ref": "#35595" } ] }, @@ -4040,7 +4052,7 @@ "title": "Record edit undo: toast Undo / Ctrl+Z restores the prior value through the API and logs a revert; undo after a concurrent change must not silently clobber", "since": "v16", "status": "active", - "revision": 6, + "revision": 7, "priority": "P2", "surface": "browser", "personas": [ @@ -4060,7 +4072,7 @@ "steps": [ "open a record; run the packaged undoable action (fixtures.requires[0]) on it; confirm the success toast shows an Undo button. An inline edit offers none by design", "click Undo (or press Ctrl+Z); capture the resulting update; re-read the record over the API and confirm the prior value is restored", - "read the record's field-change history on the record page's timeline stream, under its Changes chip (变更). Record page v3 draws no tab named History at any width (#27055). The stream's whole face, with its chips, is the 动态 (Activity) tab: open it from the header of the 动态 panel, the first panel of the record page's right column (below the details in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor), or by ?related=timeline (#27524). The panel itself shows only the newest lines, with no chips. Also read sys_audit_log for the record over the API, and confirm a revert entry was added (a forward write, not a silent rollback)", + "read the record's field-change history on the record page's timeline stream, under its Changes chip (变更). Record page v3 draws no tab named History at any width (#27055). The stream's whole face, with its chips, is the 动态 (Activity) tab: open it from the Activity tab of the record's tab row — Overview (概览), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595), from the title of the Overview tab's 最近动态 (Recent activity) card, in the right rail beside the details (below them in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor; ui/packages/plugin-detail/src/RecordSummaryRail.tsx, #35596), or by ?related=timeline (#27524). The rail card itself shows only the newest three lines, read-only, with no chips. Also read sys_audit_log for the record over the API, and confirm a revert entry was added (a forward write, not a silent rollback)", "press Ctrl+Shift+Z (redo); confirm the edited value is restored", "CONCURRENT-CLOBBER probe: in session A make the undoable edit; in session B change the SAME field and save; back in A, click Undo", "observe and FLAG whether A's undo carries an OCC guard or silently overwrites B's value" @@ -4145,6 +4157,12 @@ "date": "2026-10-29", "change": "steps[2] and acceptance[2] (clause, verify, evidence) re-pointed from the History tab to the record page v3 surface, the same shape records-forms.field-history-tracking took at its revision 10 (#27492). Record page v3 (#27055) removed the History tab at every width. The revert's oracle is now the record's sys_audit_log read over the API, with the timeline stream's Changes chip (located by width tier, recordPageTierFor) as the screenshot when the object tracks history. The clause's contract (the undo is a forward, audited write) is unchanged, and the item stays blocked(fixture)", "ref": "#27654" + }, + { + "revision": 7, + "date": "2026-11-20", + "change": "steps[2] re-pointed (#35595, #35596): the stream opens from the Activity tab of the record's tab row, from the title of the Overview rail's 最近动态 card (the right column's 动态 panel is retired), or ?related=timeline. No clause changed. Read from source at the PR's head.", + "ref": "#35595" } ] }, @@ -5569,7 +5587,7 @@ "title": "Per-field trackHistory: a tracked edit lands the ADR-0052 §5b old→new timeline summary with display values, an untracked edit does not, and object-level enable.trackHistory gates the record page's sys_audit_log field-change read and derived history op both ways", "since": "v15", "status": "active", - "revision": 13, + "revision": 14, "priority": "P1", "surface": "mixed", "personas": [ @@ -5590,7 +5608,7 @@ "boot the showcase on its own port and DB; sign in as admin; open a seeded account record", "edit the TRACKED select `industry` (e.g. Technology → Finance); save; read the record's sys_activity rows over the API and open the timeline", "edit an UNTRACKED field (e.g. website) alone; save; re-read sys_activity for the record", - "record the network log from page load, open the account record and select its timeline stream's Changes chip (变更). Record page v3 has no History tab at any width (#27055). The chips are on the stream's whole face, the 动态 (Activity) tab: open it from the Activity tab of the record page's tab row (Overview · Activity · the related panels, ui/packages/plugin-detail/src/RecordPageColumns.tsx), from the header of the 动态 panel, the first panel of the record page's right column at every width (below the details in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor), or by ?related=timeline (#27524). QA run #28656 read the tab row at 1440, 1000 and 700 px. Then open a seeded task's detail and read the network log again", + "record the network log from page load, open the account record and select its timeline stream's Changes chip (变更). Record page v3 has no History tab at any width (#27055). The chips are on the stream's whole face, the 动态 (Activity) tab: open it from the Activity tab of the record's tab row — Overview (概览), one tab per related list in its order (an empty one muted, with no number), Attachments, Approvals (while a request exists), then Activity (动态) last with its count, the tabs that do not fit folded into its 'More N' (更多 N) dropdown (ui/packages/plugin-detail/src/RecordPageColumns.tsx, the tab row; ui/packages/plugin-detail/src/RecordTabRow.tsx; #35595), from the title of the Overview tab's 最近动态 (Recent activity) card, in the right rail beside the details (below them in one column under 760 px, ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageTierFor; ui/packages/plugin-detail/src/RecordSummaryRail.tsx, #35596), or by ?related=timeline (#27524). QA run #28656 read the tab row at 1440, 1000 and 700 px. Then open a seeded task's detail and read the network log again", "GET /api/v1/auth/me/permissions and compare apiOperations for showcase_account vs showcase_task" ], "acceptance": [ @@ -5609,7 +5627,7 @@ { "clause": "the record page's sys_audit_log field-change history gates on OBJECT-level enable.trackHistory, both ways: the account detail (flag true) reads sys_audit_log and its timeline stream's Changes chip lists the tracked edits as old → new lines with display values; the task detail (no enable block — per-field flags alone do not summon it) makes NO sys_audit_log read", "oracle": "network", - "verify": "the network log after settle: one sys_audit_log read for the account record (at page load, at every width: the 动态 panel is on screen at open since #27524) and none for the task; screenshot the account's Changes chip showing the industry edit. Gating ruled at ui/packages/app-shell/src/views/RecordDetailView.tsx (historyEnabled: enable.trackHistory explicitly true, sys_audit_log registered, the viewed object not sys_audit_log itself; and the read serves only the synthesized page's stream, never an assigned page); the read's rows reach the stream through RecordFieldChangesContext as field_change items (ui/packages/plugin-detail/src/recordTimelineStream.ts#auditEntriesToFeedItems). The task half is over-determined (knownGaps): record which gate the verdict rests on. ⛔ An empty Changes chip is never an absence oracle: the chip also lists the stream's sys_activity created/updated rows (ACTIVITY_TYPE_TO_FEED_TYPE maps both to field_change). Measured on a seeded account, the chip showed a sys_activity 'Updated Account …' row beside the audit read. ⛔ Nor is a History tab: record page v3 removed it at every width (#27055; buildDefaultPageSchema.test.ts asserts 'no Activity or History tab'), so looking for one fails a working product (QA run #27438)", + "verify": "the network log after settle: one sys_audit_log read for the account record (at page load, at every width: the Overview rail's 最近动态 card draws the stream at open, #35596; a drawer, which draws no rail, reads it when its Activity tab opens) and none for the task; screenshot the account's Changes chip showing the industry edit. Gating ruled at ui/packages/app-shell/src/views/RecordDetailView.tsx (historyEnabled: enable.trackHistory explicitly true, sys_audit_log registered, the viewed object not sys_audit_log itself; and the read serves only the synthesized page's stream, never an assigned page); the read's rows reach the stream through RecordFieldChangesContext as field_change items (ui/packages/plugin-detail/src/recordTimelineStream.ts#auditEntriesToFeedItems). The task half is over-determined (knownGaps): record which gate the verdict rests on. ⛔ An empty Changes chip is never an absence oracle: the chip also lists the stream's sys_activity created/updated rows (ACTIVITY_TYPE_TO_FEED_TYPE maps both to field_change). Measured on a seeded account, the chip showed a sys_activity 'Updated Account …' row beside the audit read. ⛔ Nor is a History tab: record page v3 removed it at every width (#27055; buildDefaultPageSchema.test.ts asserts 'no Activity or History tab'), so looking for one fails a working product (QA run #27438)", "evidence": "the two network logs + the account's Changes screenshot" }, { @@ -5723,6 +5741,12 @@ "date": "2026-11-15", "change": "knownGaps[1] re-pointed: QA run #33861 closed the flag half live on a scratch object (per-field flags, no enable block, synthesized page), so the gap now names that route and keeps the code read as the fallback (ledger row 137). No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 14, + "date": "2026-11-20", + "change": "steps[3] and acceptance[2].verify re-pointed (#35595, #35596): the tab row is Overview, one tab per related list, Attachments, Approvals, Activity; the right column's 动态 panel became the Overview rail's 最近动态 card, which draws the stream at open, so the audit read at page load stands; a drawer draws no rail and reads it when its Activity tab opens. No clause changed. Read from source at the PR's head.", + "ref": "#35595" } ] }, diff --git a/ui/e2e/record-tabs-rail-35595.spec.ts b/ui/e2e/record-tabs-rail-35595.spec.ts new file mode 100644 index 00000000000..f5ff2f2b14e --- /dev/null +++ b/ui/e2e/record-tabs-rail-35595.spec.ts @@ -0,0 +1,591 @@ +import { test, expect, type Page } from '@playwright/test'; +import { compile } from 'tailwindcss'; +import { build, type Plugin, type Rollup } from 'vite'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { uiRoot } from '../scripts/ui-root.mjs'; + +/** + * GEOMETRY and INTERACTION pin for objectstack#35595 (the record page's tab + * row) and objectstack#35596 (the 概览 tab's right rail), zh-CN. + * + * - The tab row folds by WIDTH only: a row sized from its own measured + * tabs to hold the first eight draws exactly those and folds the tail + * into 「更多 N ▾」, whose items keep their counts; CONTROL, the same page + * at the 1184 px a 1440 window leaves draws every tab. + * - On 概览 the stage path and the key fields are at the top across the + * whole width — both columns; CONTROL, the details column beside the rail + * is narrower than they are. + * - The rail is the 概览 tab's: another tab open draws no rail and no + * strip; CONTROL, back on 概览 both are drawn again. + * - A rail card's title opens its tab; CONTROL, the 概览 tab returns. + * - A card measures radius 8, a 13 px title with a grey count, 26 px rows. + * + * ⚠️ A Playwright spec and not a vitest test: jsdom lays nothing out, so a + * width read there is 0 and the row's fold — which reads the row's own width + * — never runs. The vitest pins (`RecordTabRow.widthOnly-35595`, + * `RecordPageColumns.test.tsx`) hold the same rules against a width model. + * + * ## What is real here and what is a fixture + * + * REAL: plugin-detail's `RecordPageColumns`, `RecordTabRow` and + * `RecordSummaryRail`, the page synthesizer (`buildDefaultPageSchema` → + * `buildDefaultPageColumns`), the related-count store and the zh-Hans pack + * through `I18nProvider`, bundled by Vite from their source files and mounted + * in Chromium with React's client renderer; the stylesheet is real Tailwind, + * compiled for the classes on the page. Tabs and card titles are clicked + * with real pointer events. The bundling follows + * `e2e/list-header-narrow-35446.spec.ts`. + * + * FIXTURES, declared so nobody reads more into a green run than it says: + * + * - The blocks inside the page (`record:details`, `record:highlights`, + * `record:path`, the related lists, the 动态 stream) are boxes of a fixed + * height drawing their type, as the vitest pins stub them; the stream box + * reports a size of 4 the way the real stream does. What is measured is + * the page around them. + * - The data source is a literal: eight related lists (two of them empty), + * two attachments, one approval waiting on a named approver. + * - The record page's width is set by a frame, not by the shell: for the + * fold, a width computed from what the row measures its own tabs at + * (below); 1184 px (a 1440 window with the sidebar open) for its + * CONTROL; and 1024 px (a 1280 × 800 window with the sidebar open) for + * the 概览 placement and the rail. + * - Fonts are whatever the machine has, and the fold does not depend on + * them. A CJK label is about 13 px a glyph where a CJK font is installed + * and about 8 px where none is (measured: 概览 26 px against 16 px), so + * on a runner without one the whole row is ~580 px and fits a page any + * fixed width could fold elsewhere. The fold case therefore sizes the + * row from the row's own measurer: room for the first eight tabs and + * 「更多」, and half a tab short of the ninth. The assertions are which + * tabs are drawn, edges and sizes, not pixels of glyphs. + */ + +const REPO_ROOT = uiRoot(); +const source = (rel: string) => path.join(REPO_ROOT, rel); + +const THEME_CSS = source('packages/components/src/index.css'); +// The entry names workspace sources by path, never by package name: the e2e +// type-check program must import no workspace package (it builds nothing first). +const REACT_BINDINGS = source('packages/react/src/index.ts'); +const I18N = source('packages/i18n/src/index.ts'); +const PAGE_COLUMNS = source('packages/plugin-detail/src/RecordPageColumns.tsx'); +const SYNTH_COLUMNS = source('packages/plugin-detail/src/synth/recordPageColumns.ts'); +const SYNTH_PAGE = source('packages/plugin-detail/src/synth/buildDefaultPageSchema.ts'); +const TIMELINE_STREAM = source('packages/plugin-detail/src/recordTimelineStream.ts'); +// The store module `@object-ui/components` re-exports: one module, one store, in the bundle. +const COUNT_STORE = source('packages/components/src/hooks/related-count-store.ts'); + +/** A 1280 × 800 window with the 256 px sidebar open. */ +const PAGE_1280 = 1024; +/** A 1440 window with the sidebar open (the list specs' full page). */ +const PAGE_1440 = 1184; +/** The fold case's first draw (a 900 px window with the 256 px sidebar open): it is measured, then resized. */ +const PAGE_900 = 644; +/** The space between two tabs (`RecordTabRow`'s `gap-4`). */ +const TAB_GAP = 16; +/** How many tabs the fold case sizes its row to hold. */ +const FOLD_KEEPS = 8; + +interface Case { + name: string; + viewport: number; + frame: number; +} + +const ENTRY = '\0record-tabs-rail:entry'; +const REACT_SHIM = '\0record-tabs-rail:react'; +const STUB = '\0record-tabs-rail:stub'; + +/** `@object-ui/` to `packages//src`; the page's `@object-ui/react` to the shim. */ +function workspaceSources(): Plugin { + return { + name: 'record-tabs-rail-workspace-src', + enforce: 'pre', + async resolveId(id, importer) { + if (id === 'record-tabs-rail:react-real') { + return this.resolve(REACT_BINDINGS, importer, { skipSelf: true }); + } + const m = /^@object-ui\/([a-z0-9-]+)(?:\/(.+))?$/.exec(id); + if (!m) return null; + const [, pkg, sub] = m; + // The page's blocks are fixture boxes: plugin-detail's own modules read + // `SchemaRenderer` from the shim, everything else from the real module. + if (pkg === 'react' && !sub && importer && importer.includes(`${path.sep}plugin-detail${path.sep}src${path.sep}`)) { + return REACT_SHIM; + } + const target = + pkg === 'types' && sub === 'zod' + ? source('packages/types/src/zod/index.zod.ts') + : source(`packages/${pkg}/src${sub ? `/${sub}` : ''}`); + const resolved = await this.resolve(target, importer, { skipSelf: true }); + if (!resolved) throw new Error(`${id} did not resolve to a source file under ${target}`); + return resolved; + }, + }; +} + +/** The fixture block: a box of a fixed height naming its type; the stream reports a size. */ +const STUB_CODE = ` +import * as React from 'react'; +import { RecordTimelinePanelContext, RecordTimelineCountContext } from ${JSON.stringify(TIMELINE_STREAM)}; +const HEIGHT = { 'record:details': 360, 'record:highlights': 56, 'record:path': 40, 'record:related_list': 240, 'record:activity': 96, 'record:attachments': 120, 'record:approvals': 120 }; +export function SchemaRenderer({ schema }) { + const panel = React.useContext(RecordTimelinePanelContext); + const reporter = React.useContext(RecordTimelineCountContext); + const type = schema && schema.type; + React.useEffect(() => { + if (type !== 'record:activity') return; + if (panel) panel.onCount(4); + else if (reporter) reporter(4); + }, [type, panel, reporter]); + return React.createElement('div', { + 'data-node': type, + className: 'rounded-md border border-dashed border-border text-xs text-muted-foreground', + style: { height: (HEIGHT[type] || 48) + 'px' }, + }, type); +} +`; + +const SHIM_CODE = ` +export * from 'record-tabs-rail:react-real'; +export { SchemaRenderer } from ${JSON.stringify(STUB)}; +`; + +/** The page: the synthesized record page at the case's width, the host holding the open tab. */ +function entry(): Plugin { + const code = ` +import * as React from 'react'; +import { createRoot } from 'react-dom/client'; +import { RecordContextProvider } from 'record-tabs-rail:react-real'; +import { I18nProvider } from ${JSON.stringify(I18N)}; +import { RelatedCountStore } from ${JSON.stringify(COUNT_STORE)}; +import { RecordPageColumns } from ${JSON.stringify(PAGE_COLUMNS)}; +import { buildDefaultPageColumns, recordPageTierFor } from ${JSON.stringify(SYNTH_COLUMNS)}; +import { buildDefaultPageSchema } from ${JSON.stringify(SYNTH_PAGE)}; + +const h = React.createElement; +const c = window.__case; +const RELATED = [ + ['contact', 'account_id', '联系人', 4], + ['opportunity', 'account_id', '商机', 3], + ['case', 'account_id', '个案', 0], + ['contract', 'account_id', '合同', 1], + ['quote', 'account_id', '报价单', 2], + ['invoice', 'account_id', '发票', 0], + ['campaign_member', 'account_id', '活动成员', 5], + ['task', 'what_id', '任务', 6], +]; +const TOTALS = Object.fromEntries(RELATED.map(([o, , , n]) => [o, n])); +TOTALS.sys_attachment = 2; +const rowsOf = (object, n) => Array.from({ length: Math.min(n, 5) }, (_, i) => ({ + id: object + '-' + i, name: object + ' ' + (i + 1), file_name: 'file-' + (i + 1) + '.pdf', size: 2048 * (i + 1), +})); +const dataSource = { + find: async (object) => ({ data: rowsOf(object, TOTALS[object] || 0), total: TOTALS[object] || 0 }), + getObjectSchema: async () => ({ fields: { name: { type: 'text' } } }), +}; +const approvals = { + available: true, + requests: [{ id: 'req-1' }], + pendingRequest: { id: 'req-1', step_label: '经理审批', pending_approvers: ['u2'], pending_approver_names: { u2: '王经理' } }, +}; +const page = buildDefaultPageSchema( + { name: 'account', label: '客户', enable: { files: true }, fields: { name: { type: 'text' }, phone: { type: 'phone' }, rating: { type: 'select' } } }, + { + related: RELATED.map(([objectName, relationshipField, title]) => ({ objectName, relationshipField, title })), + highlightFields: ['phone'], + statusField: 'rating', + stages: [{ value: 'cold', label: '冷' }, { value: 'warm', label: '温' }, { value: 'hot', label: '热' }], + approvals: { count: 1, node: { approvals, currentUserId: 'u1' } }, + }, +); +const columns = buildDefaultPageColumns(page); + +function Host() { + const [open, setOpen] = React.useState(undefined); + return h(RecordPageColumns, { + tier: recordPageTierFor(c.frame), + columns, + enlargedRelated: open, + onEnlargeRelated: setOpen, + onCloseEnlargedRelated: () => setOpen(undefined), + relatedFieldsOf: () => ({ name: { type: 'text' } }), + }); +} + +const root = createRoot(document.getElementById('root')); +let mounts = 0; +// A fresh page: the row keeps what it measured on its first frame, so the +// spec mounts it again once the stylesheet is in, as a page load would. +window.__remount = () => { + RelatedCountStore._reset(); + root.render( + h(I18nProvider, { key: ++mounts, config: { defaultLanguage: 'zh', detectBrowserLanguage: false } }, + h(RecordContextProvider, { objectName: 'account', recordId: 'acc-1', data: { id: 'acc-1', name: '示例客户' }, dataSource }, + h('div', { id: 'frame', className: 'bg-background', style: { width: c.frame + 'px' } }, h(Host)))), + ); +}; +window.__remount(); +`; + return { + name: 'record-tabs-rail-entry', + resolveId: (id) => (id === 'record-tabs-rail:entry' ? ENTRY : id === REACT_SHIM || id === STUB ? id : null), + load: (id) => (id === ENTRY ? code : id === REACT_SHIM ? SHIM_CODE : id === STUB ? STUB_CODE : null), + }; +} + +/** Bundle the page once, from source, to one ES module held in memory. */ +async function bundlePage(): Promise { + const result = await build({ + configFile: false, + root: REPO_ROOT, + // Out of the tree: this run must leave nothing behind in the checkout. + cacheDir: path.join(os.tmpdir(), 'objectui-record-tabs-rail'), + logLevel: 'error', + mode: 'production', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [workspaceSources(), entry()], + build: { + write: false, + minify: false, + target: 'es2022', + modulePreload: false, + reportCompressedSize: false, + rollupOptions: { + input: 'record-tabs-rail:entry', + output: { format: 'es', codeSplitting: false }, + }, + }, + }); + const outputs = (Array.isArray(result) ? result : [result]) as Rollup.RollupOutput[]; + const chunks = outputs.flatMap((o) => o.output).filter((o): o is Rollup.OutputChunk => o.type === 'chunk'); + if (chunks.length !== 1) throw new Error(`expected one bundled chunk, got ${chunks.length}`); + return chunks[0].code; +} + +/** The real theme sheet, compiled for the given class candidates. */ +async function tailwindFor(candidates: string[]): Promise { + const requireFromComponents = createRequire(source('packages/components/package.json')); + const twEntry = requireFromComponents.resolve('tailwindcss/index.css'); + const compiler = await compile(readFileSync(THEME_CSS, 'utf8'), { + base: path.dirname(THEME_CSS), + loadStylesheet: async (id: string, base: string) => { + const file = id === 'tailwindcss' ? twEntry : path.resolve(base, id); + return { path: file, base: path.dirname(file), content: readFileSync(file, 'utf8') }; + }, + loadModule: async (id: string) => { + const file = requireFromComponents.resolve(id); + const mod = await import(pathToFileURL(file).href); + return { path: file, base: path.dirname(file), module: mod.default ?? mod }; + }, + }); + return compiler.build(candidates); +} + +let bundle = ''; + +/** Compile the stylesheet until the page's class set stops growing. */ +async function styleUntilStable(page: Page, compiled: Set): Promise { + const classesOnPage = () => + page.evaluate(() => [ + ...new Set( + [...document.querySelectorAll('[class]')].flatMap((el) => (el.getAttribute('class') ?? '').split(/\s+/)).filter(Boolean), + ), + ]); + for (let round = 0; ; round++) { + const candidates = await classesOnPage(); + if (round > 0 && candidates.every((cls) => compiled.has(cls))) break; + if (round === 5) throw new Error('the page kept adding classes; the stylesheet never caught up'); + candidates.forEach((cls) => compiled.add(cls)); + const css = await tailwindFor([...compiled]); + await page.evaluate((text) => { + let sheet = document.getElementById('tailwind'); + if (!sheet) { + sheet = document.createElement('style'); + sheet.id = 'tailwind'; + document.head.appendChild(sheet); + } + sheet.textContent = text; + }, css); + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + } +} + +/** What the row and the rail show, as one string: the page holds still when it stops changing. */ +const face = (page: Page) => + page.evaluate(() => { + const tabs = [...document.querySelectorAll('[role="tab"]')].map((el) => el.textContent).join('|'); + const more = document.querySelector('[data-record-tab-more]')?.textContent ?? ''; + const cards = [...document.querySelectorAll('[data-record-summary-card]')] + .filter((el) => !(el as HTMLElement).hidden) + .map((el) => el.textContent) + .join('|'); + return `${tabs}#${more}#${cards}`; + }); + +async function settle(page: Page, compiled: Set): Promise { + let last = ''; + for (let i = 0; i < 20; i++) { + const now = await face(page); + if (now === last) break; + last = now; + await page.waitForTimeout(300); + } + await styleUntilStable(page, compiled); +} + +/** Mount the case, style it, and wait until the row and the rail hold still. */ +async function mount(page: Page, c: Case): Promise> { + await page.setViewportSize({ width: c.viewport, height: 800 }); + await page.setContent('
'); + await page.evaluate((value) => { + (window as unknown as { __case: Case }).__case = value; + }, c); + await page.addScriptTag({ content: bundle, type: 'module' }); + await page.locator('[data-page-type="record"]').waitFor({ state: 'attached', timeout: 30_000 }); + const compiled = new Set(); + await styleUntilStable(page, compiled); + await page.evaluate(() => document.fonts?.ready); + await page.evaluate(() => (window as unknown as { __remount: () => void }).__remount()); + await settle(page, compiled); + return compiled; +} + +interface RowReading { + shown: string[]; + more: string | null; + /** Tabs whose box spills past the row's right edge. */ + spill: string[]; + rowWidth: number; + /** Each drawn tab's width, in order. */ + widths: number[]; + /** What the row measures each tab of the page at, in order (its off-screen measurer), to 0.1 px. */ + measured: number[]; + /** What the row measures its 「更多 N ▾」 trigger at, to 0.1 px. */ + moreMeasured: number; + /** The row's width, unrounded. */ + rowExact: number; +} + +const readRow = (page: Page): Promise => + page.evaluate(() => { + const row = document.querySelector('[data-record-tab-row]')!; + const rr = row.getBoundingClientRect(); + const tabs = [...row.querySelectorAll('[role="tab"]')]; + return { + shown: tabs.map((el) => el.getAttribute('data-record-tab') ?? ''), + more: row.querySelector('[data-record-tab-more]')?.textContent ?? null, + spill: [...tabs, ...row.querySelectorAll('[data-record-tab-more]')] + .filter((el) => el.getBoundingClientRect().right > rr.right + 0.5) + .map((el) => el.getAttribute('data-record-tab') ?? 'more'), + rowWidth: Math.round(rr.width), + widths: tabs.map((el) => Math.round(el.getBoundingClientRect().width)), + measured: [...document.querySelectorAll('[data-record-tab-measure]')].map( + (el) => Math.round(el.getBoundingClientRect().width * 10) / 10, + ), + moreMeasured: + Math.round((document.querySelector('[data-record-tab-measure-more]')?.getBoundingClientRect().width ?? 0) * 10) / 10, + rowExact: rr.width, + }; + }); + +/** Every tab the page offers, in order: 概览, the eight lists, 附件, 审批, 动态. */ +const ALL_TABS = [ + 'overview', + 'contact.account_id', + 'opportunity.account_id', + 'case.account_id', + 'contract.account_id', + 'quote.account_id', + 'invoice.account_id', + 'campaign_member.account_id', + 'task.what_id', + 'attachments', + 'approvals', + 'timeline', +]; + +function report(testInfo: import('@playwright/test').TestInfo, name: string, reading: unknown): void { + testInfo.annotations.push({ type: `record-tabs-rail@${name}`, description: JSON.stringify(reading) }); + process.stdout.write(`[record-tabs-rail ${name}] ${JSON.stringify(reading)}\n`); +} + +const box = (page: Page, selector: string) => + page.evaluate((sel) => { + const el = document.querySelector(sel); + if (!el) return null; + const r = el.getBoundingClientRect(); + return { left: Math.round(r.left), right: Math.round(r.right), top: Math.round(r.top), width: Math.round(r.width) }; + }, selector); + +test.describe('the record page\'s tabs and 概览 rail, zh-CN (objectstack#35595, objectstack#35596)', () => { + test.skip(({ browserName }) => browserName !== 'chromium', 'one engine is enough for a layout pin'); + + test.beforeAll(async () => { + test.setTimeout(240_000); + bundle = await bundlePage(); + }); + + test('a row with room for eight tabs draws those eight and folds the tail into 「更多 N ▾」, whose items keep their counts', async ({ page }, testInfo) => { + test.setTimeout(180_000); + // Draw once to read what the row measures each tab at, in this machine's + // fonts, and what the page around the row takes. + await mount(page, { name: 'foldMeasure', viewport: 1280, frame: PAGE_900 }); + const first = await readRow(page); + report(testInfo, 'foldMeasure', first); + expect(first.measured).toHaveLength(ALL_TABS.length); + const sum = (widths: number[]) => widths.reduce((a, b) => a + b, 0) + TAB_GAP * Math.max(0, widths.length - 1); + // The row the page draws: the first eight with their gaps, a gap, 「更多」 — + // and half of the ninth tab (with its gap) to spare, so it fits no ninth. + const kept = sum(first.measured.slice(0, FOLD_KEEPS)); + const ninth = first.measured[FOLD_KEEPS] + TAB_GAP; + const row = kept + TAB_GAP + first.moreMeasured + ninth / 2; + const frame = Math.round(PAGE_900 - first.rowExact + row); + // The precondition that makes this a fold and not a no-op: every tab does not fit the row. + expect(sum(first.measured), 'the tabs fit the row, so nothing can fold').toBeGreaterThan(row); + await mount(page, { name: 'fold', viewport: 1280, frame }); + const r = await readRow(page); + report(testInfo, 'fold', { frame, row, ...r }); + expect(Math.abs(r.rowExact - row), 'the row is not the width it was sized to').toBeLessThan(1); + expect(r.more, 'no 「更多」 on a row narrower than its tabs').toMatch(/^更多 \d+$/); + const folded = Number(r.more!.replace('更多 ', '')); + // Width alone decides: the row keeps the FRONT of the order, empty lists + // included — exactly the eight it has room for, no fewer and no more. + expect(r.shown).toEqual(ALL_TABS.slice(0, FOLD_KEEPS)); + expect(folded).toBe(ALL_TABS.length - FOLD_KEEPS); + expect(r.spill, 'a tab spills past the row').toEqual([]); + await page.locator('[data-record-tab-more]').click(); + const items = page.getByRole('menuitem'); + await expect(items).toHaveCount(folded); + const menu = await items.evaluateAll((els) => + els.map((el) => ({ + id: el.getAttribute('data-record-tab-menu-item'), + count: el.querySelector('[data-record-tab-count]')?.textContent ?? null, + dot: !!el.querySelector('[data-record-tab-dot]'), + })), + ); + report(testInfo, 'fold-menu', menu); + expect(menu.map((m) => m.id)).toEqual(ALL_TABS.slice(r.shown.length)); + // The folded lists keep their numbers; 审批 its dot; 动态 its size. + const byId = Object.fromEntries(menu.map((m) => [m.id, m])); + expect(byId['task.what_id']?.count).toBe('6'); + expect(byId['approvals']?.dot).toBe(true); + expect(byId['timeline']?.count).toBe('4'); + }); + + test('CONTROL: the same page at 1184 px draws every tab, the empty ones muted, and no 「更多」', async ({ page }, testInfo) => { + test.setTimeout(120_000); + await mount(page, { name: 'full1184', viewport: 1440, frame: PAGE_1440 }); + const r = await readRow(page); + report(testInfo, 'full1184', r); + expect(r.more).toBeNull(); + expect(r.shown).toEqual(ALL_TABS); + expect(r.spill).toEqual([]); + const empty = await page.locator('[data-record-tab-empty]').evaluateAll((els) => els.map((el) => el.getAttribute('data-record-tab'))); + expect(empty).toEqual(['case.account_id', 'invoice.account_id']); + const muted = await page + .locator('[data-record-tab="case.account_id"] [data-record-tab-label]') + .evaluate((el) => Number(getComputedStyle(el).opacity)); + expect(muted).toBeLessThan(1); + expect(await page.locator('[data-record-tab="case.account_id"] [data-record-tab-count]').count()).toBe(0); + }); + + test('1280 × 800: on 概览 the stage path and the key fields span both columns, above them', async ({ page }, testInfo) => { + test.setTimeout(120_000); + await mount(page, { name: 'overview1280', viewport: 1280, frame: PAGE_1280 }); + const strip = await box(page, '[data-record-overview-strip]'); + const details = await box(page, '[data-record-column="details"]'); + const rail = await box(page, '[data-record-column="right"]'); + const row = await box(page, '[data-record-tab-row]'); + report(testInfo, 'overview1280', { strip, details, rail, row }); + expect(strip && details && rail && row).toBeTruthy(); + // Across the whole width: from the details' left edge to the rail's right edge. + expect(Math.abs(strip!.left - details!.left)).toBeLessThanOrEqual(1); + expect(Math.abs(strip!.right - rail!.right)).toBeLessThanOrEqual(1); + // Below the tab row, above both columns. + expect(strip!.top).toBeGreaterThanOrEqual(row!.top); + expect(details!.top).toBeGreaterThan(strip!.top); + expect(rail!.top).toBeGreaterThan(strip!.top); + // CONTROL: the details column beside the rail is narrower than the strip. + expect(details!.width).toBeLessThan(strip!.width - 200); + }); + + test('the rail and the strip are 概览\'s: another tab draws neither; CONTROL, 概览 brings both back', async ({ page }, testInfo) => { + test.setTimeout(120_000); + const compiled = await mount(page, { name: 'otherTab1280', viewport: 1280, frame: PAGE_1280 }); + // CONTROL first: on 概览 both are drawn. + await expect(page.locator('[data-record-column="right"]')).toHaveCount(1); + await expect(page.locator('[data-record-overview-strip]')).toHaveCount(1); + await page.locator('[data-record-tab="contact.account_id"]').click(); + await expect(page.locator('[data-record-tab="contact.account_id"]')).toHaveAttribute('aria-selected', 'true'); + await settle(page, compiled); + const opened = await page.evaluate(() => ({ + rail: document.querySelectorAll('[data-record-column="right"]').length, + cards: document.querySelectorAll('[data-record-summary-card]').length, + strip: document.querySelectorAll('[data-record-overview-strip], [data-node="record:highlights"], [data-node="record:path"]').length, + face: document.querySelector('[data-related-enlarged]')?.getAttribute('data-related-enlarged') ?? null, + })); + report(testInfo, 'otherTab1280', opened); + expect(opened).toEqual({ rail: 0, cards: 0, strip: 0, face: 'contact.account_id' }); + await page.locator('[data-record-tab="overview"]').click(); + await expect(page.locator('[data-record-column="right"]')).toHaveCount(1); + await expect(page.locator('[data-record-overview-strip]')).toHaveCount(1); + }); + + test('a rail card\'s title opens its tab; the rail reads 审批, 附件, 最近动态, 其他相关, sized 8 / 13 / 26', async ({ page }, testInfo) => { + test.setTimeout(120_000); + await mount(page, { name: 'railClick1280', viewport: 1280, frame: PAGE_1280 }); + const rail = await page.evaluate(() => { + const cards = [...document.querySelectorAll('[data-record-summary-card]')].filter((el) => !el.hidden); + const first = cards[0]; + const title = first.querySelector('[data-record-summary-card-title]')!; + const row = document.querySelector('[data-record-summary-row]')!; + const count = document.querySelector('[data-record-summary-card-count]')!; + return { + order: cards.map((el) => el.getAttribute('data-record-summary-card')), + rows: cards.map((el) => el.querySelectorAll('[data-record-summary-row]').length), + radius: getComputedStyle(first).borderTopLeftRadius, + titleSize: getComputedStyle(title).fontSize, + rowHeight: Math.round(row.getBoundingClientRect().height), + countColor: getComputedStyle(count).color, + titleColor: getComputedStyle(title).color, + other: document.querySelector('[data-record-summary-other]')?.textContent ?? null, + emptyLine: /还有\s*\d+\s*个空关联/.test(document.body.textContent ?? ''), + }; + }); + report(testInfo, 'railClick1280', rail); + // 审批, 附件, 最近动态, then 其他相关: the six lists with records, in their order. + expect(rail.order).toEqual([ + 'approvals', + 'attachments', + 'timeline', + 'contact.account_id', + 'opportunity.account_id', + 'contract.account_id', + 'quote.account_id', + 'campaign_member.account_id', + 'task.what_id', + ]); + expect(Math.max(...rail.rows)).toBeLessThanOrEqual(3); + expect(rail.radius).toBe('8px'); + expect(rail.titleSize).toBe('13px'); + expect(rail.rowHeight).toBe(26); + expect(rail.countColor).not.toBe(rail.titleColor); + expect(rail.other).toBe('其他相关'); + expect(rail.emptyLine).toBe(false); + // The whole title opens the tab. + await page.locator('[data-record-summary-card="quote.account_id"] [data-record-summary-card-title]').click(); + await expect(page.locator('[data-record-tab="quote.account_id"]')).toHaveAttribute('aria-selected', 'true'); + await expect(page.locator('[data-related-enlarged="quote.account_id"]')).toHaveCount(1); + // CONTROL: 概览 returns, and the rail with it. + await page.locator('[data-record-tab="overview"]').click(); + await expect(page.locator('[data-record-tab="overview"]')).toHaveAttribute('aria-selected', 'true'); + await expect(page.locator('[data-record-summary-card="quote.account_id"]')).toHaveCount(1); + await page.locator('[data-record-summary-card="approvals"] [data-record-summary-card-title]').click(); + await expect(page.locator('[data-record-tab="approvals"]')).toHaveAttribute('aria-selected', 'true'); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.accessibleNames-12625.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.accessibleNames-12625.test.tsx index 7f75f34a258..e9e69570681 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.accessibleNames-12625.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.accessibleNames-12625.test.tsx @@ -115,7 +115,10 @@ async function mountLeadPage() { const objects = [LEAD, TASK]; const findOne = vi.fn(async () => ({ id: 'L1', name: 'Ada', company: 'Acme', city: 'Paris' })); const dataSource = { - find: vi.fn(async () => ({ data: [] })), + // The lead has one task, so the right rail draws its card (objectstack#35596). + find: vi.fn(async (object: string) => + object === 'task' ? { data: [{ id: 't1', subject: 'Call back' }], total: 1 } : { data: [] }, + ), findOne, create: vi.fn(async () => ({})), update: vi.fn(async () => ({})), @@ -170,11 +173,13 @@ afterEach(() => { }); describe('objectui#12625 — the record page names its regions, header actions and section headers', () => { - it('the right column and its panels are named by their labels', async () => { + it('the right column and its cards are named by their labels; the 动态 tab by its label', async () => { await mountLeadPage(); const right = screen.getByRole('complementary', { name: 'Right column' }); expect(right).toBeInTheDocument(); - expect(within(right).getByRole('region', { name: 'Activity' })).toBeInTheDocument(); + // objectstack#35595 / #35596 — the stream is the Activity tab; the rail's + // cards are regions named by their titles. + expect(screen.getByRole('tab', { name: /^Activity/ })).toBeInTheDocument(); expect(await within(right).findByRole('region', { name: 'Task' })).toBeInTheDocument(); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.activityMapIdentity-5878.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.activityMapIdentity-5878.test.tsx index 005967e1b89..ef2b555859e 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.activityMapIdentity-5878.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.activityMapIdentity-5878.test.tsx @@ -180,7 +180,8 @@ function makeMetadata() { function tree(dataSource: any) { return ( - + // objectstack#35595 — the whole stream, composer included, is the 动态 tab's face; the 概览 rail shows a read-only peek. + >) => render( - + // objectstack#35595 — the whole stream, composer included, is the 动态 tab's face; the 概览 rail shows a read-only peek. + { + stubApprovalsApi(pendingRequest({ can_act: true, is_submitter: false, can_override: false })); + const { container } = renderRecordPage(); + const tag = await screen.findByTestId('record-approval-tag'); + // CONTROL: 概览 draws no approvals panel and no tab face. + expect(container.querySelector('[data-testid="record-approvals-panel"]')).toBeNull(); + expect(container.querySelector('[data-related-enlarged]')).toBeNull(); + fireEvent.click(tag); + await waitFor(() => expect(container.querySelector('[data-related-enlarged="approvals"]')).not.toBeNull()); + expect(container.querySelector('[role="tab"][data-record-tab="approvals"]')?.getAttribute('aria-selected')).toBe('true'); + }); + it('a reject from the record page requires its reason', async () => { stubApprovalsApi(pendingRequest({ can_act: true, is_submitter: false, can_override: false })); renderRecordPage(); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.childWriteRefreshesParent-12244.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.childWriteRefreshesParent-12244.test.tsx index 0cab313de82..463e22ba496 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.childWriteRefreshesParent-12244.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.childWriteRefreshesParent-12244.test.tsx @@ -47,7 +47,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, cleanup, act, within } from '@testing-library/react'; +import { render, screen, waitFor, cleanup, act, within, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { MetadataCtx, notifyDataChanged, useMutationInvalidationBridge } from '@object-ui/react'; @@ -259,10 +259,19 @@ async function settledPage(objects: readonly unknown[] = OBJECTS) { renderPage(backend.ds, objects); await waitFor(() => expect(parentReads(backend.ds)).toBe(1)); await screen.findByText('Seat licence'); - await waitFor(() => expect(figureShown(backend.rollup())).toBe(true)); + // objectstack#35595 — the key fields (the rollup among them) are the 概览 + // tab's: the list's tab, open here, draws none. + expect(figureShown(backend.rollup())).toBe(false); return backend; } +/** Back to 概览, where the highlight strip draws the parent's rollup. */ +async function toOverview() { + await act(async () => { + fireEvent.click(document.querySelector('[role="tab"][data-record-tab="overview"]') as HTMLElement); + }); +} + beforeEach(() => { cleanup(); RelatedCountStore._reset(); @@ -305,11 +314,14 @@ describe('RecordDetailView — a child write in a related list refreshes the par await waitFor(() => expect(ds.delete).toHaveBeenCalledWith(CHILD, 'l-1')); expect(rollup()).toBe(3000); await waitFor(() => expect(parentReads(ds)).toBe(2)); - await waitFor(() => expect(figureShown(3000)).toBe(true)); - expect(figureShown(9000)).toBe(false); // In place: the same header node, the list's face still the open one. expect(document.querySelector(HEADER)).toBe(headerBefore); expect(document.querySelector(`[data-related-enlarged="${CHILD}.${PARENT}"]`)).not.toBeNull(); + // 概览 draws the re-read row: the recomputed total, with no read of its own. + await toOverview(); + await waitFor(() => expect(figureShown(3000)).toBe(true)); + expect(figureShown(9000)).toBe(false); + expect(parentReads(ds)).toBe(2); }); it('a child update through the dataSource (the form overlay\'s save) re-reads the parent', async () => { @@ -322,8 +334,9 @@ describe('RecordDetailView — a child write in a related list refreshes the par expect(rollup()).toBe(12000); await waitFor(() => expect(parentReads(ds)).toBe(2)); - await waitFor(() => expect(figureShown(12000)).toBe(true)); expect(document.querySelector(HEADER)).toBe(headerBefore); + await toOverview(); + await waitFor(() => expect(figureShown(12000)).toBe(true)); }); it('a child row action that bypasses the dataSource (an object-wide child change) re-reads the parent', async () => { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.fallbackRecordTabs-35595.test.ts b/ui/packages/app-shell/src/views/RecordDetailView.fallbackRecordTabs-35595.test.ts new file mode 100644 index 00000000000..15ba33cdc8c --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.fallbackRecordTabs-35595.test.ts @@ -0,0 +1,77 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35595 — a record page drawn as written (an authored page, or a + * synthesized one whose strip cannot be laid out) that does not place the + * record's approval or attachments panel gets them as tabs of its first + * `page:tabs` strip — 「附件」 then 「审批」, after its own tabs — and no longer + * at the page's foot. A page with no strip keeps the foot: there is nowhere + * else to put them. The page comes back by reference when nothing is added, + * so a page with nothing to add re-renders nothing. + */ + +import { describe, it, expect } from 'vitest'; +import { withFallbackRecordTabs } from './RecordDetailView'; + +const APPROVALS = { approvals: { available: true, requests: [{ id: 'r1' }], pendingRequest: { id: 'r1' } }, currentUserId: 'u1' }; +const details = { type: 'record:details', properties: {} }; + +const authored = (tabs: Record) => ({ + type: 'record', + regions: [{ name: 'main', components: [{ type: 'page:header' }, tabs, { type: 'page:tabs', properties: { items: [{ label: 'Second', value: 'second', children: [] }] } }] }], +}); +const firstTabs = (page: any) => page.regions[0].components[1]; +const values = (tabs: any) => (tabs.properties?.items ?? tabs.items).map((item: any) => item.value); + +describe('withFallbackRecordTabs (objectstack#35595)', () => { + it('appends 附件 then 审批 to the FIRST strip, after its own tabs; the second strip is untouched', () => { + const page = authored({ type: 'page:tabs', properties: { items: [{ label: 'Details', value: 'details', children: [details] }] } }); + const out = withFallbackRecordTabs(page, { approvals: APPROVALS, attachments: true }); + expect(out.approvals).toBe(true); + expect(out.attachments).toBe(true); + expect(values(firstTabs(out.page))).toEqual(['details', 'attachments', 'approvals']); + const items = firstTabs(out.page).properties.items; + expect(items[1].children).toEqual([{ type: 'record:attachments', properties: {} }]); + expect(items[2].children).toEqual([{ type: 'record:approvals', properties: APPROVALS }]); + expect(values(out.page.regions[0].components[2])).toEqual(['second']); + // The input is not mutated. + expect(values(firstTabs(page))).toEqual(['details']); + }); + + it('reads the strip\'s items in either spelling (`properties.items` or `items`)', () => { + const page = authored({ type: 'page:tabs', items: [{ label: 'Details', value: 'details', children: [details] }] }); + const out = withFallbackRecordTabs(page, { approvals: null, attachments: true }); + expect(values(firstTabs(out.page))).toEqual(['details', 'attachments']); + expect(out).toMatchObject({ approvals: false, attachments: true }); + }); + + it('finds a strip nested in a component\'s children', () => { + const page = { + type: 'record', + regions: [{ name: 'main', components: [{ type: 'page:card', children: [{ type: 'page:tabs', properties: { items: [{ label: 'A', value: 'a', children: [] }] } }] }] }], + }; + const out = withFallbackRecordTabs(page, { approvals: APPROVALS, attachments: false }); + expect(values(out.page.regions[0].components[0].children[0])).toEqual(['a', 'approvals']); + expect(out).toMatchObject({ approvals: true, attachments: false }); + }); + + it('a page with no strip keeps the foot: nothing is added and the page comes back by reference', () => { + const page = { type: 'record', regions: [{ name: 'main', components: [details] }] }; + const out = withFallbackRecordTabs(page, { approvals: APPROVALS, attachments: true }); + expect(out.page).toBe(page); + expect(out).toMatchObject({ approvals: false, attachments: false }); + }); + + it('CONTROL: nothing to add returns the page by reference', () => { + const page = authored({ type: 'page:tabs', properties: { items: [{ label: 'Details', value: 'details', children: [details] }] } }); + const out = withFallbackRecordTabs(page, { approvals: null, attachments: false }); + expect(out.page).toBe(page); + expect(out).toMatchObject({ approvals: false, attachments: false }); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.feedLoadFailure-29188.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.feedLoadFailure-29188.test.tsx index 54c97b41b35..c6fbd1dccc5 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.feedLoadFailure-29188.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.feedLoadFailure-29188.test.tsx @@ -197,7 +197,7 @@ beforeEach(() => { }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); -async function boot(answers: Answers = {}) { +async function boot(answers: Answers = {}, search = '') { const { fetch, held } = heldTransport(answers); vi.stubGlobal('fetch', fetch); const ds = new ObjectStackAdapter({ baseUrl: BASE, fetch, autoReconnect: false }); @@ -209,7 +209,7 @@ async function boot(answers: Answers = {}) { } as never; const page = (id: string) => ( - + {}} objectNameOverride={OBJECT} recordIdOverride={id} /> @@ -230,6 +230,13 @@ const NO_COMMENTS = { comments: [], reactions: { records: [] } }; const NO_ACTIVITY = { total: 0, records: [] }; const peekOf = (c: HTMLElement) => c.querySelector('[data-record-timeline-peek]') as HTMLElement; +/** + * objectstack#35595 / #35596 — the stream's whole face is the 动态 tab + * (`?related=timeline`). An empty stream draws no card on the 概览 rail, so + * its empty state is read there. + */ +const ON_TIMELINE = '?related=timeline'; +const faceOf = (c: HTMLElement) => c.querySelector('[data-related-enlarged="timeline"]') as HTMLElement; const failedSources = (c: HTMLElement) => Array.from(c.querySelectorAll('[data-failed-source]')).map((e) => e.getAttribute('data-failed-source')); const retryButton = (c: HTMLElement) => c.querySelector('[data-feed-retry]') as HTMLButtonElement | null; @@ -237,8 +244,8 @@ const retryButton = (c: HTMLElement) => c.querySelector('[data-feed-retry]') as const timelineTab = (c: HTMLElement) => Array.from(c.querySelectorAll('[role="tab"]')).find((t) => /^Activity/.test(t.textContent ?? ''))?.textContent; /** Open the record over an adapter that reads every stream on its own. */ -async function bootDirect(answers: Answers) { - const booted = await boot(answers); +async function bootDirect(answers: Answers, search = '') { + const booted = await boot(answers, search); Object.assign(booted.ds, { getRecordPage: undefined, prefetchRecordPage: undefined }); return booted; } @@ -336,11 +343,11 @@ describe('objectstack#29188 — controls', () => { }); it('an empty 200 on direct reads still shows the empty state, with no notice', async () => { - const { held, open } = await bootDirect({}); + const { held, open } = await bootDirect({}, ON_TIMELINE); const view = open(); await settle(held); - expect(peekOf(view.container).textContent).toContain(EMPTY_ACTIVITY); - expect(failedSources(peekOf(view.container))).toEqual([]); + expect(faceOf(view.container).textContent).toContain(EMPTY_ACTIVITY); + expect(failedSources(faceOf(view.container))).toEqual([]); }); it('a refused (403) discussion part keeps the no-permission state and offers no Retry', async () => { @@ -359,7 +366,8 @@ describe('objectstack#29188 — controls', () => { describe('objectstack#29188 — attachments (pin: main already shows the failure)', () => { it('a 500 attachments part shows the panel\'s load-failure state with a Retry, and no count', async () => { - const { held, open } = await boot({ attachments: FAIL }); + // objectstack#35595 — the panel is the 附件 tab's face. + const { held, open } = await boot({ attachments: FAIL }, '?related=attachments'); const view = open(); await settle(held); expect(view.container.querySelector('[data-testid="record-attachments-unavailable"]')).not.toBeNull(); @@ -437,7 +445,7 @@ describe('objectstack#30145 — navigating away from a failed feed read does not }); it('direct reads: A\'s sys_comment 500 settles after navigating to B, which stays clean', async () => { - const { held, open, navigate } = await bootDirect({ failGet: ['sys_comment@c1'] }); + const { held, open, navigate } = await bootDirect({ failGet: ['sys_comment@c1'] }, ON_TIMELINE); const view = open(); await idle(); const aComment = readsOf(held, 'sys_comment').filter((h) => !h.released); @@ -450,11 +458,11 @@ describe('objectstack#30145 — navigating away from a failed feed read does not if (pending.length === 0) break; await release(pending); } - expect(failedSources(peekOf(view.container))).toEqual([]); + expect(failedSources(faceOf(view.container))).toEqual([]); await release(aComment); await settle(held); - const peek = peekOf(view.container); + const peek = faceOf(view.container); expect(failedSources(peek)).toEqual([]); expect(retryButton(peek)).toBeNull(); expect(peek.textContent).toContain(EMPTY_ACTIVITY); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx index 54aec7c480d..9d103cf9a82 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx @@ -172,7 +172,8 @@ function makeMetadata(pages: any[]) { function renderDetail(dataSource: any, pages: any[] = []) { return render( - + // objectstack#35595 — the whole stream, composer included, is the 动态 tab's face; the 概览 rail shows a read-only peek. + + // objectstack#35595 — the whole stream, composer included, is the 动态 tab's face; the 概览 rail shows a read-only peek. + { function renderDetail(dataSource: any) { return render( - + { ); } + // objectstack#35595 — every side list is a tab of its own, in this order. const cardOrder = (container: HTMLElement) => - Array.from(container.querySelectorAll('[data-record-column="right"] [data-related-card-id]')).map((el) => - el.getAttribute('data-related-card-id'), - ); + Array.from(container.querySelectorAll('[role="tab"][data-record-tab]')) + .map((el) => el.getAttribute('data-record-tab')) + .filter((id): id is string => !!id && id.includes('.')); beforeEach(() => { cleanup(); @@ -1934,7 +1935,7 @@ describe('RecordDetailView.relatedListsOrder-27241', () => { vi.restoreAllMocks(); }); - describe('RecordDetailView — the related cards follow the object\'s relatedLists (objectstack#27069)', () => { + describe('RecordDetailView — the related lists\' tabs follow the object\'s relatedLists (objectstack#27069, objectstack#35595)', () => { it('without relatedLists: the derived order — the owned child first, then the lookups in declaration order', async () => { const { container } = renderPage(objectsWith()); await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); @@ -2043,10 +2044,11 @@ describe('RecordDetailView.bodyTablePredicate-27478', () => { ); } + // objectstack#35595 — every side list is a tab of its own, in this order. const cardOrder = (container: HTMLElement) => - Array.from(container.querySelectorAll('[data-record-column="right"] [data-related-card-id]')).map((el) => - el.getAttribute('data-related-card-id'), - ); + Array.from(container.querySelectorAll('[role="tab"][data-record-tab]')) + .map((el) => el.getAttribute('data-record-tab')) + .filter((id): id is string => !!id && id.includes('.')); beforeEach(() => { cleanup(); @@ -2121,19 +2123,16 @@ describe('RecordDetailView.bodyTablePredicate-27478', () => { // ── RecordDetailView.relatedCountsFirst-27056 ─────────────────────────────── /** - * objectstack#27056 — the record page's related panels load counts first, - * then the first rows of only the cards in view, and never blocks the details. - * - * The REAL page, at a desktop width (the column tiers), over a data source - * that holds every related read until the test answers it. The record has six - * related lists. Measured: + * objectstack#27056, as objectstack#35595/#35596 lay the page out — the related + * lists load counts first and never block the details. Every list is a tab; + * the 概览 tab's right rail lists, under 「其他相关」, the lists that have + * records, with their first three rows. Measured: * * - the details draw from the record read alone, while every related read is - * still out, and the right column shows one placeholder per card; + * still out, with every list's tab drawn (no number yet) and no rail card; * - the six counts go out as ONE request set, before any of them answers; - * - once they answer, rows are read for the two counted cards in view only, - * three rows each — never for a card counted at 0 (in view too), never for - * the cards below the fold. + * - once they answer, rows are read for the lists counted above 0 only, three + * rows each — never for a list counted at 0. */ describe('RecordDetailView.relatedCountsFirst-27056', () => { @@ -2262,7 +2261,6 @@ describe('RecordDetailView.relatedCountsFirst-27056', () => { } const isCount = (r: HeldRead) => r.query.$count === true && r.query.$skip === undefined; - const isRows = (r: HeldRead) => r.query.$skip !== undefined; const column = (container: HTMLElement, name: string) => container.querySelector(`[data-record-column="${name}"]`) as HTMLElement | null; @@ -2290,8 +2288,12 @@ describe('RecordDetailView.relatedCountsFirst-27056', () => { vi.restoreAllMocks(); }); - describe('RecordDetailView — the related column loads counts first (objectstack#27056)', () => { - it('draws the details before any related read answers, with one placeholder per card', async () => { + describe('RecordDetailView — the related lists load counts first (objectstack#27056, objectstack#35596)', () => { + const tabIds = (container: HTMLElement) => + Array.from(container.querySelectorAll('[role="tab"][data-record-tab]')).map((el) => el.getAttribute('data-record-tab')); + const isRowRead = (r: HeldRead) => r.query.$count !== true; + + it('draws the details and every list\'s tab before any related read answers', async () => { const { container } = renderPage(); await idle(); expect(reads.length).toBeGreaterThan(0); @@ -2301,46 +2303,47 @@ describe('RecordDetailView.relatedCountsFirst-27056', () => { expect(container.textContent).toContain('Acme'); expect(container.textContent).toContain('Retail'); expect(column(container, 'details')?.textContent).toContain(RECORD_ID); - const related = column(container, 'right')!; - expect(related.querySelectorAll('[data-related-card-pending]')).toHaveLength(CHILDREN.length); - expect(related.querySelector('[data-related-card-row]')).toBeNull(); + // Every list has its tab already, with no number yet. + expect(tabIds(container).filter((id) => id?.includes('.'))).toEqual(CHILDREN.map((c) => `${c}.account`)); + for (const c of CHILDREN) { + expect(container.querySelector(`[data-record-tab="${c}.account"] [data-record-tab-count]`)).toBeNull(); + } + // No rail card for a list before its count says it has records. + expect(container.querySelector('[data-record-summary-other]')).toBeNull(); }); - it('asks the six counts as one request set, then the rows of the two counted cards in view only', async () => { + it('asks the six counts as one request set, then three rows of each list counted above 0 only', async () => { const { container } = renderPage(); await idle(); // One request set: every list's count, all out before any answered, and // nothing else of theirs. expect(reads.filter(isCount).map((r) => r.object).sort()).toEqual([...CHILDREN].sort()); - expect(reads.filter(isRows)).toEqual([]); + expect(reads.filter(isRowRead)).toEqual([]); expect(reads.filter(isCount).every((r) => r.query.$top === 1)).toBe(true); await act(async () => { for (const r of reads.filter((read) => !read.answered)) r.answer(); }); await idle(); - const rowReads = reads.filter(isRows); - // The counted cards in view: the first and the third. The second is in - // view but counted at 0; the last three are below the fold. - expect(rowReads.map((r) => r.object).sort()).toEqual([C1, C3].sort()); - for (const r of rowReads) { - expect(r.query.$top).toBe(3); - expect(r.query.$select).toEqual(['id', 'name', 'status']); - } - // Two round trips in all: the counts, then the rows. - expect(reads).toHaveLength(CHILDREN.length + 2); + const rowReads = reads.filter(isRowRead); + // Every list counted above 0; never the second, counted at 0. + const withRecords = CHILDREN.filter((c) => TOTALS[c] > 0); + expect(rowReads.map((r) => r.object).sort()).toEqual([...withRecords].sort()); + for (const r of rowReads) expect(r.query.$top).toBe(3); + expect(reads.some((r) => r.object === C2 && isRowRead(r))).toBe(false); await act(async () => { for (const r of reads.filter((read) => !read.answered)) r.answer(); }); await idle(); - const related = column(container, 'right')!; - expect(related.querySelector(`[data-related-card-id="${C1}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(3); - expect(related.querySelector(`[data-related-card-id="${C3}.account"]`)?.querySelectorAll('[data-related-card-row]')).toHaveLength(2); - expect(related.querySelector('[data-related-card-pending]')).toBeNull(); - // Still nothing for the empty card, nor for the cards out of view. - expect(reads.filter(isRows).map((r) => r.object).sort()).toEqual([C1, C3].sort()); - expect(reads.some((r) => r.object === C2 && isRows(r))).toBe(false); + const rail = column(container, 'right')!; + const rowsOf = (c: string) => + rail.querySelector(`[data-record-summary-card="${c}.account"]`)?.querySelectorAll('[data-record-summary-row]') ?? []; + expect(rowsOf(C1)).toHaveLength(3); + expect(rowsOf(C3)).toHaveLength(2); + // CONTROL: the list counted at 0 has no rail card at all, but keeps its tab. + expect(rail.querySelector(`[data-record-summary-card="${C2}.account"]`)).toBeNull(); + expect(container.querySelector(`[data-record-tab="${C2}.account"]`)?.hasAttribute('data-record-tab-empty')).toBe(true); }); }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.panelToggles-27052.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.panelToggles-27052.test.tsx index a039f589e9e..fab885fbce7 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.panelToggles-27052.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.panelToggles-27052.test.tsx @@ -29,9 +29,13 @@ * crumb row is gone; a record drawn with no top bar of its own (a host's * plain overlay) keeps it at the end of that row (objectstack#27241); * - it is drawn only where the tier has a right column: both two-column - * tiers, the embedded record at those widths too, never the one column; - * - the chord is the topmost record view's: a drawer wide enough for its - * own right column flips its own switch, never the page's under it. + * tiers, never the one column, and never an embedded record (a drawer or + * pane draws no right rail, objectstack#35596); + * - the chord is the topmost record view's: under a drawer it flips nothing, + * the page's switch included. + * + * objectstack#35596 — the right column is the 概览 tab's rail; it is drawn + * while it has a card to show, so every child here answers two records. */ import * as React from 'react'; @@ -134,7 +138,7 @@ let dialogRootWidth: number | null = null; function makeDataSource() { return { - find: vi.fn(async () => ({ data: [], total: 0 })), + find: vi.fn(async () => ({ data: [], total: 2 })), create: vi.fn(async (_o: string, row: unknown) => row), findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Record ${recordId}` })), update: vi.fn(async () => ({})), @@ -245,11 +249,11 @@ describe('RecordDetailView — the right-column switch ⊟ (objectstack#27052, o await waitFor(() => expect(shown(container)).toBe('details')); expect(rightColumnSwitch().getAttribute('aria-pressed')).toBe('false'); expect(container.querySelector('[data-record-column="right"]')).toBeNull(); - expect(container.querySelector('[data-record-timeline-panel]')).toBeNull(); + expect(container.querySelector('[data-record-summary-card]')).toBeNull(); fireEvent.click(rightColumnSwitch()); await waitFor(() => expect(shown(container)).toBe('details right')); - expect(container.querySelector('[data-record-column="right"] > [data-record-timeline-panel]')).not.toBeNull(); + expect(container.querySelector('[data-record-column="right"] [data-record-summary-card]')).not.toBeNull(); }); it('the choice survives a remount and is per object', async () => { @@ -274,13 +278,15 @@ describe('RecordDetailView — the right-column switch ⊟ (objectstack#27052, o it.each([ ['an object that is not worked', PRODUCT], ['an object that is only another object\'s `master_detail` parent', PRICE_BOOK], - ])('%s opens with the right column too, 动态 last (objectstack#34590)', async (_name, object) => { + ])('%s opens with the right rail too; 动态 the last tab (objectstack#34590)', async (_name, object) => { const { container } = renderPage({ object }); await screen.findByRole('group', { name: 'Panels' }, { timeout: 5000 }); - expect(shown(container)).toBe('details right'); + await waitFor(() => expect(shown(container)).toBe('details right')); expect(rightColumnSwitch().getAttribute('aria-pressed')).toBe('true'); - // objectstack#34590, ruling 6937542160 — 动态 last (supersedes objectstack#27524 Targets 5 and 8's 动态-first). - expect(container.querySelector('[data-record-column="right"]')?.lastElementChild?.hasAttribute('data-record-timeline-panel')).toBe(true); + // objectstack#34590 — 动态 is the tab row's last tab (the rail itself + // orders 审批, 附件, 最近动态, then the lists: objectstack#35596). + const tabs = Array.from(container.querySelectorAll('[role="tab"][data-record-tab]')); + expect(tabs[tabs.length - 1]?.getAttribute('data-record-tab')).toBe('timeline'); }); it('⌘⇧, flips ⊟; with a text field focused it does nothing; ⌘⇧. is not the page\'s any more', async () => { @@ -335,7 +341,7 @@ describe('RecordDetailView — the right-column switch ⊟ (objectstack#27052, o expect(rightColumnSwitch().getAttribute('aria-keyshortcuts')).toMatch(/^(Meta|Control)\+Shift\+,$/); }); - it('not drawn in the one column, where there is no right column to hide; the shortcut does nothing there. The embedded record at 1440 px has one, and draws it', async () => { + it('not drawn in the one column, where there is no right column to hide; the shortcut does nothing there. The embedded record at 1440 px has none, and no rail (objectstack#35596)', async () => { const stacked = renderPage({ width: 700 }); await waitFor(() => expect(stacked.container.querySelector('[data-record-page-tier]')?.getAttribute('data-record-page-tier')).toBe('stack'), { timeout: 5000 }); expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull(); @@ -346,16 +352,17 @@ describe('RecordDetailView — the right-column switch ⊟ (objectstack#27052, o stacked.unmount(); const embedded = renderPage({ width: 1440, embedded: true }); - await screen.findByRole('group', { name: 'Panels' }, { timeout: 5000 }); - expect(shown(embedded.container)).toBe('details right'); + await waitFor(() => expect(embedded.container.querySelector('[data-record-page-tier]')?.getAttribute('data-record-page-tier')).toBe('wide'), { timeout: 5000 }); + expect(shown(embedded.container)).toBe('details'); + expect(embedded.container.querySelector('[data-record-column="right"]')).toBeNull(); + expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull(); }); - it('⌘⇧, flips the topmost record view\'s switch alone: a 1000 px drawer over a 1440 px page (objectstack#27524)', async () => { + it('⌘⇧, under a drawer flips nothing: the drawer draws no ⊟, and never writes the page\'s choice (objectstack#27524, objectstack#35596)', async () => { // A record page keeps its own tree mounted under the drawer its rows and // lookups open (`RecordPageDrawerHost`), and the drawer's sheet is - // portaled after it, to the end of the body. A drawer dragged to 1000 px - // has a right column of its own, so both views draw ⊟: the chord is the - // drawer's, and never writes the hidden page's stored choice. + // portaled after it, to the end of the body. The drawer draws no right + // rail at any width, so no ⊟: the chord is not the hidden page's either. dialogRootWidth = 1000; const page = renderPage(); await waitFor(() => expect(shown(page.container)).toBe('details right'), { timeout: 5000 }); @@ -363,13 +370,13 @@ describe('RecordDetailView — the right-column switch ⊟ (objectstack#27052, o sheet.setAttribute('role', 'dialog'); document.body.appendChild(sheet); const drawer = renderPage({ object: PRODUCT, embedded: true, container: sheet }); - await waitFor(() => expect(shown(sheet)).toBe('details right'), { timeout: 5000 }); - expect(sheet.querySelector('[data-record-page-tier]')?.getAttribute('data-record-page-tier')).toBe('two-column'); - expect(within(sheet).queryByRole('group', { name: 'Panels' })).not.toBeNull(); + await waitFor(() => expect(sheet.querySelector('[data-record-page-tier]')?.getAttribute('data-record-page-tier')).toBe('two-column'), { timeout: 5000 }); + expect(shown(sheet)).toBe('details'); + expect(within(sheet).queryByRole('group', { name: 'Panels' })).toBeNull(); press('related'); - await waitFor(() => expect(shown(sheet)).toBe('details')); - expect(window.localStorage.getItem(RIGHT_KEY(PRODUCT))).toContain('off'); + expect(shown(sheet)).toBe('details'); + expect(window.localStorage.getItem(RIGHT_KEY(PRODUCT))).toBeNull(); expect(shown(page.container)).toBe('details right'); expect(window.localStorage.getItem(RIGHT_KEY(LEAD))).toBeNull(); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenOneRequest-28470.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenOneRequest-28470.test.tsx index 5b3755e7f26..3b4f00602ef 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenOneRequest-28470.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenOneRequest-28470.test.tsx @@ -88,8 +88,6 @@ const ACTIVITY = { id: 'ac1', type: 'created', object_name: OBJECT, record_id: ' const ATTACHMENT = { id: 'f1', parent_object: OBJECT, parent_id: 'c1', file_id: 'file-1', file_name: 'contract.pdf', created_at: '2026-10-02T10:00:00.000Z' }; interface Answers { - /** Answer the related rows' owner as a bare id even when the request expands it. */ - ignoreExpand?: boolean; activity?: unknown; } @@ -113,7 +111,7 @@ function pageAnswer(id: string, body: any, answers: Answers) { id: `t${i}`, name: `Task ${i}`, contact: id, - owner: !answers.ignoreExpand && r.expand?.includes('owner') ? { id: 'u9', name: 'Una Owner' } : 'u9', + owner: r.expand?.includes('owner') ? { id: 'u9', name: 'Una Owner' } : 'u9', })), })), ...(body.fieldAccess ? { fieldAccess: { object: OBJECT, recordId: id, readable: ['name', 'account'], editable: ['name'], writable: true } } : {}), @@ -178,7 +176,6 @@ const STREAMS = ['sys_comment', 'sys_comment_reaction', 'sys_activity', 'sys_att const streamReads = (held: Held[]) => STREAMS.flatMap((o) => readsOf(held, o).map(() => o)); const mentionReads = (held: Held[]) => readsOf(held, 'sys_user').filter((h) => /[?&]\$?top=50\b/.test(h.path)); const nameProbes = (held: Held[]) => held.filter((h) => h.method === 'GET' && /[?&]\$?top=1\b/.test(h.path)); -const probedObject = (h: Held) => /\/api\/v1\/data\/([^/?]+)\?/.exec(h.path)![1]; beforeEach(() => { cleanup(); @@ -248,14 +245,20 @@ describe('objectstack#28470 — one record open is one request', () => { await settle(held); expect(mentionReads(held)).toEqual([]); - const standIn = view.container.querySelector('[data-record-timeline-composer]') as HTMLElement | null; - expect(standIn, 'the 动态 panel draws its one-line composer').not.toBeNull(); - await act(async () => { fireEvent.click(standIn!); }); + // objectstack#35595 / #35596 — the 概览 rail's 动态 card is read-only; the + // composer is the 动态 tab's. + expect(view.container.querySelector('[data-record-summary-card="timeline"] textarea')).toBeNull(); + const tab = view.container.querySelector('[role="tab"][data-record-tab="timeline"]') as HTMLElement; + await act(async () => { fireEvent.click(tab); }); + await settle(held); + expect(mentionReads(held)).toEqual([]); + const editor = view.container.querySelector('[data-related-enlarged="timeline"] textarea') as HTMLTextAreaElement | null; + expect(editor, 'the 动态 tab draws the composer').not.toBeNull(); + await act(async () => { fireEvent.focus(editor!); }); await settle(held); expect(mentionReads(held)).toHaveLength(1); - const editor = view.container.querySelector('[data-record-timeline-peek] textarea') as HTMLTextAreaElement; - await act(async () => { fireEvent.blur(editor); fireEvent.focus(editor); }); + await act(async () => { fireEvent.blur(editor!); fireEvent.focus(editor!); }); await settle(held); expect(mentionReads(held)).toHaveLength(1); }); @@ -280,11 +283,7 @@ describe('objectstack#28470 — one record open is one request', () => { expect([...new Set(streamReads(held))].sort()).toEqual(['sys_activity', 'sys_attachment', 'sys_comment']); }); - it('ablation — rows answered with bare ids pay one name read per referenced object, never the parent\'s', async () => { - const { held, open } = await boot({ ignoreExpand: true }); - open(); - await settle(held); - expect(held.filter(isPage)).toHaveLength(1); - expect(nameProbes(held).map(probedObject)).toEqual(['sys_user']); - }); + // objectstack#35596 retired the bare-id ablation: the 概览 rail draws a + // related row's name and key value only, never its lookups, so no surface + // on the page's open resolves a related row's owner to probe for. }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenRequests-12701.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenRequests-12701.test.tsx index b2e94a9c094..6b45e1674fa 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenRequests-12701.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenRequests-12701.test.tsx @@ -230,7 +230,7 @@ async function drain(held: Held[]) { } /** Mount the real record page under StrictMode, as the console's `main.tsx` does. */ -async function openRecordPage() { +async function openRecordPage(page: unknown = RECORD_PAGE) { const { fetch, held } = heldTransport(); vi.stubGlobal('fetch', fetch); const ds = new ObjectStackAdapter({ baseUrl: BASE, fetch, autoReconnect: false }); @@ -238,7 +238,7 @@ async function openRecordPage() { (ds as unknown as { getObjectSchema: () => Promise }).getObjectSchema = async () => objectDef; let objects: unknown[] = [objectDef]; - const pages = [RECORD_PAGE]; + const pages = [page]; const tree = () => { const metadata = { objects, pages, loading: false, error: null, @@ -348,3 +348,50 @@ describe('a record open sends one approvals read and one record read (objectui#1 expect(expansionOf(recordReads[1])).toEqual(['account', 'created_by', 'owner', 'reviewer']); }); }); + +/** + * objectstack#35484 (and the drawn-as-written fallback of objectstack#35483) — + * a page drawn as written whose details are split across two + * `record:details` nodes draws the record's approval band ONCE, recall + * included, on the first body (`ApprovalBandOnceScope` around the page). + */ +describe('a page drawn as written with two details nodes draws one approval band (objectstack#35484)', () => { + const twoDetails = (first: unknown) => ({ + ...RECORD_PAGE, + regions: [{ + name: 'main', + width: 'full', + components: [ + first, + { + type: 'record:details', + properties: { sections: [{ name: 'more', label: 'More', columns: 2, fields: ['account', 'owner'] }] }, + }, + { type: 'record:approvals', properties: {} }, + ], + }], + }); + const FIRST = { + type: 'record:details', + properties: { sections: [{ name: 'overview', label: 'Overview', columns: 2, fields: ['title', 'stage'] }] }, + }; + const bands = () => screen.queryAllByText('Locked for approval'); + + it('two details bodies: "Locked for approval" once, with one recall lever, on the first body', async () => { + await openRecordPage(twoDetails(FIRST)); + await waitFor(() => expect(bands()).toHaveLength(1)); + // Both bodies mark the band's place; only the first draws it. + expect(document.querySelectorAll('[data-approval-band-mark]')).toHaveLength(2); + const first = document.querySelectorAll('[data-approval-band-mark]')[0]; + expect(first.compareDocumentPosition(bands()[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // The approvals panel draws its own state; the band's recall is drawn once. + const panel = await screen.findByTestId('record-approvals-panel'); + const bandRecalls = screen.getAllByText('Recall approval').filter((el) => !panel.contains(el)); + expect(bandRecalls).toHaveLength(1); + }); + + it('CONTROL: the one-body page draws its band as before (the open-requests page above)', async () => { + await openRecordPage(); + await waitFor(() => expect(bands()).toHaveLength(1)); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenWaves-13010.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenWaves-13010.test.tsx index aa25a00c0c9..84cd90ded22 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.recordOpenWaves-13010.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.recordOpenWaves-13010.test.tsx @@ -458,10 +458,11 @@ describe('the record page open waves (objectui#13010)', () => { const asked = pageLists(held).filter((l) => l.object === object); expect(asked.map((l) => l.top), `${object}\n${table}`).toEqual([3]); } - // The badge total is drawn from that read: quote 6 + line 7 + the - // filtered task probe's own 4. + // objectstack#35595 — one table, one count: the Related tab merges three + // tables, so it names no number (it summed quote 6 + line 7 + the filtered + // task probe's own 4 before). const relatedTab = screen.getByRole('tab', { name: /Related/ }); - expect(relatedTab.textContent, table).toContain('17'); + expect(relatedTab.textContent, table).toBe('Related'); // The card rows are drawn from the same read: three rows each, and the // card's own total. for (const object of [QUOTE, LINE]) { @@ -530,8 +531,8 @@ const FOUR_READS = [isActivityRead, isCommentRead, isUserListRead, isAttachmentL /** * Every element is on screen except the host's foot-of-page Attachments panel, - * which is below the record's content until `scrollFallbackIntoView` says it - * scrolled in. + * which stays below the record's content (a page with a tab strip has none + * since objectstack#35595: the panel is the strip's Attachments tab). */ const offscreen: Array<{ cb: (entries: Array<{ isIntersecting: boolean }>) => void; live: boolean }> = []; class FoldObserver { @@ -551,11 +552,6 @@ class FoldObserver { for (const entry of this.entries) entry.live = false; } } -async function scrollFallbackIntoView() { - await act(async () => { - for (const entry of offscreen) if (entry.live) entry.cb([{ isIntersecting: true }]); - }); -} /** Open a tab the way a user does: Radix activates a trigger on mouse down. */ async function openTab(name: string) { @@ -579,10 +575,11 @@ describe('the timeline, comments, attachments and user list wait for their panel const table = waveTable(held); expect(held.filter(isRecordRead).map((h) => h.wave), table).toEqual([1]); for (const isRead of FOUR_READS) expect(held.filter(isRead), table).toEqual([]); - // The foot panel is mounted and shows its loading state, not "no attachments". - const fallback = document.querySelector('[data-record-attachments-fallback]'); - expect(fallback, table).not.toBeNull(); - expect(fallback?.textContent ?? '', table).not.toContain('signed-contract.pdf'); + // objectstack#35595 — the host's attachments panel is a tab of the page's + // strip, not a band at its foot. + expect(document.querySelector('[data-record-attachments-fallback]'), table).toBeNull(); + expect(screen.getByRole('tab', { name: /^Attachments/ }), table).toBeTruthy(); + expect(screen.queryByText('signed-contract.pdf'), table).toBeNull(); }); // The open's payload did not ask the feed (its block was not on screen), so @@ -642,17 +639,20 @@ describe('the timeline, comments, attachments and user list wait for their panel expect(screen.getByText('Ping the buyer on Friday')).toBeTruthy(); }); - // objectstack#28470 — the payload carries the attachments: the panel takes - // them once it scrolls into view, and reads nothing of its own. - it('the foot-of-page Attachments panel draws the payload\'s rows once it scrolls into view, and reads nothing', async () => { + // objectstack#28470 — the payload carries the attachments, so nothing reads + // them at open. objectstack#35595 — the host's panel is the strip's + // Attachments tab, drawn when it opens. (Under StrictMode the face's mount + // runs the panel's effect twice: the first run takes the payload's rows and + // is superseded, the second reads — a development-only re-read of + // `RecordAttachmentsPanel`'s take-once hand-off, not asserted here.) + it('the host\'s Attachments tab draws the record\'s files when it opens; nothing reads them at open', async () => { const { held, state } = await openRecordPage({ page: ACTIVITY_PAGE, object: filesObject, observer: FoldObserver }); expect(pageStreams(held).attachments, waveTable(held)).toBe(100); expect(held.filter(isAttachmentRead), waveTable(held)).toEqual([]); - await scrollFallbackIntoView(); + expect(screen.queryByText('signed-contract.pdf'), waveTable(held)).toBeNull(); + await openTab('Attachments'); await runWaves(held, state); - const table = waveTable(held); - expect(held.filter(isAttachmentRead), table).toEqual([]); - expect(screen.getByText('signed-contract.pdf')).toBeTruthy(); + expect(screen.getByText('signed-contract.pdf'), waveTable(held)).toBeTruthy(); }); it('CONTROL: a record opened on its Activity tab asks the feed with its page at open, and draws the same rows', async () => { @@ -701,7 +701,8 @@ describe('the timeline, comments, attachments and user list wait for their panel const { held } = await openRecordPage({ page: { ...RECORD_PAGE, isDefault: false, object: 'os_13010_other' }, observer: FoldObserver }); const table = waveTable(held); expect(screen.queryByRole('tab', { name: /^Timeline/ }), table).toBeNull(); - expect(document.querySelector('[data-record-timeline-panel]'), table).not.toBeNull(); + // objectstack#35596 — the stream's newest rows are the 概览 rail's 最近动态 card. + expect(document.querySelector('[data-record-summary-card="timeline"]'), table).not.toBeNull(); // objectstack#28737 — the panel draws its newest rows, and the page // payload serves the stream's count, so the activity part asks the // panel's rows only. @@ -766,16 +767,16 @@ describe('the 动态 stream reads the audit log when it is shown (objectui#13010 expect(screen.queryByRole('tab', { name: /^(Timeline|History)/ }), table).toBeNull(); expect(held.filter(isAuditRead).map((h) => h.wave), table).toEqual([1]); expect(held.filter(isAuditUserLookup).map((h) => h.wave), table).toEqual([2]); - const panel = document.querySelector('[data-record-timeline-panel]') as HTMLElement; + const panel = document.querySelector('[data-record-summary-card="timeline"]') as HTMLElement; expect(panel.textContent, table).toMatch(/negotiation/); }); - it('opening the 动态 tab from its panel reads nothing again, and draws the rows with their actor', async () => { + it('opening the 动态 tab from its rail card reads nothing again, and draws the rows with their actor', async () => { const { held, state } = await openHistory(); const audit = () => held.filter(isAuditRead); expect(audit(), waveTable(held)).toHaveLength(1); await act(async () => { - fireEvent.click(document.querySelector('[data-record-timeline-panel-open]') as HTMLElement); + fireEvent.click(document.querySelector('[data-record-summary-card="timeline"] [data-record-summary-card-title]') as HTMLElement); }); await runWaves(held, state); const table = waveTable(held); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.recordPageTiers-26678.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.recordPageTiers-26678.test.tsx index 510d9bb3a81..9322f8420ff 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.recordPageTiers-26678.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.recordPageTiers-26678.test.tsx @@ -249,11 +249,17 @@ const columnsGrid = (container: HTMLElement) => /** The details' field grid, by the classes it draws (container queries). */ const detailsGrid = (container: HTMLElement) => column(container, 'details')?.querySelector('[data-detail-section-face="frameless"] .grid')?.getAttribute('class') ?? ''; -/** The right column's panels, in order: `timeline` for 动态, else the related card's id. */ +/** + * The right rail's cards on screen, in order (objectstack#35596): 审批, 附件, + * 最近动态 (`timeline`), then each related list with records. A card with + * nothing to show is not drawn (the 动态 card waits `hidden` for its count). + */ const rightPanels = (container: HTMLElement) => - Array.from(column(container, 'right')?.querySelectorAll('[data-record-timeline-panel], [data-related-card-id]') ?? []).map( - (el) => (el.hasAttribute('data-record-timeline-panel') ? 'timeline' : el.getAttribute('data-related-card-id')), + Array.from(column(container, 'right')?.querySelectorAll('[data-record-summary-card]:not([hidden])') ?? []).map((el) => + el.getAttribute('data-record-summary-card'), ); +/** objectstack#35596 — this record's stream is empty, so the rail holds its two lists with records. */ +const RAIL = ['showcase_task.project', 'showcase_note.project']; /** * The page's only tablist is its tab row (objectstack#27524, Target 8): the @@ -277,7 +283,7 @@ const expectTabRowOnly = async (active = 'overview') => { }; describe('RecordDetailView — one record page, laid out by its width (objectstack#26678, objectstack#27524)', () => { - it('1440 px: details beside the right column at 380 px, the details grid at three columns; 动态 last (objectstack#34590); History is read at open', async () => { + it('1440 px: details beside the right rail at 380 px, the details grid at three columns; 动态 the last tab (objectstack#34590); History is read at open', async () => { const { container } = renderPage({ width: 1440 }); await screen.findAllByText('Tasks', undefined, { timeout: 5000 }); expect(tierOf(container)).toBe('wide'); @@ -286,8 +292,9 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta // Container breakpoints of the dense label-left rows (objectstack#35602). expect(detailsGrid(container)).toContain('@4xl:grid-cols-3'); await expectTabRowOnly(); - // objectstack#34590, ruling 6937542160 — 动态 last (supersedes objectstack#27524 Targets 5 and 8's 动态-first). - expect(rightPanels(container)).toEqual(['showcase_task.project', 'showcase_note.project', 'timeline']); + // objectstack#35596 — the rail's order: 审批, 附件, 最近动态, then the lists + // with records (supersedes objectstack#34590's 动态-last right column). + await waitFor(() => expect(rightPanels(container)).toEqual(RAIL)); // No resident timeline column and no rail: the two columns are all. expect(column(container, 'timeline')).toBeNull(); expect(column(container, 'related')).toBeNull(); @@ -311,8 +318,9 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta expect(detailsGrid(container)).toContain('@xl:grid-cols-2'); expect(detailsGrid(container)).not.toContain('@4xl:grid-cols-3'); // The same panels as the wide tier — no rail to open first. - // objectstack#34590, ruling 6937542160 — 动态 last (supersedes objectstack#27524 Targets 5 and 8's 动态-first). - expect(rightPanels(container)).toEqual(['showcase_task.project', 'showcase_note.project', 'timeline']); + // objectstack#35596 — the rail's order: 审批, 附件, 最近动态, then the lists + // with records (supersedes objectstack#34590's 动态-last right column). + await waitFor(() => expect(rightPanels(container)).toEqual(RAIL)); expect(screen.queryByTestId('record-related-rail-toggle')).toBeNull(); await expectTabRowOnly(); }); @@ -320,7 +328,7 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta it.each([ ['the split pane', 720, 1440], ['a phone', 390, 390], - ])('%s (%i px): one column — the details, then the 动态 panel and the related panels; the tab row; History is read at open', async (name, width, windowWidth) => { + ])('%s (%i px): one column — the details, then the right rail; the tab row; History is read at open', async (name, width, windowWidth) => { const { container } = renderPage({ width, windowWidth }); await screen.findAllByText('Tasks', undefined, { timeout: 5000 }); expect(tierOf(container)).toBe('stack'); @@ -331,8 +339,9 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta const details = column(container, 'details')!; const right = column(container, 'right')!; expect(details.compareDocumentPosition(right) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - // objectstack#34590, ruling 6937542160 — 动态 last (supersedes objectstack#27524 Targets 5 and 8's 动态-first). - expect(rightPanels(container)).toEqual(['showcase_task.project', 'showcase_note.project', 'timeline']); + // objectstack#35596 — the rail's order: 审批, 附件, 最近动态, then the lists + // with records (supersedes objectstack#34590's 动态-last right column). + await waitFor(() => expect(rightPanels(container)).toEqual(RAIL)); await waitFor(() => expect(auditReads()).toBeGreaterThan(0)); // objectstack#27058 — on a phone the stack ends where the bottom action // bar starts: the header's actions are drawn there, after the body, and @@ -350,11 +359,12 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta } }); - it('embedded (drawer / split pane): the same rule — two columns at 1440 px, one at 720 px', async () => { + it('embedded (drawer / split pane): the same tiers, and no right rail (objectstack#35596)', async () => { const wide = renderPage({ width: 1440, embedded: true }); await screen.findAllByText('Tasks', undefined, { timeout: 5000 }); expect(tierOf(wide.container)).toBe('wide'); - expect(shown(wide.container)).toBe('details right'); + expect(shown(wide.container)).toBe('details'); + expect(column(wide.container, 'right')).toBeNull(); wide.unmount(); const { container } = renderPage({ width: 720, embedded: true }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.relatedBadgeArity-8882.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.relatedBadgeArity-8882.test.tsx index 134b97c2eef..0d228b1a984 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.relatedBadgeArity-8882.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.relatedBadgeArity-8882.test.tsx @@ -82,6 +82,8 @@ vi.mock('./MetadataInspector', () => ({ })); import { RecordDetailView } from './RecordDetailView'; +// The list's tab face draws its rows in the object grid (objectstack#35595). +import '@object-ui/plugin-grid'; const PARENT = 'task_version'; const CHILD = 'check_item'; @@ -257,6 +259,13 @@ function makeDataSource(rows: Record[], objects: any[]) { } as any; } +/** The child list's tab id: `object.field`, the field that references the parent. */ +function listTabOf(objects: any[]): string { + const child = objects.find((o) => o.name === CHILD); + const field = Object.keys(child.fields).find((name) => child.fields[name].reference === PARENT); + return `${CHILD}.${field}`; +} + function renderPage(objects: any[], dataSource: any) { const metadata = { objects, @@ -270,7 +279,9 @@ function renderPage(objects: any[], dataSource: any) { getItemsByType: () => [], } as any; return render( - + // objectstack#35595 — the list is a tab of the record page (`object.field`); + // the page opens on it (`?related=`), the face that draws its rows. + !p?.$count && typeof p?.$top === 'number'; const isBadgeProbe = (p: any) => p?.$count === true; @@ -321,10 +332,10 @@ async function renderAndCollect(child: any, rows: Record[]) { }; } -/** The digits the related panel's header counts, or `null`. */ +/** The digits the list's tab counts, or `null` (objectstack#35595). */ async function relatedPanelCount(): Promise { - const card = await screen.findByRole('region', { name: 'Check Item' }); - return card.querySelector('[data-related-card-count]')?.textContent?.trim() ?? null; + const tab = await screen.findByRole('tab', { name: /Check Item/ }); + return tab.querySelector('[data-record-tab-count]')?.textContent?.trim() ?? null; } /** How many child rows the related list actually drew. */ diff --git a/ui/packages/app-shell/src/views/RecordDetailView.relatedListFilter-4664.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.relatedListFilter-4664.test.tsx index bbc7580a5b2..a4e47ccb8e9 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.relatedListFilter-4664.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.relatedListFilter-4664.test.tsx @@ -67,6 +67,8 @@ import { render, screen, waitFor, cleanup } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataCtx } from '@object-ui/react'; import { RelatedCountStore } from '@object-ui/components'; +// The list's tab face draws its rows in the object grid (objectstack#35595). +import '@object-ui/plugin-grid'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), @@ -108,6 +110,8 @@ const PARENT = 'task_version'; const CHILD = 'check_item'; const RECORD_ID = 'tv-1'; const OTHER_ID = 'tv-2'; +/** The list's tab id (objectstack#35595): `object.field`. */ +const LIST_TAB = `${CHILD}.${PARENT}`; /** The FK's declared scope — the soft-delete shape the card's provenance names. */ const DECLARED_FILTER = { status: { $ne: 'archived' } } as const; @@ -259,7 +263,9 @@ function renderPage(objects: any[], dataSource: any) { getItemsByType: () => [], } as any; return render( - + // objectstack#35595 — the list is a tab of the record page; the page opens + // on it (`?related=`), the face that draws its rows. + { - const card = await waitFor(() => { - const el = document.querySelector('[data-related-card]'); + const tab = await waitFor(() => { + const el = document.querySelector(`[role="tab"][data-record-tab="${LIST_TAB}"]`); expect(el).not.toBeNull(); return el as HTMLElement; }); - return card.querySelector('[data-related-card-count]')?.textContent?.trim() ?? null; + return tab.querySelector('[data-record-tab-count]')?.textContent?.trim() ?? null; } beforeEach(() => { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.timelineCount-28737.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.timelineCount-28737.test.tsx index 336d2c8f6c1..ecc5447a942 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.timelineCount-28737.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.timelineCount-28737.test.tsx @@ -227,8 +227,11 @@ const ROWS = (n: number) => Array.from({ length: n }, (_, i) => ({ timestamp: new Date(Date.UTC(2026, 8, 30, 10, 59 - i)).toISOString(), })); const activityReads = (held: Held[]) => readsOf(held, 'sys_activity'); +// objectstack#35595 — the stream's count is the 动态 tab's number. const chipOf = (container: HTMLElement) => - container.querySelector('[data-record-timeline-panel] [data-record-timeline-count]')?.textContent ?? null; + container.querySelector('[role="tab"][data-record-tab="timeline"] [data-record-tab-count]')?.textContent ?? null; +const timelineTab = (container: HTMLElement) => + container.querySelector('[role="tab"][data-record-tab="timeline"]') as HTMLButtonElement; describe('objectstack#28737 — the 动态 count is the server\'s, and the page asks only the panel\'s rows', () => { it('a record with more than 200 merged entries shows the served total, and the request asks only the panel\'s rows', async () => { @@ -244,7 +247,7 @@ describe('objectstack#28737 — the 动态 count is the server\'s, and the page // The 动态 tab draws the whole stream: it reads the window once, and the // count stays the served one. - const openTab = view.container.querySelector('[data-record-timeline-panel-open]') as HTMLButtonElement; + const openTab = timelineTab(view.container); await act(async () => { fireEvent.click(openTab); }); await settle(held); expect(activityReads(held)).toHaveLength(1); @@ -256,8 +259,10 @@ describe('objectstack#28737 — the 动态 count is the server\'s, and the page const { held, open } = await boot({ activity: { total: 0, records: [] }, comments: [], timeline: { total: 0 } }); const view = open(); await settle(held); - expect(chipOf(view.container)).toBe('0'); - const openTab = view.container.querySelector('[data-record-timeline-panel-open]') as HTMLButtonElement; + // objectstack#35595 — an empty stream's tab is muted and names no number. + expect(chipOf(view.container)).toBeNull(); + expect(timelineTab(view.container).hasAttribute('data-record-tab-empty')).toBe(true); + const openTab = timelineTab(view.container); await act(async () => { fireEvent.click(openTab); }); await settle(held); expect(held.filter((h) => !isMeta(h)).map((h) => `${h.method} ${h.path}`)).toEqual([`POST /api/v1/data/${OBJECT}/c1/page`]); @@ -345,6 +350,8 @@ describe('objectstack#30035 — the 动态 stream is read again after a save', ( it(`${surface}: the count and the rows hold the save's activity row without a reload`, async () => { const { view, after } = await saveAndRead(embedded); expect(chipOf(view.container)).toBe('3'); + // A drawer draws no right rail (objectstack#35596): its rows are the 动态 tab's. + if (embedded) await act(async () => { fireEvent.click(timelineTab(view.container)); }); expect(view.container.textContent).toContain('changed the amount'); // One ask of the streams the open asked, and only those: no related // list, verdict, projection or approval rides it. diff --git a/ui/packages/app-shell/src/views/RecordDetailView.topBar-27524.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.topBar-27524.test.tsx index 7d6e73fca9f..5cad070a7bd 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.topBar-27524.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.topBar-27524.test.tsx @@ -332,8 +332,8 @@ function PaneHost({ dataSource }: { dataSource: unknown }) { ); } -describe('the pane\'s top bar holds the record\'s ⊟ and names it (objectstack#27524)', () => { - it('the record\'s header names it in the pane\'s bar, and its ⊟ sits in the pane\'s bar, not the header', async () => { +describe('the pane\'s top bar names the record (objectstack#27524)', () => { + it('the record\'s header names it in the pane\'s bar; a pane draws no right rail, so no ⊟ (objectstack#35596)', async () => { const dataSource = makeDataSource(); render( @@ -347,10 +347,9 @@ describe('the pane\'s top bar holds the record\'s ⊟ and names it (objectstack# const paneTitle = () => document.querySelector('[data-record-bar-title] h1')?.textContent; await waitFor(() => expect(paneTitle()).toBe('Record r-1'), { timeout: 5000 }); expect(screen.queryByTestId('record-drawer-crumb')).toBeNull(); - const group = await screen.findByRole('group', { name: 'Panels' }, { timeout: 5000 }); - expect(group.closest('[data-record-pane-toggles]')).not.toBeNull(); - expect(group.closest('[data-record-top-bar]')).not.toBeNull(); - expect(group.closest('[data-record-page-root]')).toBeNull(); + await waitFor(() => expect(document.querySelector('[data-record-page-tier]')).not.toBeNull(), { timeout: 5000 }); + expect(screen.queryByRole('group', { name: 'Panels' })).toBeNull(); + expect(document.querySelector('[data-record-column="right"]')).toBeNull(); expect(document.querySelector('[data-page-header-trailing]')).toBeNull(); // The pane draws its own bar; the record inside draws none. expect(document.querySelectorAll('[data-record-top-bar]')).toHaveLength(1); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 63e9a138718..76d6d2e0c53 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -83,6 +83,7 @@ import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; import { RecordAttachmentsPanel } from './RecordAttachmentsPanel.js'; import { RecordApprovalsPanel } from './RecordApprovalsPanel.js'; +import { ApprovalBandOnceScope } from '@object-ui/plugin-detail'; import { DeclaredActionsBar } from './DeclaredActionsBar.js'; import { SYS_APPROVAL_REQUEST_OBJECT, @@ -5152,11 +5153,13 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // switch: ONE ⊟ icon (「右栏」), drawn in the record's top bar after its step // group (the page's own bar below; a pane's bar through // `RecordPaneBarToggles`), only where the tier has a right column and the - // page has a panel for it — never in the stack. + // page has a panel for it — never in the stack, and never in a drawer or + // pane, which draws no right rail (objectstack#35596). const panelToggleItems: PanelToggleItem[] = []; if ( pageColumns && pageHasRightColumn + && !embedded && (pageColumns.timeline.length > 0 || pageColumns.related.length > 0) ) { panelToggleItems.push({ @@ -5418,7 +5421,14 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri type="button" onClick={() => { const panel = pageRootEl?.querySelector('[data-testid="record-approvals-panel"]'); - panel?.scrollIntoView({ block: 'start', behavior: 'smooth' }); + if (panel) { + panel.scrollIntoView({ block: 'start', behavior: 'smooth' }); + return; + } + // objectstack#35595 — the approvals panel is the page's 审批 tab, not + // drawn on 概览: the tag opens that tab. + if (pageColumns) openEnlargedRelated('approvals'); + else if (!hasApprovalsNode) handleTabChange('approvals'); }} className={cn( 'inline-flex h-5 shrink-0 items-center rounded-md border px-1.5 text-xs font-medium focus:outline-none focus-visible:ring-2 focus-visible:ring-ring', @@ -5475,6 +5485,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ); + // objectstack#35595 — where a page drawn as written gets the panels it does + // not place: its tab strip's 审批 and 附件 tabs, not the page's foot. + const fallbackTabs = pageColumns + ? { page: renderedPage, approvals: false, attachments: false } + : withFallbackRecordTabs(renderedPage, { + approvals: pureRecordId && !hasApprovalsNode && approvals.requests.length > 0 + ? { approvals: { available: approvals.available, requests: approvals.requests, pendingRequest: approvals.pendingRequest }, currentUserId: user?.id } + : null, + attachments: !!(filesEnabled && !hasAttachments && pureRecordId), + }); const pageTree = ( @@ -5741,6 +5761,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri tier={recordPageTier} columns={pageColumns} rightColumn={relatedSwitch === 'on'} + // objectstack#35596 — a drawer (or pane) draws no right rail: + // its 审批, 附件 and 动态 are its tabs. + rail={!embedded} relatedArrangement={relatedArrangement} onRelatedArrangementChange={setRelatedArrangement} enlargedRelated={enlargedRelatedParam} @@ -5763,12 +5786,21 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // (frameless sections, the highlight grid); an authored page // keeps its own face. Every `record:details` body, authored // or not, draws the empty-sections line (objectstack#35019). + // + // objectstack#35595 — the approval and the attachments a page + // does not place go into its tab strip, as the 审批 and 附件 + // tabs (`withFallbackRecordTabs`), not the page's foot; and + // however many details nodes it places, it draws ONE approval + // band (`ApprovalBandOnceScope`, objectstack#35483, + // objectstack#35484). {/* A page drawn as its strip is drawn as written: the reader's arrangement belongs to the right column and the tab row (objectstack#27524). */} - + + + )} @@ -5780,7 +5812,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri AUTHORED pages that don't place the node, so the read-gated approval story is never lost to a custom layout. Renders nothing when the record has no requests. */} - {pureRecordId && !hasApprovalsNode && ( + {pureRecordId && !hasApprovalsNode && !fallbackTabs.approvals && ( ); } + +/** + * objectstack#35595 — a page drawn as written (an authored page, or a + * synthesized one whose strip cannot be laid out) that does not place the + * record's approval or attachments panel gets them as tabs of its FIRST + * `page:tabs` strip — 「附件」 then 「审批」, after its own tabs — instead of + * at the page's foot. A page with no strip keeps the foot (there is nowhere + * else to put them). Returns the page unchanged, by reference, when it adds + * nothing, and says which tab it added. + */ +export function withFallbackRecordTabs( + page: any, + add: { approvals: Record | null; attachments: boolean }, +): { page: any; approvals: boolean; attachments: boolean } { + const none = { page, approvals: false, attachments: false }; + if (!add.approvals && !add.attachments) return none; + const extra = (): any[] => [ + ...(add.attachments + ? [{ label: 'Attachments', value: 'attachments', children: [{ type: 'record:attachments', properties: {} }] }] + : []), + ...(add.approvals + ? [{ label: 'Approvals', value: 'approvals', children: [{ type: 'record:approvals', properties: add.approvals }] }] + : []), + ]; + let placed = false; + const visit = (node: any): any => { + if (placed || !node || typeof node !== 'object') return node; + if (Array.isArray(node)) { + let changed = false; + const next = node.map((child) => { + const out = visit(child); + if (out !== child) changed = true; + return out; + }); + return changed ? next : node; + } + if (node.type === 'page:tabs') { + const items = node.properties?.items ?? node.items; + if (!Array.isArray(items)) return node; + placed = true; + const nextItems = [...items, ...extra()]; + return node.properties?.items + ? { ...node, properties: { ...node.properties, items: nextItems } } + : { ...node, items: nextItems }; + } + let out = node; + for (const key of ['regions', 'components', 'children'] as const) { + const value = node[key]; + if (value === undefined) continue; + const next = visit(value); + if (next !== value) out = { ...out, [key]: next }; + if (placed) break; + } + return out; + }; + const next = visit(page); + return placed ? { page: next, approvals: !!add.approvals, attachments: add.attachments } : none; +} diff --git a/ui/packages/components/src/__tests__/page-node-visibility-fail-closed-13299.test.tsx b/ui/packages/components/src/__tests__/page-node-visibility-fail-closed-13299.test.tsx index 99138fe1932..5b41edda19c 100644 --- a/ui/packages/components/src/__tests__/page-node-visibility-fail-closed-13299.test.tsx +++ b/ui/packages/components/src/__tests__/page-node-visibility-fail-closed-13299.test.tsx @@ -20,7 +20,7 @@ */ import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; -import { render, cleanup, screen } from '@testing-library/react'; +import { render, cleanup, screen, waitFor } from '@testing-library/react'; import { ComponentRegistry } from '@object-ui/core'; import { RecordContextProvider, @@ -31,6 +31,9 @@ import { __resetVisibilityPredicateWarnings } from '../../../react/src/utils/vis import { RelatedCountStore } from '../hooks/related-count-store'; // Module-scope import (not `beforeAll`) — objectui#3010/#3021. import '../renderers'; +// `react-page` reaches this dynamically; load it during collection, not in a +// clocked case (`check:test-source-alias`). +import '@object-ui/react-runtime'; const RECORD_OBJECT = 'zz13299_env'; const PARENT_ID = 'ENV-13299'; @@ -117,22 +120,24 @@ describe('objectui#13299 (e) — the tab badge does not count a node withheld by expect(lines[0]).toContain('WITHHELD'); }); + // objectstack#35595 — one table, one count: with both lists drawn the tab + // merges two tables and names no number, so the CONTROL reads the probes. it('CONTROL: a gate that evaluates to true is counted', async () => { - const { findByLabelText, ds } = renderTabs({ + const { queryByLabelText, ds } = renderTabs({ children: [relatedList(WITHHELD_CHILD, cel("record.plan == 'free'")), relatedList(SHOWN_CHILD)], }); - expect((await findByLabelText('5 items')).textContent).toBe('5'); - expect(probedObjects(ds)).toEqual([WITHHELD_CHILD, SHOWN_CHILD].sort()); + await waitFor(() => expect(probedObjects(ds)).toEqual([WITHHELD_CHILD, SHOWN_CHILD].sort())); + expect(queryByLabelText(/items$/)).toBeNull(); }); it('CONTROL: a blank gate declares nothing and is counted', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); - const { findByLabelText } = renderTabs({ + const { ds } = renderTabs({ children: [relatedList(WITHHELD_CHILD, ''), relatedList(SHOWN_CHILD)], }); - expect((await findByLabelText('5 items')).textContent).toBe('5'); + await waitFor(() => expect(probedObjects(ds)).toEqual([WITHHELD_CHILD, SHOWN_CHILD].sort())); }); }); diff --git a/ui/packages/components/src/__tests__/page-tabs-count-visible-when-12987.test.tsx b/ui/packages/components/src/__tests__/page-tabs-count-visible-when-12987.test.tsx index 73819a55099..bc816c5426d 100644 --- a/ui/packages/components/src/__tests__/page-tabs-count-visible-when-12987.test.tsx +++ b/ui/packages/components/src/__tests__/page-tabs-count-visible-when-12987.test.tsx @@ -24,6 +24,9 @@ import { RelatedCountStore } from '../hooks/related-count-store'; // Registers the renderers at module scope, NOT inside a `beforeAll` — there the // cold transform is billed to `hookTimeout` (objectui#3010/#3021). import '../renderers'; +// `react-page` reaches this dynamically; load it during collection, not in a +// clocked case (`check:test-source-alias`). +import '@object-ui/react-runtime'; const RECORD_OBJECT = 'zz12987_env'; const PARENT_ID = 'ENV-1'; @@ -94,13 +97,15 @@ describe('page:tabs derived count skips a related list its own visibleWhen hides expect(probedObjects(ds)).toEqual([SHOWN_CHILD]); }); - it('CONTROL: counts both lists when both are shown', async () => { - const { findByLabelText, ds } = renderTabs('pro', { + it('CONTROL: both lists shown are both asked — and the tab, merging two tables, carries no number (objectstack#35595)', async () => { + const { queryByLabelText, ds } = renderTabs('pro', { children: [relatedList(HIDDEN_CHILD, PRO_ONLY), relatedList(SHOWN_CHILD)], }); - expect((await findByLabelText('5 items')).textContent).toBe('5'); - expect(probedObjects(ds)).toEqual([HIDDEN_CHILD, SHOWN_CHILD].sort()); + await waitFor(() => expect(probedObjects(ds)).toEqual([HIDDEN_CHILD, SHOWN_CHILD].sort())); + // One table, one count: the platform does not total two lists. + expect(queryByLabelText('5 items')).toBeNull(); + expect(queryByLabelText('2 items')).toBeNull(); }); it('CONTROL: an authored count wins over the derived one', async () => { @@ -141,8 +146,10 @@ describe('page:tabs derived count skips a related list its own visibleWhen hides it('drops the list from the badge when its gate closes on a later render', async () => { const overview = { children: [relatedList(HIDDEN_CHILD, PRO_ONLY), relatedList(SHOWN_CHILD)] }; - const { findByLabelText, rerender, ds } = renderTabs('pro', overview); - await findByLabelText('5 items'); + const { findByLabelText, queryByLabelText, rerender, ds } = renderTabs('pro', overview); + // Both shown: a merged tab, no number (objectstack#35595). + await waitFor(() => expect(probedObjects(ds)).toEqual([HIDDEN_CHILD, SHOWN_CHILD].sort())); + expect(queryByLabelText('5 items')).toBeNull(); rerender( = { zz35595_contact: 3, zz35595_case: 2, zz35595_quote: 0 }; + +const makeDS = () => ({ + find: vi.fn(async (object: string) => ({ data: [], total: TOTALS[object] ?? 0 })), + getObjectSchema: vi.fn(async (name: string) => ({ name, fields: {} })), +}); + +const relatedList = (objectName: string) => ({ + type: 'record:related_list', + properties: { objectName, relationshipField: 'account' }, +}); +const text = (content: string) => [{ type: 'element:text', properties: { content } }]; + +function renderTabs(items: any[]) { + const ds = makeDS(); + const utils = render( + + + , + ); + return { ...utils, ds }; +} + +const tabByLabel = (container: HTMLElement, label: string) => + Array.from(container.querySelectorAll('[role="tab"]')).find((el) => el.textContent?.startsWith(label)) as HTMLElement; +const badge = (tab: HTMLElement) => tab.querySelector('[aria-label$="items"], [aria-label$="item"]'); + +beforeEach(() => RelatedCountStore._reset()); +afterEach(() => { + cleanup(); + RelatedCountStore._reset(); +}); + +describe('page:tabs — one table, one count (objectstack#35595)', () => { + it('a tab merging two related lists carries no number', async () => { + const { container, findByLabelText } = renderTabs([ + { label: 'Related', value: 'related', children: [relatedList('zz35595_contact'), relatedList('zz35595_case')] }, + { label: 'Contacts', value: 'contacts', children: [relatedList('zz35595_contact')] }, + ]); + // CONTROL: the single-list tab on the same strip is counted. + expect((await findByLabelText('3 items')).textContent).toBe('3'); + expect(tabByLabel(container, 'Contacts').textContent).toBe('Contacts3'); + // The merged tab: no badge, and no 5 (= 3 + 2) anywhere. + const merged = tabByLabel(container, 'Related'); + expect(badge(merged)).toBeNull(); + expect(merged.textContent).toBe('Related'); + expect(container.querySelector('[aria-label="5 items"]')).toBeNull(); + }); + + it('a list with no records keeps its tab, muted, with no number; CONTROL: a counted one is not muted', async () => { + const { container, findByLabelText } = renderTabs([ + { label: 'Quotes', value: 'quotes', children: [relatedList('zz35595_quote')] }, + { label: 'Cases', value: 'cases', children: [relatedList('zz35595_case')] }, + ]); + await findByLabelText('2 items'); + await waitFor(() => expect(container.querySelector('[data-page-tab-empty]')).not.toBeNull()); + const quotes = tabByLabel(container, 'Quotes'); + const label = quotes.querySelector('[data-page-tab-empty]')!; + expect(label.textContent).toBe('Quotes'); + expect(label.className).toContain('opacity-70'); + expect(badge(quotes)).toBeNull(); + const cases = tabByLabel(container, 'Cases'); + expect(cases.querySelector('[data-page-tab-empty]')).toBeNull(); + expect(badge(cases)?.textContent).toBe('2'); + }); +}); + +describe('page:tabs — the 审批 tab\'s dot (objectstack#35595)', () => { + const approvals = (pendingRequest: unknown) => ({ + label: 'Approvals', + value: 'approvals', + children: [{ type: 'record:approvals', properties: { approvals: { available: true, requests: [{ id: 'r1' }], pendingRequest } } }], + }); + + it('a pending approval draws a dot on its tab, not a count', () => { + const { container } = renderTabs([approvals({ id: 'r1' })]); + const tab = tabByLabel(container, 'Approvals'); + expect(tab.querySelector('[data-page-tab-dot]')).not.toBeNull(); + expect(badge(tab)).toBeNull(); + expect(container.querySelectorAll('[data-page-tab-dot]')).toHaveLength(1); + }); + + it('CONTROL: an approval with nothing pending draws no dot', () => { + const { container } = renderTabs([approvals(null)]); + expect(container.querySelector('[data-page-tab-dot]')).toBeNull(); + }); +}); + diff --git a/ui/packages/components/src/__tests__/page-tabs-probe-route-id-13010.test.tsx b/ui/packages/components/src/__tests__/page-tabs-probe-route-id-13010.test.tsx index 3b66b1435a8..17800e4431d 100644 --- a/ui/packages/components/src/__tests__/page-tabs-probe-route-id-13010.test.tsx +++ b/ui/packages/components/src/__tests__/page-tabs-probe-route-id-13010.test.tsx @@ -27,6 +27,9 @@ import { RelatedCountStore } from '../hooks/related-count-store'; // Registers the renderers at module scope, NOT inside a `beforeAll` — there the // cold transform is billed to `hookTimeout` (objectui#3010/#3021). import '../renderers'; +// `react-page` reaches this dynamically; load it during collection, not in a +// clocked case (`check:test-source-alias`). +import '@object-ui/react-runtime'; const RECORD_OBJECT = 'zz13010_env'; const PARENT_ID = 'ENV-13010'; @@ -94,8 +97,11 @@ describe('page:tabs probes from the named record, not the loaded row (objectui#1 expect(probed(ds)).toEqual([OPEN_CHILD]); rerender(tree(ds, { id: PARENT_ID, plan: 'pro' }, overview)); - expect((await findByLabelText('5 items')).textContent).toBe('5'); - expect(probed(ds)).toEqual([GATED_CHILD, OPEN_CHILD].sort()); + await waitFor(() => expect(probed(ds)).toEqual([GATED_CHILD, OPEN_CHILD].sort())); + // Both shown now: the tab merges two tables and carries no number + // (objectstack#35595, one table, one count). + await waitFor(() => expect(document.querySelector('[aria-label="2 items"]')).toBeNull()); + expect(document.querySelector('[aria-label="5 items"]')).toBeNull(); }); it('a tab whose item-level visibleWhen decides it waits for the record body', async () => { diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index 5fabc80ead2..c542c310877 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -264,6 +264,8 @@ const KNOWN_LABEL_DICT: Record> = { */ const KNOWN_LABEL_KEYS: Record = { Details: 'detail.details', + // The synthesized record page's first tab, 「概览」 (objectstack#35595). + Overview: 'detail.recordTabOverview', Related: 'detail.related', Activity: 'detail.activity', History: 'detail.history', @@ -547,8 +549,9 @@ interface CollectedRelatedList { /** * Walk a tab's children (depth-first) and collect every `record:related_list` * schema node. Used to auto-derive a count for the tab badge when the spec - * author didn't supply one explicitly. Multiple lists are summed (Salesforce - * "Related" tab convention). + * author didn't supply one explicitly. A tab holding more than one list + * merges tables and carries no count (objectstack#35595: one table, one + * count). * * The gate is the node-level `visibleWhen`, the one key the spec declares for * it: `PageComponentSchema` declares `visibleWhen` on the node, and the @@ -743,6 +746,30 @@ function useStickyTopInset( return [setNode, inset]; } +/** + * Whether a tab's subtree holds a `record:approvals` block whose host handed it + * a pending request (`approvals.pendingRequest`, objectstack#35595): the 审批 + * tab's dot. A block that reads its approvals itself is not known here. + */ +const containsPendingApproval = (nodes: any): boolean => { + if (!nodes) return false; + const list = Array.isArray(nodes) ? nodes : [nodes]; + for (const n of list) { + if (!n || typeof n !== 'object') continue; + if (n.type === 'record:approvals') { + const approvals = n.properties?.approvals ?? n.approvals; + if (approvals?.pendingRequest) return true; + continue; + } + // `body` stays — same ground as `collectRelatedLists` above. + const candidates = [n.children, n.properties?.children, n.properties?.items, n.body, n.items]; + for (const c of candidates) { + if (c && containsPendingApproval(c)) return true; + } + } + return false; +}; + /** * Whether a tab's subtree holds a `list-view` block, the block that reports its * count through {@link PageTabPanelCountContext}. Walks the same slots @@ -1144,8 +1171,15 @@ const PageTabsRenderer: React.FC = ({ schema, className, ...props }) => { // useRelatedCountVersion above subscribed us to changes, so any store update — // whether from this effect or from an external invalidate — re-renders. // objectstack#26613 — plus what the tab's list blocks reported. + // + // objectstack#35595 — one table, one count: a record tab whose badge would + // add up several related tables (two related lists, a list and the + // attachments) merges tables, which only an authored page does, and its + // title carries no number — the platform does not total them for it. A tab + // of list blocks (an app page's, objectstack#26613) still sums its reports. const computeCount = (idx: number, value: string): number | undefined => { const probes = probeTargets.get(idx) ?? []; + if (probes.length > 1 || shownListsByItem[idx].length > 1) return undefined; let sum = 0; let seenAny = false; for (const p of probes) { @@ -1180,6 +1214,9 @@ const PageTabsRenderer: React.FC = ({ schema, className, ...props }) => { labelStr: translateLabel(pickLocalized(it.label, language), language, ttLabel), // Explicit spec count wins; otherwise fall back to the derived probe. count: authoredCount ? it.count : computeCount(idx, value), + // objectstack#35595 — the 审批 tab carries a dot while the approval its + // `record:approvals` block was handed is pending. + approvalPending: containsPendingApproval((it as any).children), // objectstack#26613 — a tab whose badge its list blocks answer is // mounted while inactive, so they run their queries; an authored count // needs none of that, and leaves the tab mounted on open only. @@ -1319,7 +1356,15 @@ const PageTabsRenderer: React.FC = ({ schema, className, ...props }) => { aria-hidden /> )} - {item.labelStr} + + {item.labelStr} + + {item.approvalPending && ( + + )} {item.count !== undefined && item.count !== null && item.count !== '' && Number(item.count) > 0 && ( = ({ const isPrintPage = usePrintPage() !== null; // objectstack#35253 — `false` on every details part of a split default page // but the first: the approval band is the record's, drawn once per page. + // objectstack#35483 / objectstack#35484 — and on a page drawn as written, + // the first body to reach the band's place draws it (`ApprovalBandOnceScope`). const drawsApprovalBand = React.useContext(ApprovalBandContext); + const approvalBandOnce = useApprovalBandOnce(); // objectstack#27055, objectstack#35019 — a record page's details body folds // its entirely empty sections into one line (`EmptySectionsLine`): every // `record:details` body, authored page or synthesized default page alike, @@ -1744,8 +1747,10 @@ export const DetailView: React.FC = ({ objectstack#35253 — and once per page: a default page split around a body table draws it on its first details part only - (`ApprovalBandContext`). */} - {inlineEdit && schema.showHeader === false && !isPrintPage && drawsApprovalBand && (() => { + (`ApprovalBandContext`), and on a page drawn as written by its + first details body (`ApprovalBandOnceScope`). */} + {inlineEdit && schema.showHeader === false && !isPrintPage && drawsApprovalBand && approvalBandOnce.mark} + {inlineEdit && schema.showHeader === false && !isPrintPage && drawsApprovalBand && approvalBandOnce.draws && (() => { // Two independent facts, not one (objectui#2902): // // isPending — an approval is running on this record. diff --git a/ui/packages/plugin-detail/src/RecordPageColumns.tsx b/ui/packages/plugin-detail/src/RecordPageColumns.tsx index a38d6c03749..294ddf0a453 100644 --- a/ui/packages/plugin-detail/src/RecordPageColumns.tsx +++ b/ui/packages/plugin-detail/src/RecordPageColumns.tsx @@ -17,18 +17,25 @@ import { type RecordPageTier, } from './synth/recordPageColumns'; import { useDetailTranslation } from './useDetailTranslation'; -import { RecordBodyTablesContext, RelatedEnlargeContext, RelatedListCompactContext, RelatedListEnlargedContext } from './relatedListCompact'; +import { RecordBodyTablesContext, RelatedEnlargeContext, RelatedListEnlargedContext } from './relatedListCompact'; import { ApprovalBandContext, DefaultRecordPageContext, DetailsColumnCapContext } from './defaultRecordPage'; -import { RelatedCardStack } from './RelatedCardStack'; -import { RecordTimelinePanel } from './RecordTimelinePanel'; +import { RelatedDefaultChangedHint, RelatedFootLine } from './RelatedCardStack'; import { RECORD_TAB_OVERVIEW, RecordTabRow, type RecordTab } from './RecordTabRow'; -import { partitionRecordTabsByRecords } from './synth/recordTabRow'; -import { RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordTimelineCountContext } from './recordTimelineStream'; +import { + RECORD_SUMMARY_APPROVALS, + RECORD_SUMMARY_ATTACHMENTS, + RecordSummaryRail, + approvalSummaryRows, + useRecordAttachmentCount, +} from './RecordSummaryRail'; +import { RecordTimelineCountContext } from './recordTimelineStream'; import { RecordTimelineCountProbe } from './renderers/record-activity'; import { + editRelatedArrangement, relatedCardId, resolveRelatedArrangement, type RelatedArrangement, + type RelatedArrangementEdit, type RelatedCardId, } from './synth/relatedArrangement'; import { relatedCountTargetOf, useRelatedCounts, type RelatedCountTarget } from './useRelatedCounts'; @@ -51,6 +58,11 @@ export interface RecordPageColumnsProps { * details — so it does not read the switch. Absent: on. */ rightColumn?: boolean; + /** + * Whether the 概览 tab draws its right rail at all (objectstack#35596: a + * drawer draws none). Absent: it does. + */ + rail?: boolean; /** * The reader's arrangement of the related panels (objectstack#27055, * Targets 7 and 10) — order, hidden — from the host's workspace preference @@ -87,6 +99,10 @@ export interface RecordPageColumnsProps { /** Rows per page of an enlarged related list whose block names no `limit`. */ const ENLARGED_PAGE_SIZE = 25; +/** A node's props: the ADR-0089 D3a `properties` bag over its own keys. */ +const nodeProps = (node: any): Record => + node && typeof node === 'object' ? { ...node, ...(node.properties ?? {}) } : {}; + /** The relationship id of a related-list node, or `null`. */ function relatedNodeId(node: any): RelatedCardId | null { const p = node && typeof node === 'object' ? { ...node, ...(node.properties ?? {}) } : null; @@ -245,19 +261,24 @@ const COLUMN_STACK = 'flex min-w-0 flex-col gap-4 [&>*:has(>[hidden]:only-child) /** * The synthesized default record page, laid out by the width it has * (objectstack#26678; one rule since objectstack#27524, Target 6): one record - * header, then the details and the right column — the related panels in the - * reader's arrangement (attachments and approvals close them), then the 动态 - * panel, last (objectstack#34590, which supersedes objectstack#27524 Targets - * 5 and 8's 动态-first for the right column, the stack and the tab row). + * header, the record's tab row (objectstack#35595: 概览, one tab per related + * list in the reader's arrangement, 附件, 审批, then 动态 last — every tab + * there at first paint, an empty list muted with no number, the width the + * row's only fold), then the open tab's face. + * + * 概览 draws the strip (`record:path`, `record:highlights`) across the whole + * width, then the details and the right rail — the summary of the other tabs + * (`RecordSummaryRail`, objectstack#35596: 审批, 附件, 最近动态, then the + * lists with records; a card with nothing to show is not drawn, and a rail + * known to have none folds away). Every other tab draws its block in full in + * place of all three. * - * - `two-column` / `wide`: details | the right column (320 / 380 px). The - * wide tier lets a details section take three field columns (two - * otherwise, `DetailsColumnCapContext`) and the 动态 panel five entries - * (three otherwise). The reader's ⊟ (`rightColumn`) takes the right - * column out; the details then take the row. - * - `stack`: ONE column — the details, then the right column's panels in - * their order. No tabs, no rail: the stack is what a narrow container - * (the split pane, a phone) draws. + * - `two-column` / `wide`: details | the rail (320 / 380 px). The wide tier + * lets a details section take three field columns (two otherwise, + * `DetailsColumnCapContext`). The reader's ⊟ (`rightColumn`) takes the + * rail out; the details then take the row. A host that draws no rail (a + * drawer, `rail={false}`) draws the details alone. + * - `stack`: ONE column — the details, then the rail. * * The frame mirrors the record page frame `PageRenderer` draws (its padding * and background, the header nodes 16 px apart), so the header sits where an @@ -272,6 +293,7 @@ export const RecordPageColumns: React.FC = ({ columns, footer, rightColumn = true, + rail = true, relatedArrangement, onRelatedArrangementChange, onEnlargeRelated, @@ -284,32 +306,34 @@ export const RecordPageColumns: React.FC = ({ const ctx = useRecordContext(); const bodyTableIds = React.useMemo(() => new Set(relatedListIdsIn(columns.details)), [columns.details]); const hasTimeline = columns.timeline.length > 0; - const hasPanels = hasTimeline || columns.related.length > 0; const wide = tier === 'wide'; const besideDetails = tier !== 'stack'; - const drawsPanels = hasPanels && (!besideDetails || rightColumn); - const viewAllTimeline = React.useCallback( - () => onEnlargeRelated?.(RECORD_PAGE_TIMELINE_PANEL), - [onEnlargeRelated], - ); - // ── The reader's arrangement, read once for the panels and the tab row ── - // A host without a preference store keeps the reader's choices here, for - // this view, so the stack and the row read the same one. - const [localArrangement, setLocalArrangement] = React.useState(undefined); - const arrangement = onRelatedArrangementChange ? relatedArrangement : localArrangement; - const onArrangementChange = onRelatedArrangementChange ?? setLocalArrangement; + // ── The right column's blocks: the related lists, 附件 and 审批 ── + const approvalsNode = columns.related.find((node) => node?.type === 'record:approvals'); + const attachmentsNode = columns.related.find((node) => node?.type === 'record:attachments'); const panelNodes = new Map(); for (const node of columns.related) { const id = relatedNodeId(node); if (id && !panelNodes.has(id)) panelNodes.set(id, node); } + const hasPanels = hasTimeline || columns.related.length > 0; + // objectstack#35596 — the rail is the 概览 tab's, and a drawer draws none. + const drawsPanels = rail && hasPanels && (!besideDetails || rightColumn); + + // ── The reader's arrangement of the related lists, read for the tab row ── + // A host without a preference store keeps the reader's choices here, for + // this view. + const [localArrangement, setLocalArrangement] = React.useState(undefined); + const arrangement = onRelatedArrangementChange ? relatedArrangement : localArrangement; + const onArrangementChange = onRelatedArrangementChange ?? setLocalArrangement; const [now] = React.useState(() => Date.now()); - const resolved = resolveRelatedArrangement(Array.from(panelNodes.keys()), arrangement, now); + const defaultOrder = Array.from(panelNodes.keys()); + const resolved = resolveRelatedArrangement(defaultOrder, arrangement, now); - // ── The panels' counts, one set for the panels and their tabs ── - // The hidden panels are counted too: their tabs sit in the row's dropdown - // with their counts (Target 8). + // ── The related lists' counts, one set for the tabs and the rail ── + // The hidden lists are counted too: their tabs sit in the row's dropdown + // with their counts. const countTargets: RelatedCountTarget[] = []; for (const id of [...resolved.order, ...resolved.hidden]) { const target = relatedCountTargetOf(panelNodes.get(id)); @@ -324,8 +348,12 @@ export const RecordPageColumns: React.FC = ({ const state = counts.stateOf(id); return state.kind === 'counted' ? state.count : null; }; + // objectstack#35595 — 附件 counts the record's files; 审批 carries a dot + // while an approval waits. + const attachmentCount = useRecordAttachmentCount(!!attachmentsNode); + const approvalPending = !!approvalsNode && approvalSummaryRows(nodeProps(approvalsNode).approvals, undefined) !== null; - // ── The 动态 stream's size, for its panel and its tab ── + // ── The 动态 stream's size, for its card and its tab ── // Held per record, so a pane stepping to the next record never shows the // last one's number; kept while neither face that reports it is drawn. const recordKey = ctx?.recordId === undefined || ctx?.recordId === null ? '' : String(ctx.recordId); @@ -342,11 +370,19 @@ export const RecordPageColumns: React.FC = ({ const streamCount = timelineCount.record === recordKey ? timelineCount.count : null; // ── The active tab: the open face ── - // The 动态 stream in full, or a related list — body tables (in the details) - // open in place too (their ⤢), and take a tab of their own while open. + // A related list, 附件, 审批 or the 动态 stream in full — body tables (in the + // details) open in place too (their ⤢), and take a tab of their own while + // open. let enlarged: React.ReactNode = null; let activeTab = RECORD_TAB_OVERVIEW; let openBodyTable: RecordTab | null = null; + const attachmentsTitle = t('detail.attachments', { defaultValue: 'Attachments' }); + const approvalsTitle = t('detail.approvalsPanelTitle', { defaultValue: 'Approvals' }); + const blockFace = (id: string, title: string, node: any) => ( + + + + ); if (enlargedRelated === RECORD_PAGE_TIMELINE_PANEL && hasTimeline) { activeTab = RECORD_PAGE_TIMELINE_PANEL; enlarged = ( @@ -360,6 +396,12 @@ export const RecordPageColumns: React.FC = ({ ); + } else if (enlargedRelated === RECORD_SUMMARY_ATTACHMENTS && attachmentsNode) { + activeTab = RECORD_SUMMARY_ATTACHMENTS; + enlarged = blockFace(RECORD_SUMMARY_ATTACHMENTS, attachmentsTitle, attachmentsNode); + } else if (enlargedRelated === RECORD_SUMMARY_APPROVALS && approvalsNode) { + activeTab = RECORD_SUMMARY_APPROVALS; + enlarged = blockFace(RECORD_SUMMARY_APPROVALS, approvalsTitle, approvalsNode); } else if (enlargedRelated) { const node = [...columns.related, ...columns.details].find((n) => relatedNodeId(n) === enlargedRelated); if (node) { @@ -373,35 +415,22 @@ export const RecordPageColumns: React.FC = ({ } } - // ── The tab row (Target 8): 概览, the panels in the reader's order, 动态 ── - // The panels with records first and the empty ones in the dropdown - // (objectstack#28469), as the right column folds its empty panels. 动态 is - // the row's last tab, as it is the right column's last panel - // (objectstack#34590, superseding objectstack#27524 Target 8's 动态-second). + // ── The tab row (objectstack#35595): 概览, every related list, 附件, 审批, 动态 ── + // Every related list has its tab whether or not it has records — muted and + // without a number at 0 — so no tab moves when the counts land; the width + // is the row's only fold (「更多 N ▾」, `RecordTabRow`). 动态 is the row's + // last tab (objectstack#34590). const panelTab = (id: RelatedCardId): RecordTab => ({ id, label: relatedNodeTitle(panelNodes.get(id)), count: countOf(id), }); const tabs: RecordTab[] = [{ id: RECORD_TAB_OVERVIEW, label: t('detail.recordTabOverview', { defaultValue: 'Overview' }) }]; - // While the panels' first count set is still out (the right column draws its - // count skeletons meanwhile) their tabs wait off the row, so a tab that turns - // out empty never draws on the row and then leaves it: the tabs appear once, - // already in place. The active tab is always drawn; a list that is never - // counted (no source, a refused read) keeps its place in the arrangement. - const panelTabs = partitionRecordTabsByRecords( - resolved.order.filter((id) => id === activeTab || counts.stateOf(id).kind !== 'pending').map(panelTab), - ); - tabs.push(...panelTabs.withRecords); + tabs.push(...resolved.order.map(panelTab)); if (openBodyTable) tabs.push(openBodyTable); - // 动态 comes after the panels' tabs, so it too waits off the row while their - // first set is out (every panel still pending): drawn at once, it would move - // when they land in front of it — the move the rule above keeps out - // (objectstack#28469, Target 2). Drawn when it is the active tab. - const firstPanelSetOut = - resolved.order.length > 0 && resolved.order.every((id) => counts.stateOf(id).kind === 'pending'); - const timelineHeld = hasTimeline && firstPanelSetOut && activeTab !== RECORD_PAGE_TIMELINE_PANEL; - if (hasTimeline && !timelineHeld) { + if (attachmentsNode) tabs.push({ id: RECORD_SUMMARY_ATTACHMENTS, label: attachmentsTitle, count: attachmentCount }); + if (approvalsNode) tabs.push({ id: RECORD_SUMMARY_APPROVALS, label: approvalsTitle, dot: approvalPending }); + if (hasTimeline) { tabs.push({ id: RECORD_PAGE_TIMELINE_PANEL, label: t('detail.timeline', { defaultValue: 'Activity' }), count: streamCount }); } const hiddenTabs = resolved.hidden.map(panelTab); @@ -409,18 +438,9 @@ export const RecordPageColumns: React.FC = ({ if (id === RECORD_TAB_OVERVIEW) onCloseEnlargedRelated?.(); else onEnlargeRelated?.(id); }; - // A held 动态 tab still counts toward drawing the row, so the row is there - // from the first paint (概览 alone while the set is out) and the page below - // it does not shift when the tabs land. const tabRow = - onEnlargeRelated && tabs.length + (timelineHeld ? 1 : 0) + panelTabs.empty.length + hiddenTabs.length > 1 ? ( - + onEnlargeRelated && tabs.length + hiddenTabs.length > 1 ? ( + ) : null; // The provenance line closes the details column in every tier @@ -431,41 +451,81 @@ export const RecordPageColumns: React.FC = ({ {footer} ); - const rightPanels = drawsPanels ? ( + const editArrangement = (edit: RelatedArrangementEdit) => + onArrangementChange(editRelatedArrangement(defaultOrder, arrangement, edit, now)); + // objectstack#35596 — a rail with nothing to show takes no column: once + // every card is KNOWN to be absent (no approval waiting, no files, a + // counted stream with no entries, every list counted with no records — a + // refused count draws no card either — and nothing at the foot), the + // details take the row. While a count is still out the column stays, so a + // page whose cards land does not shift. A slotted chatter stream reports + // no count, so its card always draws. + const streamCounted = columns.timeline.some((node) => node?.type === 'record:activity'); + const railKnownEmpty = + !approvalPending + && (!attachmentsNode || attachmentCount === 0) + && (!hasTimeline || (streamCounted && streamCount === 0)) + && resolved.order.every((id) => { + const state = counts.stateOf(id); + return state.kind !== 'pending' && !(state.kind === 'counted' && state.count > 0); + }) + && resolved.hidden.length === 0 + && !resolved.rearranged + && !resolved.defaultChanged; + const drawsRail = drawsPanels && !railKnownEmpty; + const rightPanels = drawsRail ? ( ) : null; - // A face with neither the 动态 panel nor its tab drawn — another tab open, - // or the right column switched off — still names the stream's count on the - // 动态 tab (objectstack#27524): counted from the feed the host holds. - const probesTimelineCount = hasTimeline && !!tabRow && activeTab !== RECORD_PAGE_TIMELINE_PANEL - && (enlarged !== null || !drawsPanels); - const sideBySide = besideDetails && drawsPanels; + // A face with no 动态 card drawn — another tab open, the right column + // switched off, or a drawer — still names the stream's count on the 动态 + // tab (objectstack#27524): counted from the feed the host holds. + // A rail folded away for want of cards still learns of a new entry: the + // probe counts for it, and the rail comes back with its 最近动态 card. + const probesTimelineCount = hasTimeline && activeTab !== RECORD_PAGE_TIMELINE_PANEL + && ((!!tabRow && (enlarged !== null || !drawsPanels)) || (enlarged === null && drawsPanels && !drawsRail)); + // Folded away, the rail keeps the size its card last read: a probe that + // cannot count (no feed held by the host — the stream reads its own) says + // nothing rather than unknown, so the rail does not come back empty. + const railFolded = enlarged === null && drawsPanels && !drawsRail; + const reportProbedCount = React.useCallback( + (count: number | null) => { + if (count !== null) reportTimelineCount(count); + }, + [reportTimelineCount], + ); + const sideBySide = besideDetails && drawsRail; const template = sideBySide ? (wide ? GRID_TEMPLATE.wide : GRID_TEMPLATE.twoColumn) : GRID_TEMPLATE.oneColumn; return ( @@ -481,16 +541,28 @@ export const RecordPageColumns: React.FC = ({
{drawNodes(columns.header)} {tabRow} - {probesTimelineCount && } + {probesTimelineCount && ( + + )} {enlarged ?? ( -
- {detailsColumn} - {rightPanels} -
+ <> + {/* objectstack#35595 — the stage path and the key fields are the + 概览 tab's top, across the whole width (both columns), and + no other tab's. */} + {columns.strip.length > 0 && ( +
+ {drawNodes(columns.strip)} +
+ )} +
+ {detailsColumn} + {rightPanels} +
+ )}
diff --git a/ui/packages/plugin-detail/src/RecordSummaryRail.tsx b/ui/packages/plugin-detail/src/RecordSummaryRail.tsx new file mode 100644 index 00000000000..939dc8df0c0 --- /dev/null +++ b/ui/packages/plugin-detail/src/RecordSummaryRail.tsx @@ -0,0 +1,544 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import * as React from 'react'; +import { ChevronRight } from 'lucide-react'; +import { cn, RelatedCountStore, useRelatedCountVersion } from '@object-ui/components'; +import { columnIdentity, composeParentScopeFilter, mergeFilterNodes, type FieldContainerLike } from '@object-ui/core'; +import { formatCurrency } from '@object-ui/fields'; +import { resolveFieldCurrency, useDisplayLocale, useLocalization, withFollowedParent } from '@object-ui/i18n'; +import { SchemaRenderer, toRenderableSchema, useRecordContext } from '@object-ui/react'; +import { RecordTimelinePanelContext, type RecordTimelinePanel } from './recordTimelineStream'; +import { resolveTitleField } from './synth/buildDefaultPageSchema'; +import type { RelatedCardId } from './synth/relatedArrangement'; +import { useDetailTranslation } from './useDetailTranslation'; + +/** + * The 概览 tab's right rail (objectstack#35596): one small summary card per + * other tab that has something to show, in a fixed order — 审批, 附件, 最近动态, + * then 「其他相关」 with one card per related list that HAS records. Each card + * is a title, a grey count (or a status), and at most three rows; the whole + * title opens its tab. A card with nothing in it is not drawn, and nothing + * stands in for the empty lists (no 「还有 N 个空关联」 line). Nothing in the + * rail is editable: no composer, no upload. + * + * The rail is a summary of the tabs, never a second copy of them: each card + * reads what the tab's own block reads (the approvals the host hands the + * `record:approvals` node, the record's `sys_attachment` rows, the 动态 + * stream, a related list's first rows) and the tab draws the whole. + */ + +/** The ids of the rail's own cards; a related card's id is its relationship id. */ +export const RECORD_SUMMARY_APPROVALS = 'approvals'; +export const RECORD_SUMMARY_ATTACHMENTS = 'attachments'; + +/** The most rows a summary card shows. */ +export const RECORD_SUMMARY_ROWS = 3; + +const rowsOf = (res: any): any[] => (Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : []); + +/** + * The rows a summary card draws, for one question (`null`: nothing to ask). + * The record page's one read (objectstack#27627) holds each list's first rows + * in the related-count store: `take` hands them over, once; without them the + * card reads for itself (`read`). The answer is kept per question, so an + * effect React runs twice (StrictMode) draws the rows it took instead of + * finding the hand-off spent and reading again. A refused read draws no rows. + */ +function useSummaryRows( + question: string | null, + take: () => Promise<{ rows: any[] }> | undefined, + read: () => Promise, +): any[] | null { + const [rows, setRows] = React.useState(null); + const asked = React.useRef<{ question: string; answer: Promise } | null>(null); + React.useEffect(() => { + if (question === null) return undefined; + let answer = asked.current?.question === question ? asked.current.answer : undefined; + if (!answer) { + const seeded = take(); + answer = (seeded ? seeded.then((res) => res.rows) : read()).catch(() => []); + asked.current = { question, answer }; + } + let cancelled = false; + void answer.then((next) => { + if (!cancelled) setRows(next); + }); + return () => { + cancelled = true; + }; + // `take` and `read` answer the question; it names everything they read. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [question]); + return rows; +} + +export interface RecordSummaryRelated { + id: RelatedCardId; + /** The tab's `record:related_list` node. */ + node: any; + /** Its count; `null` while unknown. Only a count above 0 draws a card. */ + count: number | null; +} + +export interface RecordSummaryRailProps { + /** The related lists, in the tab row's order. */ + related: readonly RecordSummaryRelated[]; + /** The 审批 tab's `record:approvals` node, when the page has one. */ + approvals?: any; + /** Whether the page has an 附件 tab, and the count it shows. */ + attachments?: { count: number | null } | null; + /** The 动态 tab's blocks, and the count the tab shows. */ + timeline: any[]; + timelineCount: number | null; + onTimelineCount: (count: number | null) => void; + /** Open a tab: the card's title. Absent: the titles open nothing. */ + onOpen?: (id: string) => void; + /** The child objects' field definitions the host holds. */ + fieldsOf?: (objectName: string) => FieldContainerLike; + /** Drawn after the cards (the related panels' hidden-line). */ + footer?: React.ReactNode; +} + +/** + * One summary card: radius 8, a 13 px title with its grey count, rows 26 px + * high (objectstack#35596 item 5). The title is one button, the card's whole + * header, ending in 「›」. + */ +export const RecordSummaryCard: React.FC<{ + id: string; + title: string; + count?: number | null; + status?: React.ReactNode; + onOpen?: (id: string) => void; + hidden?: boolean; + children?: React.ReactNode; +}> = ({ id, title, count, status, onOpen, hidden, children }) => ( + +); + +/** A card's row: 26 px, the text on the left and its value on the right. */ +const SummaryRow: React.FC<{ left: React.ReactNode; right?: React.ReactNode; title?: string }> = ({ left, right, title }) => ( +
  • + {left} + {right !== undefined && right !== null && right !== '' && ( + {right} + )} +
  • +); + +const SummaryRows: React.FC<{ children: React.ReactNode }> = ({ children }) => ( +
      {children}
    +); + +type PageNode = Record; + +const propsOf = (node: unknown): PageNode => { + const raw = (node && typeof node === 'object' ? node : {}) as PageNode; + return raw.properties && typeof raw.properties === 'object' ? { ...raw, ...raw.properties } : raw; +}; + +// ── 审批 ─────────────────────────────────────────────────────────────────── + +interface ApprovalStepRow { + key: string; + label: string; + state: 'done' | 'mine' | 'waiting'; + waitingOn?: string; +} + +/** + * The pending approval's steps, at most three, ending at the step it waits + * on: the request's own route (`flow_route`, the server's) when it carries + * one, else the pending step alone. `null` when nothing is pending — the card + * is drawn only while an approval runs (objectstack#35596 item 4). + */ +export function approvalSummaryRows(approvals: any, currentUserId: string | undefined): ApprovalStepRow[] | null { + const pending = approvals?.pendingRequest; + if (!pending || typeof pending !== 'object') return null; + const approvers: string[] = Array.isArray(pending.pending_approvers) ? pending.pending_approvers : []; + const mine = pending.viewer?.can_act === true || (!!currentUserId && approvers.includes(currentUserId)); + const names: Record = pending.pending_approver_names ?? {}; + const waitingOn = approvers.map((id) => names[id]).filter((n): n is string => typeof n === 'string' && n !== ''); + const currentLabel: string = pending.step_label || pending.current_step || pending.process_label || pending.process_name || ''; + const current: ApprovalStepRow = { + key: 'current', + label: currentLabel, + state: mine ? 'mine' : 'waiting', + ...(waitingOn.length > 0 ? { waitingOn: waitingOn.join(', ') } : {}), + }; + const steps: any[] = Array.isArray(pending.flow_route?.steps) ? pending.flow_route.steps : []; + const at = steps.findIndex((s) => s?.state === 'current'); + if (at < 0) return [current]; + const rows: ApprovalStepRow[] = steps + .slice(0, at) + .filter((s) => s?.state === 'done') + .map((s, i) => ({ key: `done-${s.id ?? i}`, label: String(s.label ?? s.id ?? ''), state: 'done' as const })); + rows.push({ ...current, label: String(steps[at].label ?? currentLabel) }); + return rows.slice(-RECORD_SUMMARY_ROWS); +} + +const ApprovalsSummary: React.FC<{ node: any; onOpen?: (id: string) => void }> = ({ node, onOpen }) => { + const { t } = useDetailTranslation(); + const p = propsOf(node); + const rows = approvalSummaryRows(p.approvals, p.currentUserId); + if (!rows) return null; + const stateText = (row: ApprovalStepRow) => + row.state === 'done' + ? t('detail.summaryApprovalDone', { defaultValue: 'Approved' }) + : row.state === 'mine' + ? t('detail.summaryApprovalMine', { defaultValue: 'Awaiting you' }) + : row.waitingOn + ? t('detail.summaryApprovalWaitingOn', { name: row.waitingOn, defaultValue: 'Waiting on {{name}}' }) + : t('detail.summaryApprovalWaiting', { defaultValue: 'Waiting' }); + return ( + + + {rows.map((row) => ( + {stateText(row)}
    } + /> + ))} + + + ); +}; + +// ── 附件 ─────────────────────────────────────────────────────────────────── + +/** + * The related-count store key the record's attachments are counted under: the + * synthetic relationship the 附件 tab badge probes (`page:tabs`), which the + * record page payload seeds and the panel takes its rows from. + */ +export const attachmentsCountField = (objectName: string): string => `attachments:${objectName}`; + +/** + * How many attachments the record holds, through the store the tab badge and + * the panel share: the probe is the badge's own (the `(parent_object, + * parent_id)` scope), so a page payload that seeded it answers at once. + * `null` while unknown, or with nothing to ask. + */ +export function useRecordAttachmentCount(enabled: boolean): number | null { + const ctx = useRecordContext(); + useRelatedCountVersion(); + const objectName = ctx?.objectName; + const parentId = ctx?.recordId === undefined || ctx?.recordId === null ? undefined : String(ctx.recordId); + const ds: any = ctx?.dataSource; + const field = objectName ? attachmentsCountField(objectName) : undefined; + const cached = enabled && field && parentId ? RelatedCountStore.get('sys_attachment', field, parentId) : undefined; + React.useEffect(() => { + if (!enabled || !field || !parentId || !ds || typeof ds.find !== 'function') return; + if (RelatedCountStore.get('sys_attachment', field, parentId) !== undefined) return; + const finder = (object: string, query: any) => + ds.find(object, { ...query, $filter: { parent_object: objectName, parent_id: parentId } }); + void RelatedCountStore.fetch(finder, 'sys_attachment', field, parentId).catch(() => 0); + }, [enabled, field, parentId, ds, objectName, cached]); + return typeof cached === 'number' ? cached : null; +} + +const formatSize = (bytes: unknown): string => { + if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return ''; + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; +}; + +const AttachmentsSummary: React.FC<{ count: number | null; onOpen?: (id: string) => void }> = ({ count, onOpen }) => { + const { t } = useDetailTranslation(); + const ctx = useRecordContext(); + const ds: any = ctx?.dataSource; + const objectName = ctx?.objectName; + const parentId = ctx?.recordId === undefined || ctx?.recordId === null ? undefined : String(ctx.recordId); + const has = typeof count === 'number' && count > 0; + const rows = useSummaryRows( + has && ds && typeof ds.find === 'function' && objectName && parentId + ? JSON.stringify([objectName, parentId, count]) + : null, + // The payload's newest attachments, under the key the 附件 tab counts. + () => RelatedCountStore.takeRows('sys_attachment', attachmentsCountField(objectName!), parentId!, undefined, RECORD_SUMMARY_ROWS), + async () => + rowsOf( + await ds.find('sys_attachment', { + $filter: { parent_object: objectName, parent_id: parentId }, + $orderby: { created_at: 'desc' }, + $top: RECORD_SUMMARY_ROWS, + }), + ), + ); + if (!has) return null; + return ( + + {rows && rows.length > 0 && ( + + {rows.slice(0, RECORD_SUMMARY_ROWS).map((row, i) => ( + + ))} + + )} + + ); +}; + +// ── 最近动态 ──────────────────────────────────────────────────────────────── + +/** + * The 动态 card: the stream's own blocks in their peek face, the newest three, + * with no composer (`showCommentInput: false` — nothing in the rail is + * editable) and no 「查看全部」 of their own (the title opens the tab). It stays + * mounted, `hidden`, until the stream reports entries, because the count it + * shows is the one the stream reports. A slotted page's `record:chatter` / + * `record:discussion` stream reports no count, so its card is drawn as it + * comes — its first page of three, read-only (`feed.showCommentInput: false`, + * `feed.limit: 3`). + */ +const TimelineSummary: React.FC<{ + nodes: any[]; + count: number | null; + onCount: (count: number | null) => void; + onOpen?: (id: string) => void; + timelineId: string; +}> = ({ nodes, count, onCount, onOpen, timelineId }) => { + const { t } = useDetailTranslation(); + const panel = React.useMemo( + () => ({ entries: RECORD_SUMMARY_ROWS, onCount }), + [onCount], + ); + const peekNodes = React.useMemo(() => nodes.map(readOnlyStreamNode), [nodes]); + const counted = nodes.some((node) => node && typeof node === 'object' && node.type === 'record:activity'); + return ( + + ); +}; + +/** A stream block as the rail draws it: read-only, the newest few. */ +function readOnlyStreamNode(node: any): any { + if (!node || typeof node !== 'object') return node; + const props = node.properties ?? {}; + if (node.type === 'record:activity') return { ...node, properties: { ...props, showCommentInput: false } }; + if (node.type === 'record:chatter' || node.type === 'record:discussion') { + const feed = { ...(node.feed ?? {}), ...(props.feed ?? {}), showCommentInput: false, limit: RECORD_SUMMARY_ROWS }; + return { ...node, ...(node.feed ? { feed } : {}), properties: { ...props, feed } }; + } + return node; +} + +// ── 其他相关 ──────────────────────────────────────────────────────────────── + +// A list column's field: the one shared reader, canonical-first (objectui#3104). +const columnKey = (col: unknown): string | undefined => columnIdentity(col); + +const fieldMap = (fields: FieldContainerLike | undefined): Record => { + if (!fields) return {}; + if (Array.isArray(fields)) { + const out: Record = {}; + for (const f of fields as any[]) if (f && typeof f.name === 'string') out[f.name] = f; + return out; + } + return fields as Record; +}; + +const KEY_VALUE_TYPES = ['currency', 'select', 'status'] as const; + +/** + * The key value a related row shows beside its name (objectstack#35596 item + * 2): the list's first amount column, else its first status column — read off + * the list's declared columns, then the child's fields in order. + */ +export function relatedKeyValueField(columns: unknown, fields: FieldContainerLike | undefined): string | null { + const defs = fieldMap(fields); + const declared = Array.isArray(columns) ? columns.map(columnKey).filter((k): k is string => !!k) : []; + const keys = declared.length > 0 ? declared : Object.keys(defs); + for (const type of KEY_VALUE_TYPES) { + const hit = keys.find((k) => defs[k]?.type === type); + if (hit) return hit; + } + return null; +} + +const RelatedSummary: React.FC<{ + entry: RecordSummaryRelated; + onOpen?: (id: string) => void; + fieldsOf?: (objectName: string) => FieldContainerLike; +}> = ({ entry, onOpen, fieldsOf }) => { + const ctx = useRecordContext(); + const ds: any = ctx?.dataSource; + const parentId = ctx?.recordId; + const locale = useDisplayLocale(); + const { currency: tenantCurrency } = useLocalization(); + const p = propsOf(entry.node); + const objectName: string = p.objectName; + const relationshipField: string = p.relationshipField; + const title: string = typeof p.title === 'string' && p.title ? p.title : objectName; + const [fields, setFields] = React.useState(() => fieldsOf?.(objectName)); + const filterKey = JSON.stringify(p.filter ?? null); + // The child's field definitions: the host's, else the data source's. Read + // once per object; the scope filter and the row's name and value need them. + const defsRead = React.useRef<{ objectName: string; read: Promise } | null>(null); + const defsOf = (): Promise => { + if (defsRead.current?.objectName !== objectName) { + const held = fieldsOf?.(objectName); + const read: Promise = + held || !ds || typeof ds.getObjectSchema !== 'function' + ? Promise.resolve(held) + : Promise.resolve(ds.getObjectSchema(objectName)).then((schema: any) => schema?.fields, () => undefined); + defsRead.current = { objectName, read }; + } + return defsRead.current.read; + }; + React.useEffect(() => { + let cancelled = false; + void defsOf().then((defs) => { + if (!cancelled) setFields(defs); + }); + return () => { + cancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ds, objectName]); + const rows = useSummaryRows( + ds && typeof ds.find === 'function' && parentId !== undefined && parentId !== null + ? JSON.stringify([objectName, relationshipField, String(parentId), filterKey, entry.count]) + : null, + // The record page's one read (objectstack#27627) holds each list's first + // rows: take them rather than read again. + () => RelatedCountStore.takeRows(objectName, relationshipField, String(parentId), p.filter ?? undefined, RECORD_SUMMARY_ROWS), + async () => { + const scope = composeParentScopeFilter(relationshipField, parentId as string | number, await defsOf()); + return rowsOf(await ds.find(objectName, { $filter: mergeFilterNodes(scope, p.filter), $top: RECORD_SUMMARY_ROWS })); + }, + ); + + const defs = fieldMap(fields); + const nameField = resolveTitleField({ name: objectName, fields: defs } as any) ?? 'name'; + const valueField = relatedKeyValueField(p.columns, fields); + const valueOf = (row: any): string => { + if (!valueField) return ''; + const def = defs[valueField]; + const raw = row?.[valueField]; + if (raw === null || raw === undefined || raw === '') return ''; + if (def?.type === 'currency') { + const n = typeof raw === 'number' ? raw : Number(raw); + if (!Number.isFinite(n)) return ''; + const code = resolveFieldCurrency(def, tenantCurrency, withFollowedParent(row, def, ctx?.data as any)); + return formatCurrency(n, code, locale); + } + const options: any[] = Array.isArray(def?.options) ? def.options : []; + const option = options.find((o) => (o && typeof o === 'object' ? o.value : o) === raw); + return option && typeof option === 'object' && typeof option.label === 'string' ? option.label : String(raw); + }; + return ( + + {rows && rows.length > 0 && ( + + {rows.slice(0, RECORD_SUMMARY_ROWS).map((row, i) => { + const name = row?.[nameField] ?? row?.name ?? row?.id ?? ''; + return ; + })} + + )} + + ); +}; + +/** The 动态 tab's id (`RECORD_PAGE_TIMELINE_PANEL`), passed in to keep this file free of the page module. */ +const TIMELINE_ID = 'timeline'; + +export const RecordSummaryRail: React.FC = ({ + related, + approvals, + attachments, + timeline, + timelineCount, + onTimelineCount, + onOpen, + fieldsOf, + footer, +}) => { + const { t } = useDetailTranslation(); + const withRecords = related.filter((entry) => typeof entry.count === 'number' && entry.count > 0); + return ( + <> + {approvals && } + {attachments && } + {timeline.length > 0 && ( + + )} + {withRecords.length > 0 && ( + <> +

    + {t('detail.summaryOtherRelated', { defaultValue: 'Other related' })} +

    + {withRecords.map((entry) => ( + + ))} + + )} + {footer} + + ); +}; diff --git a/ui/packages/plugin-detail/src/RecordTabRow.tsx b/ui/packages/plugin-detail/src/RecordTabRow.tsx index fcd06a29dfe..dcadbd5eda9 100644 --- a/ui/packages/plugin-detail/src/RecordTabRow.tsx +++ b/ui/packages/plugin-detail/src/RecordTabRow.tsx @@ -17,7 +17,7 @@ import { cn, } from '@object-ui/components'; import { ChevronDown } from 'lucide-react'; -import { arrangeRecordTabRow, layoutRecordTabRow } from './synth/recordTabRow'; +import { layoutRecordTabRow } from './synth/recordTabRow'; import { useDetailTranslation } from './useDetailTranslation'; /** The id of the row's first tab, 「概览」: the page itself, no `?related=`. */ @@ -25,22 +25,28 @@ export const RECORD_TAB_OVERVIEW = 'overview'; /** One tab of the record page's tab row. */ export interface RecordTab { - /** `overview`, `timeline` (动态), or a related list's `object.field`. */ + /** + * `overview`, `timeline` (动态), `attachments`, `approvals`, or a related + * list's `object.field`. + */ id: string; label: string; - /** The panel's count; absent or `null` while it is not known (no chip). */ + /** + * The panel's count; absent or `null` while it is not known (no chip). `0` + * draws no number either: the tab's label is muted instead + * (objectstack#35595, 「没有记录的不带数字、字色稍淡」). + */ count?: number | null; + /** + * A dot after the label instead of a count — the 审批 tab while an approval + * is pending (objectstack#35595). + */ + dot?: boolean; } export interface RecordTabRowProps { /** The row's tabs in their order; the first is 「概览」. */ tabs: readonly RecordTab[]; - /** - * The empty related lists' tabs (objectstack#28469): never on the row — - * unless one is active, which then takes the row's last slot — and listed in - * the dropdown after the folded tabs, behind a separator, in a muted face. - */ - emptyTabs?: readonly RecordTab[]; /** The hidden panels' tabs: never on the row, at the end of the dropdown. */ hiddenTabs?: readonly RecordTab[]; /** The active tab's id; always on the row. */ @@ -67,13 +73,25 @@ const CountChip: React.FC<{ count: number; muted?: boolean }> = ({ count, muted
    ); -const hasCount = (tab: RecordTab): tab is RecordTab & { count: number } => typeof tab.count === 'number'; +const hasCount = (tab: RecordTab): tab is RecordTab & { count: number } => + typeof tab.count === 'number' && tab.count > 0; + +/** Whether a tab's list is known to be empty: a count of `0`. */ +export const isEmptyRecordTab = (tab: RecordTab): boolean => tab.count === 0; -/** A tab's face, shared by the row's button and the measuring copy. */ +/** + * A tab's face, shared by the row's button, the dropdown's items and the + * measuring copy: the label, then the count chip (above 0) or the dot. + */ const TabFace: React.FC<{ tab: RecordTab; muted?: boolean }> = ({ tab, muted }) => ( <> - {tab.label} + + {tab.label} + {hasCount(tab) && } + {tab.dot && ( + + )} ); @@ -83,39 +101,37 @@ const TAB_CLASS = /** * The record page's tab row (objectstack#27524, Target 8): at the bottom * edge of the record header, on every face — 「概览」, then one tab per panel - * (the related panels in the reader's arrangement, then 动态 last, - * objectstack#34590), each with its count. A tab is its panel's whole face (Target 9): choosing it draws - * that face below the row, and 「概览」 returns to the page. + * (objectstack#35595: every related list, then 附件, 审批 and 动态 last), each + * with its count. A tab is its panel's whole face (Target 9): choosing it + * draws that face below the row, and 「概览」 returns to the page. * * How many tabs the row shows is computed from its own width, measured on * every resize (a window resize, the sidebar collapsing, a pane dragged - * wider): as many as fit, the rest in a 「+N ▾」 dropdown that lists them with - * their counts, then the empty lists' tabs (objectstack#28469), then the - * hidden panels' tabs at its end. The active tab is always on the row, and so - * are 「概览」 and at least one more ({@link layoutRecordTabRow}, - * {@link arrangeRecordTabRow}). + * wider): as many as fit, the rest in a 「更多 N ▾」 dropdown that lists them + * with their counts, then the hidden panels' tabs at its end. Width is the + * only fold: a list with no records keeps its place, muted and without a + * number (objectstack#35595, superseding objectstack#28469). The active tab is + * always on the row, and so are 「概览」 and at least one more + * ({@link layoutRecordTabRow}). * * Keyboard: the row is one tab stop; ← → Home End move between its tabs, and * Enter or Space opens the focused one. */ export const RecordTabRow: React.FC = ({ - tabs: candidates, - emptyTabs: allEmpty = [], + tabs, hiddenTabs = [], activeId, onSelect, }) => { const { t } = useDetailTranslation(); - // The row's candidates: the given tabs, plus an empty list's tab while it is active. - const { row: tabs, empty: emptyTabs } = arrangeRecordTabRow(candidates, allEmpty, activeId); const rowRef = React.useRef(null); const measureRef = React.useRef(null); const [measure, setMeasure] = React.useState<{ widths: number[]; more: number; available: number } | null>(null); // What the tabs draw, as a value: re-measure when a label or a count moves. const facesKey = JSON.stringify([ - tabs.map((tab) => [tab.id, tab.label, tab.count ?? null]), - emptyTabs.length + hiddenTabs.length, + tabs.map((tab) => [tab.id, tab.label, tab.count ?? null, tab.dot === true]), + hiddenTabs.length, ]); useIsomorphicLayoutEffect(() => { const row = rowRef.current; @@ -156,14 +172,14 @@ export const RecordTabRow: React.FC = ({ gap: TAB_GAP, moreWidth: measure.more, activeIndex, - alwaysInDropdown: emptyTabs.length + hiddenTabs.length, + alwaysInDropdown: hiddenTabs.length, }) : { shown: tabs.map((_, index) => index), overflow: [] as number[] }; // An id naming no tab leaves 「概览」 active. const activeTabId = tabs[activeIndex]?.id; const shown = layout.shown.map((index) => tabs[index]); const overflow = layout.overflow.map((index) => tabs[index]); - const moreCount = overflow.length + emptyTabs.length + hiddenTabs.length; + const moreCount = overflow.length + hiddenTabs.length; const tabRefs = React.useRef(new Map()); const onKeyDown = (event: React.KeyboardEvent) => { @@ -181,6 +197,8 @@ export const RecordTabRow: React.FC = ({ }; const tabsLabel = t('detail.recordTabs', { defaultValue: 'Record tabs' }); + // objectstack#35595 — the trigger reads 「更多 N」, the one fold of the row. + const moreLabel = (count: number) => t('detail.recordTabsMoreTrigger', { count, defaultValue: 'More {{count}}' }); return (
    = ({ : 'border-transparent text-muted-foreground hover:text-foreground', )} data-record-tab={tab.id} + data-record-tab-empty={isEmptyRecordTab(tab) ? '' : undefined} onClick={() => { if (!active) onSelect(tab.id); }} @@ -231,7 +250,7 @@ export const RecordTabRow: React.FC = ({ aria-label={t('detail.recordTabsMore', { count: moreCount, defaultValue: '{{count}} more tabs' })} data-record-tab-more={moreCount} > - +{moreCount} + {moreLabel(moreCount)} @@ -241,30 +260,15 @@ export const RecordTabRow: React.FC = ({ key={tab.id} className="justify-between gap-3" data-record-tab-menu-item={tab.id} + data-record-tab-empty={isEmptyRecordTab(tab) ? '' : undefined} onSelect={() => onSelect(tab.id)} > ))} - {emptyTabs.length > 0 && ( - <> - {overflow.length > 0 && } - {emptyTabs.map((tab) => ( - onSelect(tab.id)} - > - - - ))} - - )} {hiddenTabs.length > 0 && ( <> - {overflow.length + emptyTabs.length > 0 && } + {overflow.length > 0 && } {t('detail.recordTabsHidden', { defaultValue: 'Hidden' })} @@ -274,6 +278,7 @@ export const RecordTabRow: React.FC = ({ className="justify-between gap-3 text-muted-foreground" data-record-tab-menu-item={tab.id} data-record-tab-hidden="" + data-record-tab-empty={isEmptyRecordTab(tab) ? '' : undefined} onSelect={() => onSelect(tab.id)} > @@ -294,7 +299,7 @@ export const RecordTabRow: React.FC = ({ ))} - +{tabs.length + emptyTabs.length + hiddenTabs.length} + {moreLabel(tabs.length + hiddenTabs.length)}
    diff --git a/ui/packages/plugin-detail/src/__tests__/DetailView.approvalBandOnce-35484.test.tsx b/ui/packages/plugin-detail/src/__tests__/DetailView.approvalBandOnce-35484.test.tsx new file mode 100644 index 00000000000..6911bcbcb1c --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/DetailView.approvalBandOnce-35484.test.tsx @@ -0,0 +1,99 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35484 / objectstack#35483 — a record page drawn as written (an + * authored page with two `record:details` nodes, or a synthesized page that + * falls back to its `page:tabs` strip) draws the approval band ONCE, as the + * laid-out page does since objectstack#35253. The host wraps such a page in + * `ApprovalBandOnceScope`; the first details body that reaches the band's + * place draws it. The lock rule is untouched: a `lockRecord: false` approval + * still reads editable, and a first node that draws no band leaves the band + * to the next. Measured on the body the `record:details` block mounts + * (`showHeader: false`, inline edit on); the host wiring is pinned in + * `app-shell/src/views/RecordDetailView.approvalBandOnce-35484.test.tsx`. + */ + +import * as React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, cleanup } from '@testing-library/react'; +import { InlineEditProvider } from '@object-ui/react'; +import { DetailView } from '../DetailView'; +import { ApprovalBandOnceScope } from '../defaultRecordPage'; + +afterEach(cleanup); + +const Body = ({ id, showHeader = false }: { id: string; showHeader?: boolean }) => ( +
    + +
    +); + +const page = (approval: { locked?: boolean; approvalPending?: boolean; canEdit?: boolean }, bodies: React.ReactNode, scoped = true) => + render( + + {scoped ? {bodies} : bodies} + , + ); + +const chipsIn = (container: HTMLElement, text: string) => + Array.from(container.querySelectorAll('[data-body]')).filter((body) => body.textContent?.includes(text)).map((b) => b.getAttribute('data-body')); + +describe('one approval band on a page drawn as written (objectstack#35484, objectstack#35483)', () => { + it('two details nodes, a locked record: "Locked for approval" once, on the first node', () => { + const { container } = page({ locked: true }, <>); + expect(screen.getAllByText('Locked for approval')).toHaveLength(1); + expect(chipsIn(container, 'Locked for approval')).toEqual(['a']); + }); + + it('CONTROL: the same two nodes outside the scope draw it twice (the defect)', () => { + page({ locked: true }, <>, false); + expect(screen.getAllByText('Locked for approval')).toHaveLength(2); + }); + + it('CONTROL: one details node under the scope still draws its one band', () => { + page({ locked: true }, ); + expect(screen.getAllByText('Locked for approval')).toHaveLength(1); + }); + + it('a `lockRecord: false` approval reads editable, once — never locked', () => { + page({ approvalPending: true, locked: false, canEdit: true }, <>); + expect(screen.queryByText('Locked for approval')).toBeNull(); + expect(screen.getAllByText('In approval · editable')).toHaveLength(1); + }); + + it('a first node that draws no band leaves the band to the next node', () => { + const { container } = page({ locked: true }, <>); + expect(chipsIn(container, 'Locked for approval')).toEqual(['b']); + }); + + it('when the first node leaves, the next one takes the band', () => { + const { container, rerender } = page({ locked: true }, <>); + expect(chipsIn(container, 'Locked for approval')).toEqual(['a']); + rerender( + + + + + , + ); + // A fresh scope mounts here (the provider tree changed shape), so the + // remaining node is the first. + expect(chipsIn(container, 'Locked for approval')).toEqual(['b']); + }); + + it('CONTROL: no approval running draws no band and no stray mark text', () => { + const { container } = page({}, <>); + expect(screen.queryByText('Locked for approval')).toBeNull(); + expect(container.querySelectorAll('[data-approval-band-mark]').length).toBe(2); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx new file mode 100644 index 00000000000..5b2b10024f7 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.readerArrangement-35595.test.tsx @@ -0,0 +1,186 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35595 — the reader's arrangement of the related lists + * (objectstack#27055, Targets 7 and 10; objectstack#27241) through + * `RecordPageColumns`, now that every related list is a TAB and the right + * column is the 概览 tab's summary rail (objectstack#35596). The stored order + * orders the tab row; a hidden list's tab waits at the end of 「更多 N ▾」; + * the rail's foot keeps 「已隐藏 N 个 · 显示」, 「恢复默认顺序」 and the + * changed-default hint. The card stack's ⠿ handle, ⌥↑ / ⌥↓, 隐藏 and the + * 「新」 badge were the related cards' chrome and leave the page with them + * (`RelatedCardStack`, no longer drawn by the page). This file carries over + * `RelatedCardStack-27055.test.tsx`; the merge rules themselves stay pinned in + * `synth/__tests__/relatedArrangement-27055.test.ts`. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, fireEvent } from '@testing-library/react'; +import { RelatedListCompactContext, RelatedListEnlargedContext } from '../relatedListCompact'; + +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + SchemaRenderer: ({ schema }: { schema: any }) => , +})); + +function StubNode({ schema }: { schema: any }) { + const compact = React.useContext(RelatedListCompactContext); + const enlarged = React.useContext(RelatedListEnlargedContext); + const p = schema?.properties ?? {}; + return ( +
    + {p.objectName ?? schema?.type} +
    + ); +} + +import { RecordPageColumns } from '../RecordPageColumns'; +import { buildDefaultPageColumns } from '../synth/recordPageColumns'; +import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; +import { editRelatedArrangement, type RelatedArrangement } from '../synth/relatedArrangement'; + +const RELATED = [ + { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, + { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, + { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, +]; +const DEFAULT = ['task.lead_id', 'note.parent_id', 'call.lead_id']; +const columnsOf = (related = RELATED) => + buildDefaultPageColumns(buildDefaultPageSchema({ name: 'lead', fields: {} }, { related, hideDiscussion: true }))!; + +/** The related lists' tabs on the row, in order. */ +const listTabs = () => + Array.from(document.querySelectorAll('[role="tab"][data-record-tab]')) + .map((el) => el.getAttribute('data-record-tab')) + .filter((id) => id !== 'overview'); + +/** A host with a real store: the arrangement round-trips through state. */ +function Host({ initial, onWrite, related }: { initial?: RelatedArrangement; onWrite?: (v: RelatedArrangement) => void; related?: typeof RELATED }) { + const [arrangement, setArrangement] = React.useState(initial); + return ( + { + onWrite?.(next); + setArrangement(next); + }} + onEnlargeRelated={vi.fn()} + /> + ); +} + +afterEach(cleanup); + +describe('the reader\'s arrangement orders the tab row (objectstack#35595, carrying objectstack#27055 / objectstack#27241)', () => { + it('draws the default order for a reader who never chose, with no foot line', () => { + const { container } = render(); + expect(listTabs()).toEqual(DEFAULT); + expect(container.querySelector('[data-related-foot-line]')).toBeNull(); + }); + + it("draws the stored reader's order, and 「恢复默认顺序」 at the rail's foot restores the default", () => { + const onWrite = vi.fn(); + const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); + const { container } = render(); + expect(listTabs()).toEqual(['call.lead_id', 'task.lead_id', 'note.parent_id']); + const foot = container.querySelector('[data-record-column="right"] [data-related-foot-line]')!; + expect(foot).not.toBeNull(); + const restore = foot.querySelector('[data-related-restore-default-order]') as HTMLButtonElement; + expect(restore.textContent).toBe('Restore default order'); + fireEvent.click(restore); + expect(listTabs()).toEqual(DEFAULT); + expect(onWrite.mock.calls.at(-1)![0].order).toEqual([]); + expect(container.querySelector('[data-related-foot-line]')).toBeNull(); + }); + + it('a hidden list leaves the row for the end of 「更多 N ▾」; the foot line brings it back', () => { + const hidden = editRelatedArrangement(DEFAULT, undefined, { kind: 'hide', id: 'task.lead_id' }, Date.now()); + const { container } = render(); + expect(listTabs()).toEqual(['note.parent_id', 'call.lead_id']); + expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); + const line = container.querySelector('[data-related-hidden-line]')!; + expect(line).toBeTruthy(); + fireEvent.click(line.querySelector('button')!); + expect(listTabs()).toEqual(DEFAULT); + expect(container.querySelector('[data-related-hidden-line]')).toBeNull(); + expect(document.querySelector('[data-record-tab-more]')).toBeNull(); + }); + + it('says when the default changed under a dragged order, and restores it', () => { + const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); + const reordered = [RELATED[1], RELATED[0], RELATED[2]]; + const { container } = render(); + expect(listTabs()).toEqual(['call.lead_id', 'task.lead_id', 'note.parent_id']); + const hint = container.querySelector('[data-related-default-changed]')!; + expect(hint).toBeTruthy(); + fireEvent.click(hint.querySelector('button')!); + expect(listTabs()).toEqual(['note.parent_id', 'task.lead_id', 'call.lead_id']); + expect(container.querySelector('[data-related-default-changed]')).toBeNull(); + }); + + it('CONTROL: the rail draws no card chrome — no ⠿ handle, no 隐藏, no related list drawn whole', () => { + const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); + const { container } = render(); + const rail = container.querySelector('[data-record-column="right"]')!; + expect(rail).not.toBeNull(); + expect(rail.querySelector('[data-related-card-id]')).toBeNull(); + expect(rail.querySelector('[data-node="record:related_list"]')).toBeNull(); + }); +}); + +describe('a related list\'s tab — ?related= (objectstack#27055, Target 9; objectstack#35595)', () => { + it('a list\'s tab asks the host to open that relationship', () => { + const onEnlarge = vi.fn(); + render(); + fireEvent.click(document.querySelector('[data-record-tab="note.parent_id"]')!); + expect(onEnlarge).toHaveBeenCalledWith('note.parent_id'); + }); + + it('draws the full list over the page body: the header stays, the columns step aside', () => { + const { container } = render( + , + ); + const enlarged = container.querySelector('[data-related-enlarged="note.parent_id"]')!; + expect(enlarged).toBeTruthy(); + expect(container.querySelector('[data-record-columns]')).toBeNull(); + // The FULL face, not a compact card — and paged. + const list = enlarged.querySelector('[data-node="record:related_list"]')!; + expect(list.getAttribute('data-compact')).toBe('no'); + expect(list.getAttribute('data-enlarged')).toBe('yes'); + expect(list.getAttribute('data-limit')).toBe('25'); + expect(container.querySelector('[data-node="page:header"]')).not.toBeNull(); + }); + + it('「概览」 and Esc return to the columns (objectstack#27524, Target 9)', () => { + const onClose = vi.fn(); + const { container } = render( + , + ); + fireEvent.click(container.querySelector('[data-record-tab="overview"]')!); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(onClose).toHaveBeenCalledTimes(2); + }); + + it('an id naming no related list draws the columns', () => { + const { container } = render( + , + ); + expect(container.querySelector('[data-related-enlarged]')).toBeNull(); + expect(container.querySelector('[data-record-columns]')).not.toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx index dbddf2cb245..f36ff8b7cb3 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.switches-27052.test.tsx @@ -9,9 +9,9 @@ /** * objectstack#27052 → objectstack#27524, Target 4 — `RecordPageColumns` with * the reader's ONE switch, ⊟ (the right column). The timeline switch, its - * folded 「动态」 card and the related rail retired: 动态 is a panel of the right - * column (its last since objectstack#34590), so ⊟ takes the 动态 panel and the - * related panels out together, and the details take the row. The stack has no right column, so + * folded 「动态」 card and the related rail retired. Since objectstack#35596 the + * right column is the 概览 tab's summary rail (审批, 附件, 最近动态, 其他相关), + * so ⊟ takes the whole rail out, and the details take the row. The stack has no right column, so * the switch does not reach it. The blocks are stubbed (each node draws its * type), so what is measured is where each node lands. */ @@ -52,12 +52,13 @@ const shown = (container: HTMLElement) => afterEach(() => cleanup()); describe('RecordPageColumns — the right-column switch ⊟ (objectstack#27052, objectstack#27524)', () => { - it('absent or on: details | right column, 动态 last (objectstack#34590)', () => { + it('absent or on: details | the rail (objectstack#35596)', () => { for (const rightColumn of [undefined, true]) { const { container, unmount } = render(); expect(shown(container)).toBe('details right'); - // objectstack#34590 — 动态 last (supersedes objectstack#27524 Targets 5 and 8 for the column). - expect(nodesIn(column(container, 'right'))).toEqual(['record:related_list', 'record:related_list', 'record:activity']); + // The rail: no list drawn whole; the 最近动态 card mounted (hidden until the stream reports entries). + expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); + expect(column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')).not.toBeNull(); unmount(); } }); @@ -70,6 +71,7 @@ describe('RecordPageColumns — the right-column switch ⊟ (objectstack#27052, expect(shown(container)).toBe('details'); expect(column(container, 'right')).toBeNull(); expect(container.querySelector('[data-record-timeline-panel]')).toBeNull(); + expect(container.querySelector('[data-record-summary-card]')).toBeNull(); expect(container.querySelectorAll('[data-node="record:related_list"]')).toHaveLength(0); expect(container.querySelector('[data-testid="record-related-rail-toggle"]')).toBeNull(); expect(container.querySelector('[data-record-folded-timeline]')).toBeNull(); @@ -77,10 +79,10 @@ describe('RecordPageColumns — the right-column switch ⊟ (objectstack#27052, }); } - it('the stack does not read it: its panels follow the details whatever the switch says', () => { + it('the stack does not read it: its rail follows the details whatever the switch says', () => { const { container } = render(); expect(shown(container)).toBe('details'); - // objectstack#34590 — the stack ends with 动态 (supersedes objectstack#27524 Targets 5 and 8 for the stack). - expect(nodesIn(column(container, 'right'))).toEqual(['record:related_list', 'record:related_list', 'record:activity']); + expect(column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')).not.toBeNull(); + expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); }); }); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx index e0ef07b7a76..67e0f508189 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.tabRow-27524.test.tsx @@ -8,9 +8,10 @@ /** * objectstack#27524, Targets 8 and 9 — the record page's tab row, through - * `RecordPageColumns`: 「概览」, then the related panels in the reader's - * arrangement with their counts, then 动态 last (objectstack#34590), the hidden - * panels' tabs at the end of the dropdown; and the enlarged state as the active tab — the header and + * `RecordPageColumns`: 「概览」, then EVERY related list in the reader's + * arrangement with its count (objectstack#35595: an empty one keeps its place, + * muted), then 动态 last (objectstack#34590), the hidden lists' tabs at the end + * of the dropdown; and the enlarged state as the active tab — the header and * the row stay as they are, the full face is drawn below the row, 「概览」 * returns. The block renderer is stubbed, so what is measured is the page's * own composition; the row's width rule is pinned in `RecordTabRow-27524`. @@ -103,11 +104,12 @@ describe('the record page tab row (objectstack#27524, Target 8)', () => { ); // objectstack#34590 supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」 expect(tabIds()).toEqual(['overview', 'task.lead_id', 'call.lead_id', RECORD_PAGE_TIMELINE_PANEL]); - expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('+1'); + // objectstack#35595 — the dropdown is 「更多 N ▾」. + expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); }); it('each panel tab carries its count — the hidden ones counted too — and 动态 the stream\'s size', async () => { - const find = vi.fn(async (objectName: string) => ({ data: [{ id: 'x' }], total: objectName === 'task' ? 2 : objectName === 'note' ? 0 : 5 })); + const find = vi.fn(async (objectName: string, _query?: Record) => ({ data: [{ id: 'x' }], total: objectName === 'task' ? 2 : objectName === 'note' ? 0 : 5 })); const dataSource = { find, getObjectSchema: vi.fn(async () => ({ fields: {} })) }; const stored = editRelatedArrangement(DEFAULT, undefined, { kind: 'hide', id: 'call.lead_id' }, Date.now()); render( @@ -123,14 +125,19 @@ describe('the record page tab row (objectstack#27524, Target 8)', () => {
    , ); await waitFor(() => expect(tabCount('task.lead_id')).toBe('2')); - // The empty list's tab waits in the dropdown (objectstack#28469), beside the hidden one. - expect(tabIds()).not.toContain('note.parent_id'); - expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('+2'); - expect(tabCount(RECORD_PAGE_TIMELINE_PANEL)).toBe('7'); - // The hidden panel was asked as well: its tab sits in the dropdown with its count. - expect(find.mock.calls.map((call) => call[0]).sort()).toEqual(['call', 'note', 'task']); - // One count set feeds the tabs and the panels: no relationship is read twice. - expect(find).toHaveBeenCalledTimes(3); + // objectstack#35595 (superseding objectstack#28469) — the empty list's tab + // keeps its place on the row, muted, with no number; only the hidden one + // waits in the dropdown. + expect(tabIds()).toEqual(['overview', 'task.lead_id', 'note.parent_id', RECORD_PAGE_TIMELINE_PANEL]); + expect(tabCount('note.parent_id')).toBeNull(); + expect(document.querySelector('[data-record-tab="note.parent_id"]')?.hasAttribute('data-record-tab-empty')).toBe(true); + expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('More 1'); + await waitFor(() => expect(tabCount(RECORD_PAGE_TIMELINE_PANEL)).toBe('7')); + // The hidden list was counted as well: its tab sits in the dropdown with its count. + const counted = find.mock.calls.filter((call) => call[1]?.$count === true); + expect(counted.map((call) => call[0]).sort()).toEqual(['call', 'note', 'task']); + // One count set feeds the tabs and the rail: no relationship is counted twice. + expect(counted).toHaveLength(3); }); it('a tab opens its panel\'s face; 概览 closes it', () => { diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx index 9a886a4360a..cbb0ea41891 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx @@ -11,9 +11,9 @@ * synthesized record page laid out by one rule. The blocks themselves are * stubbed (each node draws its type, and reports the details column cap it * is drawn under), so what is measured here is the layout alone: where each - * node lands, that the header is drawn once, that no tab strip and no rail - * exist, the 动态 panel closing the right column (objectstack#34590), and each - * tier's measures. + * node lands, that the header is drawn once, the 概览 tab's rail in the right + * column and its order (objectstack#35596, re-setting objectstack#34590), and + * each tier's measures. * * One describe (objectstack#35253) opts each `record:details` stub into * mounting the `DetailView` the real block mounts (`showHeader: false`, @@ -23,18 +23,29 @@ import * as React from 'react'; import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; -import { render, screen, cleanup, within } from '@testing-library/react'; +import { render, screen, cleanup, within, waitFor, fireEvent } from '@testing-library/react'; +import { RelatedCountStore } from '@object-ui/components'; +import { RecordContextProvider } from '@object-ui/react'; const harness = vi.hoisted(() => ({ /** Set by the objectstack#35253 describe: a `record:details` stub mounts `body`. */ detailBodies: false, body: null as React.ComponentType | null, + /** Set by the objectstack#35596 describe: the size a stream block reports. */ + timelineCount: undefined as number | undefined, })); vi.mock('@object-ui/react', async (importOriginal) => { const { DetailsColumnCapContext } = await import('../defaultRecordPage'); + const { RecordTimelinePanelContext } = await import('../recordTimelineStream'); const Stub = ({ schema }: { schema: any }) => { const Body = harness.detailBodies && schema?.type === 'record:details' ? harness.body : null; + // objectstack#35596 — a stream block in the rail's 最近动态 card reports + // the stream's size, as the real one does. + const panel = React.useContext(RecordTimelinePanelContext); + React.useEffect(() => { + if (schema?.type === 'record:activity' && panel && harness.timelineCount !== undefined) panel.onCount(harness.timelineCount); + }, [panel, schema?.type]); return (
    {schema?.properties?.objectName ?? schema?.type} @@ -51,7 +62,6 @@ vi.mock('@object-ui/react', async (importOriginal) => { import { RecordPageColumns } from '../RecordPageColumns'; import { buildDefaultPageColumns } from '../synth/recordPageColumns'; import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; -import { relatedDefaultOrderHash } from '../synth/relatedArrangement'; import { DetailView } from '../DetailView'; import { InlineEditProvider } from '@object-ui/react'; @@ -75,7 +85,7 @@ const grid = (container: HTMLElement) => container.querySelector('[data-record-c afterEach(() => cleanup()); describe('RecordPageColumns — details | the right column (objectstack#27524, Target 6)', () => { - it('wide (≥ 1120): one header, details | right column at 380 px, 动态 last (objectstack#34590), no tab strip', () => { + it('wide (≥ 1120): one header, details | right column at 380 px holding the rail, no tab strip without a host', () => { const { container } = render( meta

    } />, ); @@ -85,30 +95,29 @@ describe('RecordPageColumns — details | the right column (objectstack#27524, T expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); expect(grid(container).className).toContain('grid-cols-[minmax(0,1fr)_23.75rem]'); expect(nodesIn(column(container, 'details'))).toEqual(['record:details']); - // objectstack#34590 — the related panels lead the right column; the 动态 - // panel closes it (supersedes objectstack#27524 Targets 5 and 8's - // 动态-first for the column). + // objectstack#35596 — the right column is the 概览 tab's rail: summary + // cards, never a related list drawn whole (the lists are tabs, + // objectstack#35595). With no counts read, only the 最近动态 card is + // mounted, hidden until the stream reports entries. const right = column(container, 'right')!; - expect(right.lastElementChild?.hasAttribute('data-record-timeline-panel')).toBe(true); - expect(nodesIn(right)).toEqual(['record:related_list', 'record:related_list', 'record:activity']); + expect(right.querySelector('[data-node="record:related_list"]')).toBeNull(); + expect(nodesIn(right)).toEqual(['record:activity']); + expect((right.querySelector('[data-record-summary-card="timeline"]') as HTMLElement).hidden).toBe(true); // No timeline column exists any more (「动态是面板,不是栏」). expect(column(container, 'timeline')).toBeNull(); // The meta line closes the details column (objectstack#27055). expect(within(right).queryByTestId('meta-footer')).toBeNull(); expect(column(container, 'details')!.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - // The related lists are siblings of one parent, so they form one empty-fold stack. - const lists = right.querySelectorAll('[data-node="record:related_list"]'); - expect(lists[0].parentElement).toBe(lists[1].parentElement); // Wide: a details section may take three field columns. expect(column(container, 'details')!.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('3'); }); - it('two-column (760 – 1119): the right column at 320 px, its lists resident — no rail, no toggle', () => { + it('two-column (760 – 1119): the right column at 320 px holding the rail — no toggle', () => { const { container } = render(); expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); expect(grid(container).className).toContain('grid-cols-[minmax(0,1fr)_20rem]'); - // objectstack#34590 — 动态 last (supersedes objectstack#27524 Targets 5 and 8 for the column). - expect(nodesIn(column(container, 'right'))).toEqual(['record:related_list', 'record:related_list', 'record:activity']); + // objectstack#35596 — the rail's cards, not the lists themselves. + expect(nodesIn(column(container, 'right'))).toEqual(['record:activity']); expect(screen.queryByRole('button', { name: /Related/ })).toBeNull(); expect(container.querySelector('[data-testid="record-related-rail-toggle"]')).toBeNull(); // Beside the 320 px column a details section takes two field columns at most. @@ -128,7 +137,7 @@ describe('RecordPageColumns — details | the right column (objectstack#27524, T }); describe('RecordPageColumns — the stack (< 760, objectstack#27524, Target 6)', () => { - it('ONE column: the details and their footer, then the right column’s panels in their order — no tabs', () => { + it('ONE column: the details and their footer, then the rail — no tabs without a host', () => { const { container } = render( meta

    } />, ); @@ -141,28 +150,41 @@ describe('RecordPageColumns — the stack (< 760, objectstack#27524, Target 6)', expect(details.getAttribute('data-record-column')).toBe('details'); expect(right.getAttribute('data-record-column')).toBe('right'); expect(details.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); - // objectstack#34590 — 动态 is the right column's LAST panel (supersedes - // objectstack#27524 Targets 5 and 8's 动态-first for the column). - expect(nodesIn(right)).toEqual(['record:related_list', 'record:related_list', 'record:activity']); + // objectstack#35596 — the rail's cards, under the details. + expect(nodesIn(right)).toEqual(['record:activity']); // The stack's details are the whole width: the section's own container decides. expect(details.querySelector('[data-node="record:details"]')!.getAttribute('data-cap')).toBe('3'); }); }); /** - * objectstack#34590 (item 1) — on the default record page 动态 comes LAST: - * the right column reads related → attachments → (approvals) → 动态, and the - * stack reads details → related → attachments → (approvals) → 动态, so at a - * phone's width the stream sits at the very bottom of the page. The - * maintainer's words 「我们同事反馈动态不常用,是否建议移动到子表最后」「「动态」在最后」 - * supersede objectstack#27524 Targets 5 and 8's 动态-first for the column and - * the stack. The tab row's order is not this card's and is not pinned here. + * objectstack#35596 — the 概览 tab's right rail summarizes the other tabs, in + * a fixed order: 审批, 附件, 最近动态, then 「其他相关」 (one card per related + * list that has records). This re-sets objectstack#34590's column order (the + * related panels, then 动态 last): the related lists are tabs now + * (objectstack#35595), and the rail draws a card only for a tab that has + * something to show. The stack draws the same rail under the details. */ -describe('RecordPageColumns — 动态 last in the right column and the stack (objectstack#34590)', () => { +describe('RecordPageColumns — the rail: 审批, 附件, 最近动态, 其他相关 (objectstack#35596, re-setting objectstack#34590)', () => { + beforeEach(() => { + RelatedCountStore._reset(); + harness.timelineCount = 4; + }); + afterEach(() => { + harness.timelineCount = undefined; + }); const relatedLists = [ { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, + { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, ]; + const PENDING = { + approvals: { + available: true, + requests: [{ id: 'req_1' }], + pendingRequest: { id: 'req_1', step_label: 'Manager review', pending_approvers: ['u2'], pending_approver_names: { u2: 'Wang' } }, + }, + }; const synth = (opts: { files: boolean; approvals: boolean }) => buildDefaultPageColumns( buildDefaultPageSchema( @@ -172,17 +194,32 @@ describe('RecordPageColumns — 动态 last in the right column and the stack (o fields: { name: { name: 'name', type: 'text' } }, ...(opts.files ? { enable: { files: true } } : {}), }, - { related: relatedLists, ...(opts.approvals ? { approvals: { count: 1 } } : {}) }, + { related: relatedLists, ...(opts.approvals ? { approvals: { count: 1, node: PENDING } } : {}) }, ), )!; - /** The right column's blocks in document order, the panel's own node for 动态. */ - const expected = (opts: { files: boolean; approvals: boolean }) => [ - 'record:related_list', - 'record:related_list', - ...(opts.files ? ['record:attachments'] : []), - ...(opts.approvals ? ['record:approvals'] : []), - 'record:activity', - ]; + /** task 0 and call 0 are empty; note has 2; the record holds 5 files. */ + const TOTALS: Record = { task: 0, note: 2, call: 0, sys_attachment: 5 }; + const find = vi.fn(async (objectName: string) => ({ + data: TOTALS[objectName] ? [{ id: `${objectName}-1`, name: `${objectName} one` }] : [], + total: TOTALS[objectName] ?? 0, + })); + // A record of its own per draw: the count hook keeps a parent's first set. + let draws = 0; + const drawPage = (tier: 'wide' | 'two-column' | 'stack', cols: ReturnType, extra: Record = {}) => + render( + ({ fields: {} })) } as any} + > + meta

    } {...extra} /> +
    , + ); + /** The rail's cards as drawn (a `hidden` card is not drawn), in document order. */ + const cards = (container: HTMLElement) => + Array.from(column(container, 'right')?.querySelectorAll('[data-record-summary-card]') ?? []) + .filter((el) => !(el as HTMLElement).hidden) + .map((el) => el.getAttribute('data-record-summary-card')); const cases = [ { files: false, approvals: false }, @@ -192,23 +229,25 @@ describe('RecordPageColumns — 动态 last in the right column and the stack (o ]; for (const tier of ['wide', 'two-column', 'stack'] as const) { for (const opts of cases) { - it(`${tier}, attachments ${opts.files ? 'on' : 'off'}, approvals ${opts.approvals ? 'on' : 'off'}: 动态 closes the column`, () => { - const { container } = render( - meta

    } />, - ); - const right = column(container, 'right')!; - expect(nodesIn(right)).toEqual(expected(opts)); - // The 动态 panel is the column's last element: nothing of the related - // stack (its fold or foot lines) is drawn after it. - expect(right.lastElementChild?.hasAttribute('data-record-timeline-panel')).toBe(true); - expect(right.querySelectorAll('[data-record-timeline-panel]')).toHaveLength(1); + it(`${tier}, attachments ${opts.files ? 'on' : 'off'}, approvals ${opts.approvals ? 'on' : 'off'}: the rail's order`, async () => { + const { container } = drawPage(tier, synth(opts)); + const expected = [ + ...(opts.approvals ? ['approvals'] : []), + ...(opts.files ? ['attachments'] : []), + 'timeline', + 'note.parent_id', + ]; + await waitFor(() => expect(cards(container)).toEqual(expected)); + // 「其他相关」 heads the related cards, after 最近动态. + const other = column(container, 'right')!.querySelector('[data-record-summary-other]')!; + const timeline = column(container, 'right')!.querySelector('[data-record-summary-card="timeline"]')!; + expect(timeline.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // No related list is drawn whole in the rail: the lists are tabs. + expect(column(container, 'right')!.querySelector('[data-node="record:related_list"]')).toBeNull(); if (tier === 'stack') { - // One flow: the details (their footer closing them), then the panels, - // so 动态 is the page's last block. - const [details, panels] = Array.from(grid(container).children) as HTMLElement[]; + const [details, rail] = Array.from(grid(container).children) as HTMLElement[]; expect(details.getAttribute('data-record-column')).toBe('details'); - expect(panels).toBe(right); - expect(grid(container).lastElementChild).toBe(right); + expect(rail.getAttribute('data-record-column')).toBe('right'); expect(details.lastElementChild?.getAttribute('data-testid')).toBe('meta-footer'); } else { expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details right'); @@ -217,35 +256,113 @@ describe('RecordPageColumns — 动态 last in the right column and the stack (o } } - it('a reader-rearranged related stack still ends before 动态: its foot line, then the 动态 panel', () => { - const order = ['note.parent_id', 'task.lead_id']; - const { container } = render( - {}} - />, - ); - const right = column(container, 'right')!; - const lists = Array.from(right.querySelectorAll('[data-node="record:related_list"]')).map((n) => n.textContent); - expect(lists).toEqual(['note', 'task']); - expect(nodesIn(right)).toEqual(['record:related_list', 'record:related_list', 'record:attachments', 'record:activity']); - const foot = right.querySelector('[data-related-foot-line]'); - expect(foot).not.toBeNull(); - const panel = right.lastElementChild!; - expect(panel.hasAttribute('data-record-timeline-panel')).toBe(true); - expect(foot!.compareDocumentPosition(panel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + it('an empty card is absent, and nothing stands in for the empty lists (no 「还有 N 个空关联」)', async () => { + const { container } = drawPage('wide', synth({ files: false, approvals: false })); + await waitFor(() => expect(cards(container)).toContain('note.parent_id')); + expect(cards(container)).not.toContain('task.lead_id'); + expect(cards(container)).not.toContain('call.lead_id'); + expect(container.querySelector('[data-related-empty-fold]')).toBeNull(); + expect(container.textContent).not.toMatch(/还有\s*\d+\s*个空关联|more empty/i); + }); + + it('CONTROL: a stream with no entries draws no 最近动态 card; the same page with entries does', async () => { + harness.timelineCount = 0; + const { container, unmount } = drawPage('wide', synth({ files: false, approvals: false })); + await waitFor(() => expect(cards(container)).toEqual(['note.parent_id'])); + unmount(); + harness.timelineCount = 4; + RelatedCountStore._reset(); + const again = drawPage('wide', synth({ files: false, approvals: false })); + await waitFor(() => expect(cards(again.container)).toEqual(['timeline', 'note.parent_id'])); + }); + + it('a card shows at most three rows, a grey count after its 13 px title, rows 26 px high, radius 8', async () => { + TOTALS.note = 9; + find.mockImplementation(async (objectName: string) => ({ + data: Array.from({ length: Math.min(TOTALS[objectName] ?? 0, 5) }, (_, i) => ({ id: `${objectName}-${i}`, name: `${objectName} ${i}` })), + total: TOTALS[objectName] ?? 0, + })); + try { + const { container } = drawPage('wide', synth({ files: false, approvals: false })); + const card = () => container.querySelector('[data-record-summary-card="note.parent_id"]') as HTMLElement | null; + await waitFor(() => expect(card()?.querySelectorAll('[data-record-summary-row]').length).toBe(3)); + expect(card()!.className).toContain('rounded-[8px]'); + const title = card()!.querySelector('[data-record-summary-card-title]')!; + expect(title.className).toContain('text-[13px]'); + const count = title.querySelector('[data-record-summary-card-count]')!; + expect(count.textContent).toBe('9'); + expect(count.className).toContain('text-muted-foreground'); + expect(card()!.querySelector('[data-record-summary-row]')!.className).toContain('h-[26px]'); + } finally { + TOTALS.note = 2; + find.mockImplementation(async (objectName: string) => ({ + data: TOTALS[objectName] ? [{ id: `${objectName}-1`, name: `${objectName} one` }] : [], + total: TOTALS[objectName] ?? 0, + })); + } + }); + + it('the whole title opens its tab', async () => { + const onEnlargeRelated = vi.fn(); + const { container } = drawPage('wide', synth({ files: true, approvals: true }), { onEnlargeRelated }); + await waitFor(() => expect(cards(container)).toEqual(['approvals', 'attachments', 'timeline', 'note.parent_id'])); + for (const id of ['approvals', 'attachments', 'timeline', 'note.parent_id']) { + fireEvent.click(container.querySelector(`[data-record-summary-card="${id}"] [data-record-summary-card-title]`)!); + expect(onEnlargeRelated).toHaveBeenLastCalledWith(id); + } }); - it('a page whose stream is off draws its related panels alone — no 动态 panel', () => { - const bare = buildDefaultPageColumns( - buildDefaultPageSchema({ name: 'lead', fields: {} }, { related: relatedLists, hideDiscussion: true }), + it('the rail is the 概览 tab\'s: another tab open draws none, and the strip leaves with it', async () => { + const cols = buildDefaultPageColumns( + buildDefaultPageSchema( + { name: 'lead', fields: { name: { type: 'text' }, email: { type: 'email' }, rating: { type: 'select' } } } as any, + { + related: relatedLists, + highlightFields: ['email'], + statusField: 'rating', + stages: [{ value: 'hot', label: 'Hot' }], + }, + ), )!; - const { container } = render(); - const right = column(container, 'right')!; - expect(nodesIn(right)).toEqual(['record:related_list', 'record:related_list']); - expect(right.querySelector('[data-record-timeline-panel]')).toBeNull(); + expect(cols.strip.length).toBeGreaterThan(0); + const overview = drawPage('wide', cols, { onEnlargeRelated: vi.fn() }); + // CONTROL: on 概览 the rail and the strip are drawn, the strip above the columns. + expect(column(overview.container, 'right')).not.toBeNull(); + const strip = overview.container.querySelector('[data-record-overview-strip]')!; + expect(strip).not.toBeNull(); + expect(strip.compareDocumentPosition(grid(overview.container)) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(grid(overview.container).contains(strip)).toBe(false); + overview.unmount(); + const other = drawPage('wide', cols, { onEnlargeRelated: vi.fn(), enlargedRelated: 'note.parent_id' }); + expect(column(other.container, 'right')).toBeNull(); + expect(other.container.querySelector('[data-record-summary-card]')).toBeNull(); + expect(other.container.querySelector('[data-record-overview-strip]')).toBeNull(); + expect(other.container.querySelector('[data-node="record:highlights"]')).toBeNull(); + expect(other.container.querySelector('[data-node="record:path"]')).toBeNull(); + }); + + it('a rail with nothing to show takes no column once every count is in; CONTROL: one list with records keeps it', async () => { + harness.timelineCount = 0; + TOTALS.note = 0; + try { + const { container, unmount } = drawPage('wide', synth({ files: false, approvals: false })); + await waitFor(() => expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details')); + expect(column(container, 'right')).toBeNull(); + unmount(); + } finally { + TOTALS.note = 2; + } + RelatedCountStore._reset(); + const again = drawPage('wide', synth({ files: false, approvals: false })); + await waitFor(() => expect(cards(again.container)).toEqual(['note.parent_id'])); + expect(grid(again.container).getAttribute('data-record-columns-shown')).toBe('details right'); + }); + + it('a drawer draws no rail (`rail={false}`): the details alone, the tabs carry the rest', () => { + const { container } = drawPage('wide', synth({ files: true, approvals: true }), { rail: false }); + expect(column(container, 'right')).toBeNull(); + expect(container.querySelector('[data-record-summary-card]')).toBeNull(); + expect(grid(container).getAttribute('data-record-columns-shown')).toBe('details'); }); }); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTabRow-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTabRow-27524.test.tsx index dc252913a48..5769304723d 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordTabRow-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordTabRow-27524.test.tsx @@ -9,8 +9,9 @@ /** * objectstack#27524, Target 8 — the record page's tab row as drawn: its * visible count follows its own width and is recomputed on a resize, the - * active tab is always on it, the 「+N ▾」 dropdown lists the rest with their + * active tab is always on it, the 「更多 N ▾」 dropdown lists the rest with their * counts and the hidden panels' tabs at its end, and the row is one tab stop. + * (objectstack#35595 renamed the trigger 「+N ▾」 to 「更多 N ▾」.) * * jsdom has no layout engine, so the widths are given: each measured tab * answers its width from `WIDTHS`, the trigger `MORE`, the row `rowWidth`; @@ -88,22 +89,22 @@ describe('RecordTabRow (objectstack#27524, Target 8)', () => { // Wide: every tab, no dropdown. expect(shownIds()).toEqual(TABS.map((tab) => tab.id)); expect(more()).toBeNull(); - // Medium (budget 480 - 40 - 16 = 424): Overview · Activity · Tasks · Events, then +2. + // Medium (budget 480 - 40 - 16 = 424): Overview · Activity · Tasks · Events, then 「更多 2」. resizeTo(480); expect(shownIds()).toEqual(['overview', 'timeline', 'task.lead_id', 'event.lead_id']); - expect(more()?.textContent).toBe('+2'); + expect(more()?.textContent).toBe('More 2'); // Narrow: Overview and one more. resizeTo(200); expect(shownIds()).toEqual(['overview', 'timeline']); - expect(more()?.textContent).toBe('+4'); + expect(more()?.textContent).toBe('More 4'); }); - it('on a phone (objectstack#27058): the row a 390 px page draws (366 px inside its padding) shows Overview, Activity and at least one related tab, then 「+N ▾」', () => { + it('on a phone (objectstack#27058): the row a 390 px page draws (366 px inside its padding) shows Overview, Activity and at least one related tab, then 「更多 N ▾」', () => { rowWidth = 366; render(); - // Budget 366 - 40 - 16 = 310: Overview · Activity · Tasks · Events (250), then +2. + // Budget 366 - 40 - 16 = 310: Overview · Activity · Tasks · Events (250), then 「更多 2」. expect(shownIds()).toEqual(['overview', 'timeline', 'task.lead_id', 'event.lead_id']); - expect(more()?.textContent).toBe('+2'); + expect(more()?.textContent).toBe('More 2'); }); it('the active tab is always on the row, in the last slot when it would have folded', () => { @@ -126,11 +127,11 @@ describe('RecordTabRow (objectstack#27524, Target 8)', () => { expect(chip('x.y')).toBeNull(); }); - it('「+N ▾」 lists the folded tabs with their counts, then the hidden panels\' tabs; choosing one selects it', async () => { + it('「更多 N ▾」 lists the folded tabs with their counts, then the hidden panels\' tabs; choosing one selects it', async () => { rowWidth = 480; const onSelect = vi.fn(); render(); - expect(more()?.textContent).toBe('+3'); + expect(more()?.textContent).toBe('More 3'); const user = userEvent.setup(); await user.click(more()!); const items = await screen.findAllByRole('menuitem'); @@ -139,7 +140,9 @@ describe('RecordTabRow (objectstack#27524, Target 8)', () => { 'attendee.lead_id', 'duplicate.lead_id', ]); - expect(items.map((item) => item.querySelector('[data-record-tab-count]')?.textContent)).toEqual(['1', '0', '0']); + // objectstack#35595 — an empty list draws no number, here too: it is muted. + expect(items.map((item) => item.querySelector('[data-record-tab-count]')?.textContent ?? null)).toEqual(['1', null, null]); + expect(items.map((item) => item.hasAttribute('data-record-tab-empty'))).toEqual([false, true, true]); expect(items[2].hasAttribute('data-record-tab-hidden')).toBe(true); await user.click(items[0]); expect(onSelect).toHaveBeenCalledWith('campaign_member.lead_id'); @@ -148,7 +151,7 @@ describe('RecordTabRow (objectstack#27524, Target 8)', () => { it('a hidden panel makes the dropdown even on a wide row', () => { render(); expect(shownIds()).toEqual(TABS.map((tab) => tab.id)); - expect(more()?.textContent).toBe('+1'); + expect(more()?.textContent).toBe('More 1'); }); it('clicking a tab selects it; the active tab does nothing', () => { diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTabRow.recordsFirst-28469.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTabRow.recordsFirst-28469.test.tsx deleted file mode 100644 index eb6dec86a83..00000000000 --- a/ui/packages/plugin-detail/src/__tests__/RecordTabRow.recordsFirst-28469.test.tsx +++ /dev/null @@ -1,271 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#28469 — the record page's tab row as drawn: the related lists - * with records on the row, the empty ones in 「+N ▾」 after the folded tabs, - * behind a separator and in a muted face, the hidden panels' tabs last; an - * active empty tab on the row; and, through `RecordPageColumns`, a page whose - * counts arrive with its payload draws that order on its first render, with - * no tab moving after — and, when the counts are read after the page draws, - * the panel tabs wait off the row until they land, then appear in place. The - * rule itself is pinned in - * `synth/__tests__/recordTabRow-28469.test.ts`. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, cleanup, screen, waitFor } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import { RelatedCountStore } from '@object-ui/components'; -import { RecordContextProvider } from '@object-ui/react'; -import { RecordTabRow, RECORD_TAB_OVERVIEW, type RecordTab } from '../RecordTabRow'; - -vi.mock('@object-ui/react', async (importOriginal) => ({ - ...(await importOriginal>()), - SchemaRenderer: ({ schema }: { schema: any }) =>
    , -})); - -import { RecordPageColumns } from '../RecordPageColumns'; -import { RECORD_PAGE_TIMELINE_PANEL, buildDefaultPageColumns } from '../synth/recordPageColumns'; -import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; - -const TABS: RecordTab[] = [ - { id: RECORD_TAB_OVERVIEW, label: 'Overview' }, - { id: 'timeline', label: 'Activity', count: 0 }, - { id: 'attendee.contact_id', label: 'Attendees', count: 7 }, - { id: 'case.contact_id', label: 'Cases', count: 2 }, -]; -const EMPTY: RecordTab[] = [ - { id: 'lead.converted_contact', label: 'Leads (converted)', count: 0 }, - { id: 'lead.duplicate_contact', label: 'Leads (duplicate)', count: 0 }, -]; -const HIDDEN: RecordTab[] = [{ id: 'opportunity.contact_id', label: 'Opportunities', count: 0 }]; -const WIDTHS: Record = { overview: 60, timeline: 70 }; -const MORE = 40; -let rowWidth = 2000; - -const shownIds = () => Array.from(document.querySelectorAll('[role="tab"]')).map((el) => el.getAttribute('data-record-tab')); -const more = () => document.querySelector('[data-record-tab-more]'); - -describe('RecordTabRow: empty lists wait in the dropdown (objectstack#28469)', () => { - beforeEach(() => { - rowWidth = 2000; - vi.stubGlobal( - 'ResizeObserver', - class { - observe() {} - unobserve() {} - disconnect() {} - }, - ); - vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { - let width = 0; - if (this.hasAttribute('data-record-tab-row')) width = rowWidth; - else if (this.hasAttribute('data-record-tab-measure-more')) width = MORE; - else if (this.hasAttribute('data-record-tab-measure')) width = WIDTHS[this.textContent?.startsWith('Overview') ? 'overview' : this.textContent?.startsWith('Activity') ? 'timeline' : ''] ?? 80; - return { width, height: 36, top: 0, left: 0, right: width, bottom: 36, x: 0, y: 0, toJSON: () => ({}) } as DOMRect; - }); - }); - afterEach(() => { - cleanup(); - vi.restoreAllMocks(); - vi.unstubAllGlobals(); - }); - - it('a row with room for every tab still keeps the empty ones off it; 「+N」 counts them', () => { - render(); - expect(shownIds()).toEqual(TABS.map((tab) => tab.id)); - expect(more()?.textContent).toBe('+3'); - }); - - it('the dropdown lists the folded tabs, then the empty ones behind a separator in a muted face, then the hidden ones', async () => { - // Budget 330 - 40 - 16 = 274: Overview 60 · Activity 70 · Attendees 80 (= 242), then Cases folds. - rowWidth = 330; - const onSelect = vi.fn(); - render(); - expect(shownIds()).toEqual(['overview', 'timeline', 'attendee.contact_id']); - expect(more()?.textContent).toBe('+4'); - const user = userEvent.setup(); - await user.click(more()!); - const items = await screen.findAllByRole('menuitem'); - expect(items.map((item) => item.getAttribute('data-record-tab-menu-item'))).toEqual([ - 'case.contact_id', - 'lead.converted_contact', - 'lead.duplicate_contact', - 'opportunity.contact_id', - ]); - expect(items.map((item) => item.hasAttribute('data-record-tab-empty'))).toEqual([false, true, true, false]); - // A separator between the folded tabs and the empty ones, another before the hidden ones. - const menu = screen.getByRole('menu'); - const order = Array.from(menu.querySelectorAll('[role="menuitem"], [role="separator"]')).map((el) => - el.getAttribute('role') === 'separator' ? '|' : el.getAttribute('data-record-tab-menu-item'), - ); - expect(order).toEqual(['case.contact_id', '|', 'lead.converted_contact', 'lead.duplicate_contact', '|', 'opportunity.contact_id']); - // The empty tabs' counts read muted, as the right column's empty fold does; a folded tab's does not. - const chip = (item: Element) => item.querySelector('[data-record-tab-count]')!; - expect(chip(items[1]).className).toContain('text-muted-foreground'); - expect(chip(items[0]).className).not.toContain('text-muted-foreground'); - await user.click(items[1]); - expect(onSelect).toHaveBeenCalledWith('lead.converted_contact'); - }); - - it('an active empty tab (a ?related= link) is on the row, in its last slot, and leaves the dropdown', () => { - render( - , - ); - expect(shownIds()).toEqual([...TABS.map((tab) => tab.id), 'lead.duplicate_contact']); - expect(document.querySelector('[aria-selected="true"]')?.getAttribute('data-record-tab')).toBe('lead.duplicate_contact'); - expect(more()?.textContent).toBe('+2'); - cleanup(); - // Narrow (budget 274): it takes the last slot from Attendees, which folds. - rowWidth = 330; - render( - , - ); - expect(shownIds()).toEqual(['overview', 'timeline', 'lead.duplicate_contact']); - }); -}); - -const RELATED = [ - { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, - { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, - { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, - { objectName: 'event', relationshipField: 'lead_id', title: 'Events' }, -]; -const TOTALS: Record = { task: 0, note: 3, call: 0, event: 1 }; -const columnsOf = () => - buildDefaultPageColumns(buildDefaultPageSchema({ name: 'lead', fields: {} }, { related: RELATED, hideDiscussion: false }))!; - -function renderPage(find: ReturnType) { - const dataSource = { find, getObjectSchema: vi.fn(async () => ({ fields: {} })) }; - return render( - - ({})} /> - , - ); -} - -/** Watch the tab list: every tab added, removed or moved is a child-list record. */ -function watchTabList(): { moves: () => number; stop: () => void } { - const list = document.querySelector('[role="tablist"]')!; - let moves = 0; - const observer = new MutationObserver((records) => { - moves += records.filter((record) => record.type === 'childList').length; - }); - observer.observe(list, { childList: true }); - return { - moves: () => moves + observer.takeRecords().filter((record) => record.type === 'childList').length, - stop: () => observer.disconnect(), - }; -} - -const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); - -describe('the record page draws the final tab order at first paint (objectstack#28469, Target 2)', () => { - beforeEach(() => RelatedCountStore._reset()); - afterEach(() => cleanup()); - - it('counts that arrive with the page payload: the first render already has the lists with records first, and no tab moves after', async () => { - // The page payload's answers, seeded before the page draws (objectstack#27627). - const seeded = RELATED.map((list) => { - const read = Promise.resolve({ total: TOTALS[list.objectName], rows: [] }); - RelatedCountStore.seed(list.objectName, list.relationshipField, 'lead-1', undefined, 1, read); - return read; - }); - await Promise.all(seeded); - await settle(); - const find = vi.fn(async () => ({ data: [], total: 0 })); - renderPage(find); - // objectstack#34590 — 动态 is the row's last tab (supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」). - const final = ['overview', 'note.parent_id', 'event.lead_id', RECORD_PAGE_TIMELINE_PANEL]; - expect(shownIds()).toEqual(final); - const watch = watchTabList(); - await settle(); - await waitFor(() => expect(document.querySelector('[data-record-tab="note.parent_id"] [data-record-tab-count]')?.textContent).toBe('3')); - await settle(); - expect(shownIds()).toEqual(final); - expect(watch.moves()).toBe(0); - watch.stop(); - // No count was read again: the payload answered them. - expect(find).not.toHaveBeenCalled(); - }); - - it('counts read after the page draws: the panel tabs wait off the row while the set is out, then appear once, already partitioned — no tab drawn earlier moves or leaves', async () => { - let release: () => void = () => {}; - const gate = new Promise((resolve) => { - release = resolve; - }); - const find = vi.fn(async (objectName: string) => { - await gate; - return { data: [], total: TOTALS[objectName] }; - }); - renderPage(find); - // The set is out: the row is Overview alone — 动态, the last tab, waits - // with the panels (objectstack#34590 — 动态 is the row's last tab (supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」)) — and nothing on it will have to move. - expect(shownIds()).toEqual(['overview']); - const states: string[][] = [shownIds() as string[]]; - const observer = new MutationObserver(() => states.push(shownIds() as string[])); - observer.observe(document.querySelector('[data-record-tab-row]')!, { childList: true, subtree: true }); - release(); - const final = ['overview', 'note.parent_id', 'event.lead_id', RECORD_PAGE_TIMELINE_PANEL]; - await waitFor(() => expect(shownIds()).toEqual(final)); - await settle(); - observer.disconnect(); - // Every row drawn on the way is a prefix of the final one: tabs were only added after it. - for (const state of states) expect(final.slice(0, state.length)).toEqual(state); - expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('+2'); - }); - - it('a list whose count is refused keeps its place in the arrangement, among the lists with records', async () => { - const find = vi.fn(async (objectName: string) => { - if (objectName === 'task') throw new Error('refused'); - return { data: [], total: TOTALS[objectName] }; - }); - renderPage(find); - // Tasks (first in the arrangement) is never counted: it stays first; Calls (0) folds. - await waitFor(() => - // objectstack#34590 — 动态 is the row's last tab (supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」). - expect(shownIds()).toEqual(['overview', 'task.lead_id', 'note.parent_id', 'event.lead_id', RECORD_PAGE_TIMELINE_PANEL]), - ); - expect(document.querySelector('[data-record-tab="task.lead_id"] [data-record-tab-count]')).toBeNull(); - expect(document.querySelector('[data-record-tab-more]')?.textContent).toBe('+1'); - }); - - it('an active tab (restored from ?related=) is drawn while the set is out', async () => { - let release: () => void = () => {}; - const gate = new Promise((resolve) => { - release = resolve; - }); - const find = vi.fn(async (objectName: string) => { - await gate; - return { data: [], total: TOTALS[objectName] }; - }); - const dataSource = { find, getObjectSchema: vi.fn(async () => ({ fields: {} })) }; - render( - - ({})} - /> - , - ); - // 动态 waits with the panels; the active tab is drawn (objectstack#34590 — 动态 is the row's last tab (supersedes objectstack#27524 Target 8's 动态-second: 「「动态」在最后」)). - expect(shownIds()).toEqual(['overview', 'call.lead_id']); - expect(document.querySelector('[aria-selected="true"]')?.getAttribute('data-record-tab')).toBe('call.lead_id'); - release(); - // Calls turns out empty: as the active tab it stays on the row, in the last slot. - await waitFor(() => - expect(shownIds()).toEqual(['overview', 'note.parent_id', 'event.lead_id', RECORD_PAGE_TIMELINE_PANEL, 'call.lead_id']), - ); - }); -}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTabRow.widthOnly-35595.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTabRow.widthOnly-35595.test.tsx new file mode 100644 index 00000000000..9c67d9dd8dc --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordTabRow.widthOnly-35595.test.tsx @@ -0,0 +1,210 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35595 — the record page's tab row as drawn: every related list + * on the row in its order, an empty one muted and with no number, the width + * the only fold (「更多 N ▾」, whose items keep their counts), and — through + * `RecordPageColumns` — 概览, the lists, 附件, 审批 and 动态, drawn at first + * paint with no tab moving after the counts land. Supersedes objectstack#28469 + * (empty lists in the dropdown), whose pins this file replaces. The width rule + * itself is pinned in `synth/__tests__/recordTabRow.widthOnly-35595.test.ts`. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { RelatedCountStore } from '@object-ui/components'; +import { RecordContextProvider } from '@object-ui/react'; +import { RecordTabRow, RECORD_TAB_OVERVIEW, type RecordTab } from '../RecordTabRow'; + +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + SchemaRenderer: ({ schema }: { schema: any }) =>
    , +})); + +import { RecordPageColumns } from '../RecordPageColumns'; +import { RECORD_PAGE_TIMELINE_PANEL, buildDefaultPageColumns } from '../synth/recordPageColumns'; +import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; + +const TABS: RecordTab[] = [ + { id: RECORD_TAB_OVERVIEW, label: 'Overview' }, + { id: 'attendee.contact_id', label: 'Attendees', count: 7 }, + { id: 'lead.converted_contact', label: 'Leads (converted)', count: 0 }, + { id: 'case.contact_id', label: 'Cases', count: 2 }, + { id: 'approvals', label: 'Approvals', dot: true }, + { id: 'timeline', label: 'Activity', count: 3 }, +]; +const HIDDEN: RecordTab[] = [{ id: 'opportunity.contact_id', label: 'Opportunities', count: 0 }]; +const WIDTHS: Record = { overview: 60, timeline: 70 }; +const MORE = 40; +let rowWidth = 2000; + +const shownIds = () => Array.from(document.querySelectorAll('[role="tab"]')).map((el) => el.getAttribute('data-record-tab')); +const more = () => document.querySelector('[data-record-tab-more]'); +const tab = (id: string) => document.querySelector(`[data-record-tab="${id}"]`); + +function stubLayout() { + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) { + let width = 0; + if (this.hasAttribute('data-record-tab-row')) width = rowWidth; + else if (this.hasAttribute('data-record-tab-measure-more')) width = MORE; + else if (this.hasAttribute('data-record-tab-measure')) + width = WIDTHS[this.textContent?.startsWith('Overview') ? 'overview' : this.textContent?.startsWith('Activity') ? 'timeline' : ''] ?? 80; + return { width, height: 36, top: 0, left: 0, right: width, bottom: 36, x: 0, y: 0, toJSON: () => ({}) } as DOMRect; + }); +} + +describe('RecordTabRow: the width is the only fold (objectstack#35595)', () => { + beforeEach(() => { + rowWidth = 2000; + stubLayout(); + }); + afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('a row with room shows every tab: an empty list in its place, muted, with no number', () => { + render(); + expect(shownIds()).toEqual(TABS.map((t) => t.id)); + expect(more()).toBeNull(); + const empty = tab('lead.converted_contact')!; + expect(empty.hasAttribute('data-record-tab-empty')).toBe(true); + expect(empty.querySelector('[data-record-tab-count]')).toBeNull(); + expect(empty.querySelector('[data-record-tab-label]')!.className).toContain('opacity-70'); + // CONTROL: a list with records carries its count and no muted label. + const cases = tab('case.contact_id')!; + expect(cases.hasAttribute('data-record-tab-empty')).toBe(false); + expect(cases.querySelector('[data-record-tab-count]')?.textContent).toBe('2'); + expect(cases.querySelector('[data-record-tab-label]')!.className).not.toContain('opacity-70'); + }); + + it('the 审批 tab carries a dot, not a count', () => { + render(); + expect(tab('approvals')!.querySelector('[data-record-tab-dot]')).not.toBeNull(); + expect(tab('approvals')!.querySelector('[data-record-tab-count]')).toBeNull(); + // CONTROL: no other tab draws one. + expect(document.querySelectorAll('[role="tab"] [data-record-tab-dot]').length).toBe(1); + }); + + it('narrow: the tail folds into 「更多 N ▾」 (the hidden lists counted), whose items keep their counts', async () => { + // Budget 330 - 40 - 16 = 274: Overview 60 · Attendees 80 · Leads 80 (= 252), then Cases folds. + rowWidth = 330; + const onSelect = vi.fn(); + render(); + expect(shownIds()).toEqual(['overview', 'attendee.contact_id', 'lead.converted_contact']); + expect(more()?.textContent).toBe('More 4'); + expect(more()?.getAttribute('data-record-tab-more')).toBe('4'); + const user = userEvent.setup(); + await user.click(more()!); + const items = await screen.findAllByRole('menuitem'); + expect(items.map((item) => item.getAttribute('data-record-tab-menu-item'))).toEqual([ + 'case.contact_id', + 'approvals', + 'timeline', + 'opportunity.contact_id', + ]); + expect(items[0].querySelector('[data-record-tab-count]')?.textContent).toBe('2'); + expect(items[2].querySelector('[data-record-tab-count]')?.textContent).toBe('3'); + expect(items[1].querySelector('[data-record-tab-dot]')).not.toBeNull(); + await user.click(items[0]); + expect(onSelect).toHaveBeenCalledWith('case.contact_id'); + }); +}); + +const RELATED = [ + { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, + { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, + { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, + { objectName: 'event', relationshipField: 'lead_id', title: 'Events' }, +]; +const TOTALS: Record = { task: 0, note: 3, call: 0, event: 1 }; +const columnsOf = () => + buildDefaultPageColumns( + buildDefaultPageSchema({ name: 'lead', fields: {}, enable: { files: true } } as any, { related: RELATED, hideDiscussion: false }), + )!; + +function renderPage(find: ReturnType) { + const dataSource = { find, getObjectSchema: vi.fn(async () => ({ fields: {} })) }; + return render( + + ({})} /> + , + ); +} + +/** Watch the tab list: every tab added, removed or moved is a child-list record. */ +function watchTabList(): { moves: () => number; stop: () => void } { + const list = document.querySelector('[role="tablist"]')!; + let moves = 0; + const observer = new MutationObserver((records) => { + moves += records.filter((record) => record.type === 'childList').length; + }); + observer.observe(list, { childList: true }); + return { + moves: () => moves + observer.takeRecords().filter((record) => record.type === 'childList').length, + stop: () => observer.disconnect(), + }; +} + +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); +// 概览, every list in `relatedLists` order, 附件, then 动态 last (objectstack#34590). +const FINAL = ['overview', 'task.lead_id', 'note.parent_id', 'call.lead_id', 'event.lead_id', 'attachments', RECORD_PAGE_TIMELINE_PANEL]; + +describe('the record page draws every tab at first paint, and none moves (objectstack#35595)', () => { + beforeEach(() => RelatedCountStore._reset()); + afterEach(() => cleanup()); + + it('counts read after the page draws: the final order is there before they land, and nothing moves when they do', async () => { + let release: () => void = () => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const find = vi.fn(async (objectName: string) => { + await gate; + return { data: [], total: TOTALS[objectName] ?? 0 }; + }); + renderPage(find); + expect(shownIds()).toEqual(FINAL); + const watch = watchTabList(); + release(); + await waitFor(() => expect(tab('note.parent_id')?.querySelector('[data-record-tab-count]')?.textContent).toBe('3')); + await settle(); + expect(shownIds()).toEqual(FINAL); + expect(watch.moves()).toBe(0); + watch.stop(); + // The empty lists keep their places, muted, with no number; no 「更多」 on a wide row. + expect(tab('task.lead_id')?.hasAttribute('data-record-tab-empty')).toBe(true); + expect(tab('call.lead_id')?.hasAttribute('data-record-tab-empty')).toBe(true); + expect(tab('event.lead_id')?.querySelector('[data-record-tab-count]')?.textContent).toBe('1'); + expect(more()).toBeNull(); + }); + + it('a list whose count is refused keeps its place, with no number and not muted', async () => { + const find = vi.fn(async (objectName: string) => { + if (objectName === 'task') throw new Error('refused'); + return { data: [], total: TOTALS[objectName] ?? 0 }; + }); + renderPage(find); + await waitFor(() => expect(tab('note.parent_id')?.querySelector('[data-record-tab-count]')?.textContent).toBe('3')); + expect(shownIds()).toEqual(FINAL); + expect(tab('task.lead_id')?.querySelector('[data-record-tab-count]')).toBeNull(); + expect(tab('task.lead_id')?.hasAttribute('data-record-tab-empty')).toBe(false); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx index 9b89e771d4d..60d1d200bba 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel.chatterInset-34676.test.tsx @@ -7,17 +7,21 @@ */ /** - * objectstack#34676 — the 动态 panel of the record page's right column draws + * objectstack#34676 — the 动态 card of the record page's right column draws * its body edge to edge: it expects `record:activity`'s peek face, whose rows * pad themselves. A slotted page's `discussion` slot puts `record:chatter` * there instead, and the chatter block draws the - * timeline's panel face — the 全部动态 filter, the composer, full rows — which - * pads only its top, so its icons, the send button and long rows would sit - * on the card's border. + * timeline's panel face — the 全部动态 filter, full rows — which pads only its + * top, so its icons and long rows would sit on the card's border. + * + * objectstack#35596 moved the card into the 概览 tab's rail as 「最近动态」 + * (`RecordSummaryRail`, replacing `RecordTimelinePanel` on the page): the + * same inset holds there, and nothing in the rail is editable — neither face + * offers a composer. * * Drawn here through the real default record page (`buildDefaultPageSchema` * → `buildDefaultPageColumns` → `RecordPageColumns`, real block renderers), so - * the chatter node lands in `RecordTimelinePanel` the way it does on the page. + * the chatter node lands in the rail's card the way it does on the page. * jsdom lays nothing out, so the pins read the classes that make the inset. */ @@ -70,16 +74,21 @@ const classesOf = (el: Element | null | undefined) => (el?.getAttribute('class') const hasInlinePadding = (el: Element | null | undefined) => classesOf(el).some((c) => /^(px|pl|pr|p)-/.test(c)); -describe('the 动态 panel holding a record:chatter block (objectstack#34676)', () => { +const CARD = '[data-record-summary-card="timeline"]'; + +describe('the rail\'s 最近动态 card holding a record:chatter block (objectstack#34676, objectstack#35596)', () => { it('the chatter timeline is inset inside the card: horizontal and bottom padding, one divider under the head', () => { const { container } = draw(chatterColumns()); - const panel = container.querySelector('[data-record-timeline-panel]') as HTMLElement; + const panel = container.querySelector(CARD) as HTMLElement; expect(panel).not.toBeNull(); - // The block in the panel is the chatter's panel face (filter, composer), not a peek. + // A chatter stream reports no count: its card is drawn as it comes. + expect(panel.hidden).toBe(false); + // The block in the card is the chatter's panel face (filter), not a peek. expect(panel.querySelector('[data-record-timeline-peek]')).toBeNull(); const timeline = panel.querySelector('section[aria-label="Discussion"]') as HTMLElement; expect(timeline).not.toBeNull(); - expect(timeline.querySelector('textarea')).not.toBeNull(); + // Nothing in the rail is editable (objectstack#35596): no composer. + expect(timeline.querySelector('textarea')).toBeNull(); const cls = classesOf(timeline); // Inset on both sides and at the foot, like the related panels' rows (px-3). expect(cls).toContain('px-3'); @@ -98,7 +107,7 @@ describe('the 动态 panel holding a record:chatter block (objectstack#34676)', it('CONTROL — record:activity in the same card keeps its peek face, edge to edge, rows padding themselves', () => { const { container } = draw(activityColumns()); - const panel = container.querySelector('[data-record-timeline-panel]') as HTMLElement; + const panel = container.querySelector(CARD) as HTMLElement; const peek = panel.querySelector('[data-record-timeline-peek]') as HTMLElement; expect(peek).not.toBeNull(); // The peek root carries no class of its own: its rows bleed to the card's edge. @@ -107,20 +116,20 @@ describe('the 动态 panel holding a record:chatter block (objectstack#34676)', expect(hasInlinePadding(el)).toBe(false); } const rows = Array.from(panel.querySelectorAll('[data-record-timeline-peek-row]')); - expect(rows.length).toBeGreaterThan(0); + // The newest three (the rail's row cap), each padding itself. + expect(rows).toHaveLength(3); for (const row of rows) { expect(row.getAttribute('class')).toBe('flex h-8 items-center gap-2 border-t border-border px-3 text-[12.5px]'); } - expect(panel.querySelector('[data-record-timeline-composer]')!.parentElement!.getAttribute('class')).toBe( - 'border-t border-border px-3 py-2', - ); + // Read-only: the peek's composer is not offered in the rail. + expect(panel.querySelector('[data-record-timeline-composer]')).toBeNull(); }); it('CONTROL — the 动态 tab draws the same chatter block with no card, so no inset: the de-boxed face', () => { const { container } = draw(chatterColumns(), RECORD_PAGE_TIMELINE_PANEL); const face = container.querySelector(`[data-related-enlarged="${RECORD_PAGE_TIMELINE_PANEL}"]`) as HTMLElement; expect(face).not.toBeNull(); - expect(face.closest('[data-record-timeline-panel]')).toBeNull(); + expect(face.closest(CARD)).toBeNull(); const timeline = face.querySelector('section[aria-label="Discussion"]') as HTMLElement; expect(timeline).not.toBeNull(); // pt-3 since the dense activity rows (objectstack#35602). diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedCardStack-27055.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedCardStack-27055.test.tsx deleted file mode 100644 index 7b39bcfd4cf..00000000000 --- a/ui/packages/plugin-detail/src/__tests__/RelatedCardStack-27055.test.tsx +++ /dev/null @@ -1,232 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#27055, Targets 7 and 10 — the related column's panels in the - * reader's arrangement, through `RecordPageColumns`. The related-list block - * is stubbed (it draws its relationship id and the chrome it was handed), so - * what is measured is the stack: the order the store says, the keyboard - * moves the ⠿ handle hands each panel (objectstack#27524) written back - * through the host's setter, the hidden line and the changed-default hint. - * A panel no longer collapses (objectstack#27524, Target 1): its chrome - * carries no collapse. The merge rules themselves are pinned in - * `synth/__tests__/relatedArrangement-27055.test.ts`; the panel's own header - * in `RelatedPanel.header-27524.test.tsx`. - */ - -import * as React from 'react'; -import { describe, it, expect, vi, afterEach } from 'vitest'; -import { render, cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; -import { RelatedCardChromeContext, RelatedListCompactContext, RelatedListEnlargedContext } from '../relatedListCompact'; - -vi.mock('@object-ui/react', async (importOriginal) => ({ - ...(await importOriginal>()), - SchemaRenderer: ({ schema }: { schema: any }) => , -})); - -function StubNode({ schema }: { schema: any }) { - const chrome = React.useContext(RelatedCardChromeContext); - const compact = React.useContext(RelatedListCompactContext); - const enlarged = React.useContext(RelatedListEnlargedContext); - const p = schema?.properties ?? {}; - return ( -
    - {chrome?.onEnlarge && } - {p.objectName ?? schema?.type} - {chrome?.onMoveUp && } - {chrome?.onMoveDown && } - {chrome && } - {chrome?.fresh && new} -
    - ); -} - -import { RecordPageColumns } from '../RecordPageColumns'; -import { buildDefaultPageColumns } from '../synth/recordPageColumns'; -import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; -import { editRelatedArrangement, relatedDefaultOrderHash, type RelatedArrangement } from '../synth/relatedArrangement'; - -const RELATED = [ - { objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }, - { objectName: 'note', relationshipField: 'parent_id', title: 'Notes' }, - { objectName: 'call', relationshipField: 'lead_id', title: 'Calls' }, -]; -const DEFAULT = ['task.lead_id', 'note.parent_id', 'call.lead_id']; -const columnsOf = (related = RELATED) => - buildDefaultPageColumns(buildDefaultPageSchema({ name: 'lead', fields: {} }, { related, hideDiscussion: true }))!; - -const cardOrder = (container: HTMLElement) => - Array.from(container.querySelectorAll('[data-record-column="right"] [data-related-card-id]')).map((el) => - el.getAttribute('data-related-card-id'), - ); - -/** A host with a real store: the arrangement round-trips through state. */ -function Host({ initial, onWrite, related }: { initial?: RelatedArrangement; onWrite?: (v: RelatedArrangement) => void; related?: typeof RELATED }) { - const [arrangement, setArrangement] = React.useState(initial); - return ( - { - onWrite?.(next); - setArrangement(next); - }} - /> - ); -} - -afterEach(cleanup); - -describe('RelatedCardStack — the reader arranges the related cards (objectstack#27055)', () => { - it('draws the default order for a reader who never chose', () => { - const { container } = render(); - expect(cardOrder(container)).toEqual(DEFAULT); - }); - - it("draws the stored reader's order", () => { - const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); - const { container } = render(); - expect(cardOrder(container)).toEqual(['call.lead_id', 'task.lead_id', 'note.parent_id']); - }); - - it('the handle’s ⌥↑ / ⌥↓ write the new order through the host', () => { - const onWrite = vi.fn(); - const { container } = render(); - fireEvent.click(screen.getByText('down task')); - expect(cardOrder(container)).toEqual(['note.parent_id', 'task.lead_id', 'call.lead_id']); - expect(onWrite.mock.calls[0][0].order).toEqual(['note.parent_id', 'task.lead_id', 'call.lead_id']); - // The first card offers no 上移, the last no 下移. - expect(screen.queryByText('up note')).toBeNull(); - expect(screen.queryByText('down call')).toBeNull(); - }); - - it('a panel carries no collapse: every shown panel mounts its list (objectstack#27524, Target 1)', () => { - const { container } = render(); - expect(container.querySelectorAll('[data-node="record:related_list"]')).toHaveLength(DEFAULT.length); - expect(container.querySelector('[data-related-card-collapsed]')).toBeNull(); - }); - - it('a hidden card leaves the column; the last line brings them back', () => { - const { container } = render(); - fireEvent.click(screen.getByText('hide task')); - expect(cardOrder(container)).toEqual(['note.parent_id', 'call.lead_id']); - const line = container.querySelector('[data-related-hidden-line]')!; - expect(line).toBeTruthy(); - fireEvent.click(line.querySelector('button')!); - expect(cardOrder(container)).toEqual(DEFAULT); - expect(container.querySelector('[data-related-hidden-line]')).toBeNull(); - }); - - it('「恢复默认顺序」 stands at the column foot once a card moved, and restores the default (objectstack#27241)', () => { - const onWrite = vi.fn(); - const { container } = render(); - // The default arrangement: no foot line at all. - expect(container.querySelector('[data-related-foot-line]')).toBeNull(); - fireEvent.click(screen.getByText('down task')); - expect(cardOrder(container)).toEqual(['note.parent_id', 'task.lead_id', 'call.lead_id']); - const foot = container.querySelector('[data-record-column="right"] [data-related-foot-line]')!; - expect(foot).not.toBeNull(); - // Not the changed-default hint: the author's default did not change. - expect(container.querySelector('[data-related-default-changed]')).toBeNull(); - const restore = foot.querySelector('[data-related-restore-default-order]') as HTMLButtonElement; - expect(restore.textContent).toBe('Restore default order'); - fireEvent.click(restore); - expect(cardOrder(container)).toEqual(DEFAULT); - const written = onWrite.mock.calls.at(-1)![0]; - expect(written.order).toEqual([]); - expect(written.basedOn).toBe(relatedDefaultOrderHash(DEFAULT)); - expect(container.querySelector('[data-related-foot-line]')).toBeNull(); - }); - - it('a hidden card puts 「恢复默认顺序」 on the hidden line, and it shows every card again (objectstack#27241)', () => { - const { container } = render(); - fireEvent.click(screen.getByText('hide note')); - const foot = container.querySelector('[data-related-foot-line]')!; - expect(foot.querySelector('[data-related-hidden-line]')).not.toBeNull(); - fireEvent.click(foot.querySelector('[data-related-restore-default-order]')!); - expect(cardOrder(container)).toEqual(DEFAULT); - expect(container.querySelector('[data-related-foot-line]')).toBeNull(); - }); - - it('says when the default changed under a dragged order, and restores it', () => { - const dragged = editRelatedArrangement(DEFAULT, undefined, { kind: 'move', id: 'call.lead_id', to: 0 }, Date.now()); - const reordered = [RELATED[1], RELATED[0], RELATED[2]]; - const { container } = render(); - expect(cardOrder(container)).toEqual(['call.lead_id', 'task.lead_id', 'note.parent_id']); - const hint = container.querySelector('[data-related-default-changed]')!; - expect(hint).toBeTruthy(); - fireEvent.click(hint.querySelector('button')!); - expect(cardOrder(container)).toEqual(['note.parent_id', 'task.lead_id', 'call.lead_id']); - expect(container.querySelector('[data-related-default-changed]')).toBeNull(); - }); - - it('badges a relationship new since the drag, and stamps it as seen once', async () => { - const dragged = editRelatedArrangement(DEFAULT.slice(0, 2), undefined, { kind: 'move', id: 'note.parent_id', to: 0 }, Date.now()); - const onWrite = vi.fn(); - const { container } = render(); - // Rule 3: after its nearest default predecessor the reader's order holds (note). - expect(cardOrder(container)).toEqual(['note.parent_id', 'call.lead_id', 'task.lead_id']); - expect(container.querySelector('[data-related-card-id="call.lead_id"] [data-fresh]')).not.toBeNull(); - await waitFor(() => expect(onWrite).toHaveBeenCalledTimes(1)); - expect(Object.keys(onWrite.mock.calls[0][0].seen)).toEqual(['call.lead_id']); - // Still badged after the stamp (48 h from it). - expect(container.querySelector('[data-related-card-id="call.lead_id"] [data-fresh]')).not.toBeNull(); - }); -}); - -describe('the enlarged related list — ⤢ and ?related= (objectstack#27055, Target 9)', () => { - it('⤢ asks the host to enlarge that relationship', () => { - const onEnlarge = vi.fn(); - render(); - fireEvent.click(screen.getByText('enlarge note')); - expect(onEnlarge).toHaveBeenCalledWith('note.parent_id'); - }); - - it('draws the full list over the page body: the header stays, the columns step aside', () => { - const { container } = render( - , - ); - const enlarged = container.querySelector('[data-related-enlarged="note.parent_id"]')!; - expect(enlarged).toBeTruthy(); - expect(container.querySelector('[data-record-columns]')).toBeNull(); - // The FULL face, not the compact card — and paged. Since objectstack#27524 - // it is drawn as the tab's face: the toolbar over the table, no card - // (`RelatedList.enlargedToolbar-27524`). - const list = enlarged.querySelector('[data-node="record:related_list"]')!; - expect(list.getAttribute('data-compact')).toBe('no'); - expect(list.getAttribute('data-enlarged')).toBe('yes'); - expect(list.getAttribute('data-limit')).toBe('25'); - // The header nodes are still drawn above it. - expect(container.querySelector('[data-node="page:header"]')).not.toBeNull(); - }); - - it('「概览」 and Esc return to the columns (objectstack#27524, Target 9)', () => { - const onClose = vi.fn(); - const { container } = render( - , - ); - fireEvent.click(container.querySelector('[data-record-tab="overview"]')!); - fireEvent.keyDown(document, { key: 'Escape' }); - expect(onClose).toHaveBeenCalledTimes(2); - }); - - it('an id naming no related list draws the columns', () => { - const { container } = render( - , - ); - expect(container.querySelector('[data-related-enlarged]')).toBeNull(); - expect(container.querySelector('[data-record-columns]')).not.toBeNull(); - }); -}); diff --git a/ui/packages/plugin-detail/src/defaultRecordPage.ts b/ui/packages/plugin-detail/src/defaultRecordPage.ts index 901152bd7ae..ac23ce05ea8 100644 --- a/ui/packages/plugin-detail/src/defaultRecordPage.ts +++ b/ui/packages/plugin-detail/src/defaultRecordPage.ts @@ -57,9 +57,9 @@ export const EmptySectionsLineContext = React.createContext(false); * `record:details` node per run of sections — and every part used to draw it, * so the page read as if two locks applied. The laid-out page * (`RecordPageColumns`) sets `false` around every details part after the - * first, which keeps the band above the body table. Default `true`: an - * authored page's details body, a standalone `DetailView` and the drawer keep - * their band. Whether the band reads locked or editable is untouched — that is + * first, which keeps the band above the body table. Default `true`: a + * standalone `DetailView` and the drawer keep their band, and an authored + * page's details bodies draw one between them ({@link ApprovalBandOnceScope}). Whether the band reads locked or editable is untouched — that is * `resolveApprovalLock`'s rule (a `lockRecord: false` node is never locked). * * Module-internal, the way `EmptySectionsLineContext` is: neither a @@ -67,6 +67,78 @@ export const EmptySectionsLineContext = React.createContext(false); */ export const ApprovalBandContext = React.createContext(true); +/** + * One approval band per page drawn as written (objectstack#35483, + * objectstack#35484). A page the host draws through one `SchemaRenderer` — an + * authored page, or a synthesized page whose strip cannot be laid out — cannot + * set {@link ApprovalBandContext} per details node, so each `record:details` + * body drew its own band. Under {@link ApprovalBandOnceScope} every body that + * reaches the band's place marks it, and only the FIRST mark in document order + * draws the band: a first node that draws no body leaves no mark, and a + * `lockRecord: false` first node draws its own (editable) band, the page's one. + * The band keeps its recall lever and its tally. Outside a scope every body + * draws its band as before. + */ +export interface ApprovalBandOnce { + /** Mark a body's band place; returns the unmark. `onChange` re-renders the body when the first mark moves. */ + register: (mark: Element, onChange: () => void) => () => void; + /** The first mark in document order, or `null`. */ + first: () => Element | null; +} + +export function createApprovalBandOnce(): ApprovalBandOnce { + const marks = new Map void>(); + const notify = () => { + for (const onChange of Array.from(marks.values())) onChange(); + }; + return { + register(mark, onChange) { + marks.set(mark, onChange); + notify(); + return () => { + marks.delete(mark); + notify(); + }; + }, + first() { + let first: Element | null = null; + for (const mark of marks.keys()) { + if (!mark.isConnected) continue; + if (!first || first.compareDocumentPosition(mark) & Node.DOCUMENT_POSITION_PRECEDING) first = mark; + } + return first; + }, + }; +} + +export const ApprovalBandOnceContext = React.createContext(null); + +/** The page scope under which one approval band is drawn (see {@link ApprovalBandOnce}). */ +export function ApprovalBandOnceScope({ children }: { children?: React.ReactNode }): React.ReactElement { + const [once] = React.useState(createApprovalBandOnce); + return React.createElement(ApprovalBandOnceContext.Provider, { value: once }, children); +} + +/** + * A details body's part in the page's one band: `draws` is whether this body + * draws it, `mark` the hidden element it renders where the band would be. + * Outside a scope it draws, with no mark. + */ +export function useApprovalBandOnce(): { draws: boolean; mark: React.ReactNode } { + const once = React.useContext(ApprovalBandOnceContext); + const [mark, setMark] = React.useState(null); + const [, rerender] = React.useReducer((n: number) => n + 1, 0); + React.useLayoutEffect(() => { + if (!once || !mark) return undefined; + return once.register(mark, rerender); + }, [once, mark]); + if (!once) return { draws: true, mark: null }; + return { + draws: mark !== null && once.first() === mark, + mark: React.createElement('span', { ref: setMark, hidden: true, 'data-approval-band-mark': '' }), + }; +} + /** * The most columns a frameless detail section may take on the page being * drawn (objectstack#27524, Target 6): the record page's layout sets 2 in its diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 6398dce940d..daf81f54b1d 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -226,6 +226,8 @@ export type { RecordPageColumnsProps } from './RecordPageColumns'; // objectstack#27055 — the record page v3 face: a host drawing the // synthesized default page in its tabbed tier marks it, as the column tiers do. export { DefaultRecordPageContext } from './defaultRecordPage'; +// objectstack#35484 — a page drawn as written draws one approval band. +export { ApprovalBandOnceScope } from './defaultRecordPage'; export { RecordBodyTablesContext } from './relatedListCompact'; // objectstack#27056 — for the app-shell record drawer's prefetch: it warms // the next record's related counts before the reader steps to it. diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts index 73492ad7a16..b6369627550 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts @@ -15,8 +15,9 @@ * `relatedList: 'primary'`) is a table section of the Details tab, placed * BEFORE the field sections (objectstack#35597, 「关键字段下面」: under the header * strip, above the field groups; objectstack#27069 placed it after the FIRST - * section); several stack in the order given; the sections follow. Every other list is a side card in the one - * `Related` tab. A field group whose `relatedList` names a body table's + * section); several stack in the order given; the sections follow. Every other + * list is a tab of its own (objectstack#35595, which retired the one `Related` + * tab). A field group whose `relatedList` names a body table's * relationship places that table at the group's position instead * (objectstack#27069, objectstack#27241). */ @@ -52,16 +53,16 @@ const shape = (nodes: any[]) => ); describe('body tables sit in the Details tab before the field sections (objectstack#27055, objectstack#35597)', () => { - it('splits the details around the body tables; side lists stay in Related', () => { + it('splits the details around the body tables; each side list takes a tab of its own (objectstack#35595)', () => { const tabs = buildDefaultTabs(quoteDef, { sections: SECTIONS, related: [LINES, TASKS, SCHEDULE] }); - // 动态 is last for every object (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(items(tabs).map((i: any) => i.value)).toEqual(['details', 'related', 'timeline']); + // 动态 is last for every object (objectstack#34590). + expect(items(tabs).map((i: any) => i.value)).toEqual(['details', 'related:task.quote', 'timeline']); expect(shape(items(tabs)[0].children)).toEqual([ 'table(quote_line_item)', 'table(quote_schedule)', 'details(Basic,Terms,Notes)', ]); - expect(tabOf(tabs, 'related').children.map((n: any) => n.properties.objectName)).toEqual(['task']); + expect(tabOf(tabs, 'related:task.quote').children.map((n: any) => n.properties.objectName)).toEqual(['task']); }); it('a body table opens on a first page of ten rows unless its list names a limit', () => { @@ -77,8 +78,8 @@ describe('body tables sit in the Details tab before the field sections (objectst expect(shape(items(asBody)[0].children)).toContain('table(task)'); const asSide = buildDefaultTabs(quoteDef, { sections: SECTIONS, related: [{ ...primary, isBody: false }] }); expect(shape(items(asSide)[0].children)).not.toContain('table(task)'); - // Related is second now that 动态 closes the strip (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(items(asSide)[1].value).toBe('related'); + // A side list is a tab of its own, second after 概览 (objectstack#35595). + expect(items(asSide)[1].value).toBe('related:task.quote'); }); it('with one section the tables lead it', () => { @@ -91,9 +92,12 @@ describe('body tables sit in the Details tab before the field sections (objectst expect(shape(items(tabs)[0].children)).toEqual(['details()', 'table(quote_line_item)', 'table(quote_schedule)']); }); - it('emits no per-list tab any more — the strip is Details / Related / Timeline (objectstack#34590)', () => { + it('a body table takes no tab of its own: only the side lists do (objectstack#35595)', () => { const tabs = buildDefaultTabs(quoteDef, { sections: SECTIONS, related: [{ ...TASKS, isPrimary: true }, LINES] }); expect(items(tabs).some((i: any) => String(i.value).startsWith('related:'))).toBe(false); + // CONTROL: the same list as a side list is a tab. + const side = buildDefaultTabs(quoteDef, { sections: SECTIONS, related: [TASKS, LINES] }); + expect(items(side).map((i: any) => i.value)).toEqual(['details', 'related:task.quote', 'timeline']); }); }); @@ -164,7 +168,7 @@ describe('a field group places a body table at its position (objectstack#27069, // objectstack#27055); the renderer never second-guesses body-ness either. const tabs = buildDefaultTabs(placed('task'), { related: [LINES, TASKS] }); expect(shape(items(tabs)[0].children)).toEqual(['table(quote_line_item)', 'details(basic,terms,notes)']); - expect(tabOf(tabs, 'related').children.map((n: any) => n.properties.objectName)).toEqual(['task']); + expect(tabOf(tabs, 'related:task.quote').children.map((n: any) => n.properties.objectName)).toEqual(['task']); }); it('the host-passed sections place the same way (the `{ group }` sections RecordDetailView passes)', () => { diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.relatedListFilter-4664.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.relatedListFilter-4664.test.ts index 4fa2d5ea1c0..e5b64d785cb 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.relatedListFilter-4664.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.relatedListFilter-4664.test.ts @@ -36,7 +36,8 @@ const def: ObjectDefLike = { const relatedNodeOf = (rel: Record) => { const tabs = buildDefaultTabs(def, { related: [rel as any] }); - const relatedTab = tabItems(tabs).find((t: any) => t.label === 'Related'); + // objectstack#35595 — a side list is a tab of its own, `related:.`. + const relatedTab = tabItems(tabs).find((t: any) => t.value === `related:${rel.objectName}.${rel.relationshipField}`); return relatedTab.children[0]; }; diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts index 218b15ae86c..f0194041a61 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts @@ -231,9 +231,9 @@ describe('the accepted shape still carries the semantics (objectui#4232)', () => related: [{ objectName: 'task', relationshipField: 'lead_id', title: 'Tasks' }], }); const parsed = PageTabsProps.parse(tabs.properties) as any; - // objectstack#34590 — 动态 closes the strip (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(parsed.items.map((i: any) => i.label)).toEqual(['Details', 'Related', 'Activity stream']); - expect(parsed.items.map((i: any) => i.value)).toEqual(['details', 'related', 'timeline']); + // objectstack#35595 — 概览, a tab per side list; 动态 closes the strip (objectstack#34590). + expect(parsed.items.map((i: any) => i.label)).toEqual(['Overview', 'Tasks', 'Activity stream']); + expect(parsed.items.map((i: any) => i.value)).toEqual(['details', 'related:task.lead_id', 'timeline']); expect(parsed.items[0].children[0].type).toBe('record:details'); expect(parsed.items[1].children[0].properties.objectName).toBe('task'); }); @@ -244,8 +244,8 @@ describe('the accepted shape still carries the semantics (objectui#4232)', () => }); const page = PageSchema.parse(body) as any; const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); - // objectstack#34590 — 动态 closes the strip (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(tabs.properties.items.map((i: any) => i.value)).toEqual(['details', 'related', 'timeline']); + // objectstack#35595 — a tab per side list; 动态 closes the strip (objectstack#34590). + expect(tabs.properties.items.map((i: any) => i.value)).toEqual(['details', 'related:task.lead_id', 'timeline']); expect(tabs.properties.items[1].children[0].properties.relationshipField).toBe('lead_id'); }); }); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts index d718f59e38c..24c8f15064c 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts @@ -266,12 +266,12 @@ describe('buildDefaultPageSchema', () => { expect(props(header).recordChrome).toBe(true); }); - it('page:tabs always carries a details tab containing record:details, then the Timeline', () => { + it('page:tabs always carries the Overview tab (value details) containing record:details, then the Timeline (objectstack#35595)', () => { const tabs = buildDefaultPageSchema(leadDef).regions[0].components.find( (c: any) => c.type === 'page:tabs', ); expect(tabItems(tabs).map((t: any) => t.value)).toEqual(['details', 'timeline']); - expect(tabItems(tabs)[0].label).toBe('Details'); + expect(tabItems(tabs)[0].label).toBe('Overview'); expect(tabItems(tabs)[0].children[0].type).toBe('record:details'); // The Timeline tab is the one stream: a record:activity (objectstack#27055). expect(tabItems(tabs)[1].children.map((c: any) => c.type)).toEqual(['record:activity']); @@ -330,16 +330,24 @@ describe('buildDefaultPageSchema', () => { ], }); const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); - // Details, Related, then the Timeline — 动态 is last for every object - // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(tabItems(tabs)).toHaveLength(3); - expect(tabItems(tabs)[1].label).toBe('Related'); - expect(tabItems(tabs)[2].value).toBe('timeline'); - expect(tabItems(tabs)[1].children).toHaveLength(2); + // Overview, one tab per related list (objectstack#35595), then the + // Timeline — 动态 is last for every object (objectstack#34590). + expect(tabItems(tabs).map((t: any) => t.value)).toEqual([ + 'details', + 'related:task.lead_id', + 'related:note.parent_id', + 'timeline', + ]); + expect(tabItems(tabs)[1].label).toBe('Tasks'); + // A list without a title is labelled with its object name. + expect(tabItems(tabs)[2].label).toBe('note'); + expect(tabItems(tabs)[1].children).toHaveLength(1); expect(tabItems(tabs)[1].children[0].type).toBe('record:related_list'); expect(props(tabItems(tabs)[1].children[0]).objectName).toBe('task'); expect(props(tabItems(tabs)[1].children[0]).relationshipField).toBe('lead_id'); expect(props(tabItems(tabs)[1].children[0]).limit).toBe(10); + // A tab holds ONE table: no tab merges two lists, so each can carry its count. + expect(tabItems(tabs).filter((t: any) => t.children.filter((c: any) => c.type === 'record:related_list').length > 1)).toEqual([]); }); it('draws an isPrimary related list as a body table of the Details tab (objectstack#27055)', () => { @@ -349,11 +357,11 @@ describe('buildDefaultPageSchema', () => { ], }); const labels = tabItems(tabs).map((t: any) => t.label); - expect(labels).toEqual(['Details', 'Activity stream']); + expect(labels).toEqual(['Overview', 'Activity stream']); expect(tabItems(tabs)[0].children.map((c: any) => c.type)).toContain('record:related_list'); }); - it('draws primary lists in the body and collapses the rest into Related', () => { + it('draws primary lists in the body and gives each other list a tab of its own (objectstack#35595)', () => { const tabs = buildDefaultTabs(leadDef, { related: [ { objectName: 'opportunity', relationshipField: 'lead_id', title: 'Opportunities', isPrimary: true }, @@ -362,14 +370,14 @@ describe('buildDefaultPageSchema', () => { ], }); const labels = tabItems(tabs).map((t: any) => t.label); - // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) - expect(labels).toEqual(['Details', 'Related', 'Activity stream']); - const related = tabItems(tabs).find((t: any) => t.label === 'Related'); - expect(related.children).toHaveLength(2); - expect(related.children.map((c: any) => props(c).objectName)).toEqual(['task', 'note']); + expect(labels).toEqual(['Overview', 'Tasks', 'Notes', 'Activity stream']); + expect(tabItems(tabs).slice(1, 3).map((t: any) => t.children.map((c: any) => props(c).objectName))).toEqual([ + ['task'], + ['note'], + ]); }); - it('emits no reference rail and no aside region, keeping the Related tab', () => { + it('emits no reference rail and no aside region, keeping the lists as tabs', () => { const page = buildDefaultPageSchema(leadDef, { related: [ { objectName: 'task', relationshipField: 'lead_id' }, @@ -380,8 +388,9 @@ describe('buildDefaultPageSchema', () => { // (objectstack#27055, ADR-0085). expect(page.regions.map((r: any) => r.name)).toEqual(['main']); const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); - const labels = tabItems(tabs).map((t: any) => t.label); - expect(labels).toContain('Related'); + const values = tabItems(tabs).map((t: any) => t.value); + expect(values).toContain('related:task.lead_id'); + expect(values).toContain('related:note.parent_id'); }); it('the timeline is ONE stream: no Activity or History tab (objectstack#27055)', () => { @@ -402,12 +411,12 @@ describe('buildDefaultPageSchema', () => { const related = [{ objectName: 'task', relationshipField: 'lead_id' }]; const worked = { ...leadDef, stageField: 'status' } as ObjectDefLike; const workedTabs = buildDefaultPageSchema(worked, { related }).regions[0].components.find((c: any) => c.type === 'page:tabs'); - expect(tabItems(workedTabs).map((t: any) => t.value)).toEqual(['details', 'related', 'timeline']); + expect(tabItems(workedTabs).map((t: any) => t.value)).toEqual(['details', 'related:task.lead_id', 'timeline']); const plainTabs = buildDefaultPageSchema(leadDef, { related }).regions[0].components.find((c: any) => c.type === 'page:tabs'); - expect(tabItems(plainTabs).map((t: any) => t.value)).toEqual(['details', 'related', 'timeline']); + expect(tabItems(plainTabs).map((t: any) => t.value)).toEqual(['details', 'related:task.lead_id', 'timeline']); }); - it('Details / Related / Approvals / Timeline tab order is stable (objectstack#34590)', () => { + it('Overview / the lists / Approvals / Timeline tab order is stable (objectstack#34590, objectstack#35595)', () => { const page = buildDefaultPageSchema(leadDef, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], approvals: { count: 1 }, @@ -415,8 +424,8 @@ describe('buildDefaultPageSchema', () => { const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) expect(tabItems(tabs).map((t: any) => t.label)).toEqual([ - 'Details', - 'Related', + 'Overview', + 'task', 'Approvals', 'Activity stream', ]); @@ -475,7 +484,7 @@ describe('buildDefaultPageSchema', () => { expect(has('record:path')).toBe(false); }); - it('details slot replaces only the Details tab body, keeps other tabs', () => { + it('details slot replaces only the Overview tab body, keeps other tabs', () => { const page = buildDefaultPageSchema(leadDef, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], slots: { details: { type: 'div', id: 'custom-details' } }, @@ -483,8 +492,8 @@ describe('buildDefaultPageSchema', () => { const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) expect(tabItems(tabs).map((t: any) => t.label)).toEqual([ - 'Details', - 'Related', + 'Overview', + 'task', 'Activity stream', ]); expect(tabItems(tabs)[0].children).toEqual([{ type: 'div', id: 'custom-details' }]); @@ -559,15 +568,14 @@ describe('buildDefaultPageSchema', () => { expect(types).toContain('record:path'); }); - it('buildDefaultTabs emits Details/Related/Timeline in order (objectstack#34590)', () => { + it('buildDefaultTabs emits Overview / the lists / Timeline in order (objectstack#34590, objectstack#35595)', () => { const tabs = buildDefaultTabs(leadDef, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], }); expect(tabs.type).toBe('page:tabs'); - // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) expect(tabItems(tabs).map((t: any) => t.label)).toEqual([ - 'Details', - 'Related', + 'Overview', + 'task', 'Activity stream', ]); }); @@ -592,25 +600,23 @@ describe('buildDefaultPageSchema', () => { expect(JSON.stringify(page)).not.toContain('record:attachments'); }); - it('enable.files → the Related tab closes with record:attachments (objectstack#27055)', () => { + it('enable.files → an Attachments tab of its own holding record:attachments (objectstack#35595)', () => { const page = buildDefaultPageSchema(filesDef); const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); - // Attachments sit at the foot of 关联, as they sit at the foot of the - // related column — no tab of their own. - expect(tabItems(tabs).some((t: any) => t.value === 'attachments')).toBe(false); - const related = tabItems(tabs).find((t: any) => t.value === 'related'); - expect(related.label).toBe('Related'); - expect(related.children).toEqual([{ type: 'record:attachments' }]); + const attachments = tabItems(tabs).find((t: any) => t.value === 'attachments'); + expect(attachments.label).toBe('Attachments'); + expect(attachments.children).toEqual([{ type: 'record:attachments' }]); + // CONTROL: no merged Related tab carries them any more. + expect(tabItems(tabs).some((t: any) => t.value === 'related')).toBe(false); }); - it('attachments follow the side lists in the Related tab', () => { + it('the Attachments tab follows the lists\' tabs and precedes the Timeline (objectstack#35595)', () => { const tabs = buildDefaultTabs(filesDef, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], }); - // The Timeline comes last, as for every object (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). - expect(tabItems(tabs).map((t: any) => t.value)).toEqual(['details', 'related', 'timeline']); - const related = tabItems(tabs).find((t: any) => t.value === 'related'); - expect(related.children.map((c: any) => c.type)).toEqual(['record:related_list', 'record:attachments']); + expect(tabItems(tabs).map((t: any) => t.value)).toEqual(['details', 'related:task.lead_id', 'attachments', 'timeline']); + const task = tabItems(tabs).find((t: any) => t.value === 'related:task.lead_id'); + expect(task.children.map((c: any) => c.type)).toEqual(['record:related_list']); }); it('hideAttachments suppresses the tab', () => { @@ -655,18 +661,23 @@ describe('buildDefaultPageSchema', () => { expect(tab.children).toEqual([{ type: 'record:approvals', properties: { ...nodePayload } }]); }); - it('the Approvals tab sits after Related and before the Timeline, for every object (objectstack#27524, objectstack#34590)', () => { + it('the Approvals tab sits after the lists and Attachments and before the Timeline, for every object (objectstack#34590, objectstack#35595)', () => { const plain = buildDefaultTabs(leadDef, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], approvals: { node: nodePayload }, }); - // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) - expect(tabItems(plain).map((t: any) => t.value)).toEqual(['details', 'related', 'approvals', 'timeline']); + expect(tabItems(plain).map((t: any) => t.value)).toEqual(['details', 'related:task.lead_id', 'approvals', 'timeline']); const worked = buildDefaultTabs({ ...leadDef, enable: { files: true } }, { related: [{ objectName: 'task', relationshipField: 'lead_id' }], approvals: { node: nodePayload }, }); - expect(tabItems(worked).map((t: any) => t.value)).toEqual(['details', 'related', 'approvals', 'timeline']); + expect(tabItems(worked).map((t: any) => t.value)).toEqual([ + 'details', + 'related:task.lead_id', + 'attachments', + 'approvals', + 'timeline', + ]); }); it('a details slot override keeps the Approvals tab', () => { @@ -959,22 +970,34 @@ describe('buildDefaultTabs — stable tab values (objectui#2257)', () => { const relA = { title: 'Invoices', objectName: 'invoice', relationshipField: 'account', isPrimary: true }; const relB = { title: 'Notes', objectName: 'note', relationshipField: 'account' }; - it('emits semantic values: details (primary in its body) / related (rest) / timeline', () => { + it('emits semantic values: details (primary in its body) / related:. (each other list) / timeline', () => { const tabs = buildDefaultTabs(undefined, { related: [relA, relB], }); - // objectstack#34590 — 动态 last (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」). + // objectstack#35595 — each list its own tab; 动态 last (objectstack#34590). expect(tabItems(tabs).map((i: any) => i.value)).toEqual([ - 'details', 'related', 'timeline', + 'details', 'related:note.account', 'timeline', ]); }); it('values stay stable when the related list shrinks (URL tokens must not shift)', () => { const both = buildDefaultTabs(undefined, { related: [relA, relB] }); const onlyB = buildDefaultTabs(undefined, { related: [relB] }); - // 'related' names the same (stacked) tab in both trees — an index value - // would have pointed at 'related:invoice' before and 'related' after. - expect(tabItems(both).some((i: any) => i.value === 'related')).toBe(true); - expect(tabItems(onlyB).some((i: any) => i.value === 'related')).toBe(true); + // The value names the relationship, not a position: the Notes tab keeps + // its token whether or not Invoices is passed. + expect(tabItems(both).some((i: any) => i.value === 'related:note.account')).toBe(true); + expect(tabItems(onlyB).some((i: any) => i.value === 'related:note.account')).toBe(true); + }); + + it('two lists over one child object stay two tabs (objectstack#35595)', () => { + const tabs = buildDefaultTabs(undefined, { + related: [ + { objectName: 'lead', relationshipField: 'converted_contact', title: 'Leads (converted)' }, + { objectName: 'lead', relationshipField: 'duplicate_contact', title: 'Leads (duplicate)' }, + ], + }); + expect(tabItems(tabs).map((i: any) => i.value)).toEqual([ + 'details', 'related:lead.converted_contact', 'related:lead.duplicate_contact', 'timeline', + ]); }); }); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.switches-27052.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.switches-27052.test.ts index 2339f810547..9f82e7c533c 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.switches-27052.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.switches-27052.test.ts @@ -43,9 +43,10 @@ const tabValues = (def: any) => buildDefaultTabs(def, { related: RELATED }).prop describe('动态 is a panel for every object (objectstack#27524, Target 5)', () => { it('the strip places Timeline last for a worked object and a container alike (objectstack#34590)', () => { - // (objectstack#34590 supersedes objectstack#27524 Targets 5 and 8: 「「动态」在最后」) - expect(tabValues(worked)).toEqual(['details', 'related', 'timeline']); - expect(tabValues(container)).toEqual(['details', 'related', 'timeline']); + // A tab per side list (objectstack#35595); 动态 last (objectstack#34590). + // The worked object has files on: its 附件 tab follows the lists. + expect(tabValues(worked)).toEqual(['details', 'related:task.parent_id', 'attachments', 'timeline']); + expect(tabValues(container)).toEqual(['details', 'related:task.parent_id', 'timeline']); }); it('the object-derived default and the column switches are gone from the module', () => { diff --git a/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.test.ts index 566a2320fac..ce0fc8971ed 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/recordPageColumns.test.ts @@ -113,8 +113,8 @@ describe('recordPageColumnOfTab — every synthesized tab has a column', () => { const tabs = buildDefaultTabs(leadDef, maximal); const values = tabs.properties.items.map((item: any) => item.value); // The maximal synthesis really emitted the whole strip. - // `attachments` rides the Related tab now (objectstack#27055). - expect(values).toEqual(expect.arrayContaining(['details', 'related', 'approvals', 'timeline'])); + // objectstack#35595 — a tab per side list, then 附件 / 审批 / 动态. + expect(values).toEqual(['details', 'related:note.parent_id', 'related:call.lead_id', 'attachments', 'approvals', 'timeline']); for (const value of values) expect(recordPageColumnOfTab(value)).not.toBeNull(); }); @@ -130,17 +130,23 @@ describe('buildDefaultPageColumns (objectstack#26678)', () => { const page = buildDefaultPageSchema(leadDef, maximal); const columns = buildDefaultPageColumns(page); expect(columns).not.toBeNull(); - // The header is every node before the strip — the same nodes the strip draws above it. + // The nodes before the strip split in two (objectstack#35595): the header, + // and the highlights / stage path the 概览 tab draws at its top. const main = page.regions.find((r: any) => r.name === 'main'); const tabIndex = main.components.findIndex((n: any) => n.type === 'page:tabs'); - expect(columns!.header).toEqual(main.components.slice(0, tabIndex)); + const before = main.components.slice(0, tabIndex); + expect([...columns!.header, ...columns!.strip]).toEqual(expect.arrayContaining(before)); + expect(columns!.header.length + columns!.strip.length).toBe(before.length); expect(types(columns!.header)[0]).toBe('page:header'); + for (const type of types(columns!.strip)) expect(['record:highlights', 'record:path']).toContain(type); + expect(types(columns!.header)).not.toContain('record:highlights'); + expect(types(columns!.header)).not.toContain('record:path'); // The primary list is the record's body: a table in the details column // (objectstack#27055, Target 8). expect(types(columns!.details)).toEqual(['record:details', 'record:related_list']); // The one stream (objectstack#27055): a record:activity. expect(types(columns!.timeline)).toEqual(['record:activity']); - // The Related tab (side lists, attachments at its foot), then Approvals. + // The side lists' tabs, then 附件 and 审批. expect(types(columns!.related)).toEqual([ 'record:related_list', 'record:related_list', @@ -153,7 +159,7 @@ describe('buildDefaultPageColumns (objectstack#26678)', () => { it('places every node the page holds exactly once', () => { const page = buildDefaultPageSchema(leadDef, maximal); const columns = buildDefaultPageColumns(page)!; - const placed = [...columns.header, ...columns.details, ...columns.timeline, ...columns.related]; + const placed = [...columns.header, ...columns.strip, ...columns.details, ...columns.timeline, ...columns.related]; const main = page.regions.find((r: any) => r.name === 'main'); const tabs = main.components.find((n: any) => n.type === 'page:tabs'); const expected = [ diff --git a/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow-28469.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow-28469.test.ts deleted file mode 100644 index 186e1289bc4..00000000000 --- a/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow-28469.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * objectstack#28469 — the record page's tab row puts the related lists with - * records first and sinks the empty ones into 「+N ▾」, the rule the right - * column already applies to its panels (objectstack#27524, Target 2): a stable - * partition of the reader's arrangement, an unknown count kept in place, an - * empty list never on the row unless it is the active tab, which then takes - * the row's last slot. - */ - -import { describe, it, expect } from 'vitest'; -import { arrangeRecordTabRow, layoutRecordTabRow, partitionRecordTabsByRecords } from '../recordTabRow'; - -interface Tab { - id: string; - count?: number | null; -} - -// The HotCRM contact the card was read on: 7 inbound lists in arrangement order. -const PANELS: Tab[] = [ - { id: 'attendee', count: 7 }, - { id: 'lead.converted_contact', count: 0 }, - { id: 'lead.duplicate_contact', count: 0 }, - { id: 'case', count: 2 }, - { id: 'contract', count: 1 }, - { id: 'quote', count: 2 }, - { id: 'campaign_member', count: 3 }, -]; -const LEAD: Tab[] = [{ id: 'overview' }, { id: 'timeline', count: 0 }]; -const HIDDEN: Tab[] = [{ id: 'opportunity', count: 0 }]; -const GAP = 16; -const MORE = 40; -const widthOf = (tab: Tab) => (tab.id === 'overview' ? 60 : tab.id === 'timeline' ? 70 : 80); - -/** The row the page draws: partition, arrange, lay out — what each slot and the dropdown hold, by id. */ -function drawRow(panels: readonly Tab[], available: number, activeId = 'overview') { - const { withRecords, empty } = partitionRecordTabsByRecords(panels); - const { row, empty: folded } = arrangeRecordTabRow([...LEAD, ...withRecords], empty, activeId); - const layout = layoutRecordTabRow({ - widths: row.map(widthOf), - available, - gap: GAP, - moreWidth: MORE, - activeIndex: Math.max(0, row.findIndex((tab) => tab.id === activeId)), - alwaysInDropdown: folded.length + HIDDEN.length, - }); - return { - row: layout.shown.map((index) => row[index].id), - dropdown: [...layout.overflow.map((index) => row[index].id), ...folded.map((t) => t.id), ...HIDDEN.map((t) => t.id)], - }; -} - -describe('the record tab row puts lists with records first (objectstack#28469)', () => { - it('counts [7, 0, 0, 2, 1, 2, 3]: the non-empty tabs on the row; the dropdown lists the overflowed ones, then the empty, then the hidden', () => { - // Budget 500 - 40 - 16 = 444: 概览 60 + 动态 70 + three panels of 80, with gaps = 434. - expect(drawRow(PANELS, 500)).toEqual({ - row: ['overview', 'timeline', 'attendee', 'case', 'contract'], - dropdown: ['quote', 'campaign_member', 'lead.converted_contact', 'lead.duplicate_contact', 'opportunity'], - }); - }); - - it('an empty list never takes a slot, even on a row with room for every tab', () => { - expect(drawRow(PANELS, 2000)).toEqual({ - row: ['overview', 'timeline', 'attendee', 'case', 'contract', 'quote', 'campaign_member'], - dropdown: ['lead.converted_contact', 'lead.duplicate_contact', 'opportunity'], - }); - }); - - it('the partition is stable: the arrangement decides the order within each group', () => { - const { withRecords, empty } = partitionRecordTabsByRecords(PANELS); - expect(withRecords.map((t) => t.id)).toEqual(['attendee', 'case', 'contract', 'quote', 'campaign_member']); - expect(empty.map((t) => t.id)).toEqual(['lead.converted_contact', 'lead.duplicate_contact']); - }); - - it('a count not known yet (null, absent) counts as non-empty and stays where the arrangement puts it', () => { - const panels: Tab[] = [{ id: 'a', count: null }, { id: 'b', count: 0 }, { id: 'c' }, { id: 'd', count: 4 }]; - const { withRecords, empty } = partitionRecordTabsByRecords(panels); - expect(withRecords.map((t) => t.id)).toEqual(['a', 'c', 'd']); - expect(empty.map((t) => t.id)).toEqual(['b']); - expect(drawRow(panels, 2000).row).toEqual(['overview', 'timeline', 'a', 'c', 'd']); - }); - - it('an active empty tab (a ?related= link to an empty list) is on the row, in its last slot', () => { - // Narrow: the active empty tab takes the last slot, displacing the panels that no longer fit. - expect(drawRow(PANELS, 500, 'lead.duplicate_contact')).toEqual({ - row: ['overview', 'timeline', 'attendee', 'case', 'lead.duplicate_contact'], - dropdown: ['contract', 'quote', 'campaign_member', 'lead.converted_contact', 'opportunity'], - }); - // Wide: after every list with records. - expect(drawRow(PANELS, 2000, 'lead.converted_contact')).toEqual({ - row: ['overview', 'timeline', 'attendee', 'case', 'contract', 'quote', 'campaign_member', 'lead.converted_contact'], - dropdown: ['lead.duplicate_contact', 'opportunity'], - }); - }); - - it('a row whose panels are all empty or all with records changes nothing else', () => { - const allEmpty = PANELS.map((t) => ({ ...t, count: 0 })); - expect(drawRow(allEmpty, 2000)).toEqual({ row: ['overview', 'timeline'], dropdown: [...PANELS.map((t) => t.id), 'opportunity'] }); - const allFull = PANELS.map((t) => ({ ...t, count: 1 })); - expect(drawRow(allFull, 2000).row).toEqual(['overview', 'timeline', ...PANELS.map((t) => t.id)]); - }); -}); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow.widthOnly-35595.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow.widthOnly-35595.test.ts new file mode 100644 index 00000000000..a2eff659967 --- /dev/null +++ b/ui/packages/plugin-detail/src/synth/__tests__/recordTabRow.widthOnly-35595.test.ts @@ -0,0 +1,93 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35595 — the record tab row folds by WIDTH only: every related + * list is a candidate for the row in its order, whether or not it has + * records, and the tabs that do not fit go into 「更多 N ▾」. Supersedes + * objectstack#28469, which sank the empty lists into the dropdown even on a + * row with room for them (that partition, `partitionRecordTabsByRecords` / + * `arrangeRecordTabRow`, is retired with this card). + */ + +import { describe, it, expect } from 'vitest'; +import * as recordTabRow from '../recordTabRow'; +import { layoutRecordTabRow } from '../recordTabRow'; + +interface Tab { + id: string; + count?: number | null; +} + +// The HotCRM contact the old card was read on: 7 inbound lists in their order. +const PANELS: Tab[] = [ + { id: 'attendee', count: 7 }, + { id: 'lead.converted_contact', count: 0 }, + { id: 'lead.duplicate_contact', count: 0 }, + { id: 'case', count: 2 }, + { id: 'contract', count: 1 }, + { id: 'quote', count: 2 }, + { id: 'campaign_member', count: 3 }, +]; +const HIDDEN: Tab[] = [{ id: 'opportunity', count: 0 }]; +const GAP = 16; +const MORE = 40; +const widthOf = (tab: Tab) => (tab.id === 'overview' ? 60 : tab.id === 'timeline' ? 70 : 80); + +/** The row the page draws: 概览, the lists in order, 动态 last — what each slot and the dropdown hold, by id. */ +function drawRow(panels: readonly Tab[], available: number, activeId = 'overview', hidden: readonly Tab[] = HIDDEN) { + const row: Tab[] = [{ id: 'overview' }, ...panels, { id: 'timeline', count: 2 }]; + const layout = layoutRecordTabRow({ + widths: row.map(widthOf), + available, + gap: GAP, + moreWidth: MORE, + activeIndex: Math.max(0, row.findIndex((tab) => tab.id === activeId)), + alwaysInDropdown: hidden.length, + }); + return { + row: layout.shown.map((index) => row[index].id), + dropdown: [...layout.overflow.map((index) => row[index].id), ...hidden.map((t) => t.id)], + }; +} + +describe('the record tab row folds by width only (objectstack#35595)', () => { + it('a row with room for every tab shows every list, the empty ones in their place', () => { + expect(drawRow(PANELS, 2000, 'overview', [])).toEqual({ + row: ['overview', ...PANELS.map((t) => t.id), 'timeline'], + dropdown: [], + }); + }); + + it('a narrow row keeps the front of the order and folds the rest, empty or not, in order', () => { + // Budget 500 - 40 - 16 = 444: 概览 60 + four lists of 80, with gaps = 444. + expect(drawRow(PANELS, 500, 'overview', [])).toEqual({ + row: ['overview', 'attendee', 'lead.converted_contact', 'lead.duplicate_contact', 'case'], + dropdown: ['contract', 'quote', 'campaign_member', 'timeline'], + }); + }); + + it('CONTROL: the counts never decide a slot — the same row with every count 0 or every count 3 lays out alike', () => { + const allEmpty = PANELS.map((t) => ({ ...t, count: 0 })); + const allFull = PANELS.map((t) => ({ ...t, count: 3 })); + expect(drawRow(allEmpty, 500)).toEqual(drawRow(PANELS, 500)); + expect(drawRow(allFull, 500)).toEqual(drawRow(PANELS, 500)); + }); + + it('the active tab takes the last slot when it would have folded', () => { + expect(drawRow(PANELS, 500, 'quote', [])).toEqual({ + row: ['overview', 'attendee', 'lead.converted_contact', 'lead.duplicate_contact', 'quote'], + dropdown: ['case', 'contract', 'campaign_member', 'timeline'], + }); + }); + + it('the records-first partition is retired from the module', () => { + expect('partitionRecordTabsByRecords' in recordTabRow).toBe(false); + expect('arrangeRecordTabRow' in recordTabRow).toBe(false); + }); +}); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index 895f1343e4c..baa590717aa 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -173,8 +173,9 @@ export interface BuildPageOptions { */ headerActions?: any[]; /** - * Related child objects. When non-empty, the synthesizer adds a - * "Related" tab containing one `record:related_list` per entry. + * Related child objects. Each entry is one `record:related_list`: a table + * of the 概览 tab when it is the record's body (`isBody`), otherwise a tab + * of its own (objectstack#35595). * * - `objectName` and `relationshipField` are required. * - `title` overrides the default child-object label. @@ -905,13 +906,13 @@ export function bodyTablePlacement( } /** - * Sub-builder: the `page:tabs` node. Emits the Details tab, always first, - * then the Related tab, the Approvals tab and the Timeline tab (the one - * stream, objectstack#27055: field changes join it under its Changes filter, - * so there is no History tab), each of those three only when the options give - * it content. The order is stable: Timeline sits last for every object — the - * 动态 panel is the last panel of the record page's right column - * (objectstack#34590, superseding objectstack#27524 Target 5's 动态-first). + * Sub-builder: the `page:tabs` node. Emits the 概览 tab (value `details`), + * always first, then one tab per ordinary related list, the Attachments tab, + * the Approvals tab and the Timeline tab (the one stream, objectstack#27055: + * field changes join it under its Changes filter, so there is no History + * tab), each after the first only when the options give it content + * (objectstack#35595). The order is stable: Timeline sits last for every + * object (objectstack#34590). * * Useful for slotted authors who want to add a custom tab — they can * call `buildDefaultTabs(def, opts)` and splice their tab into @@ -974,7 +975,7 @@ function synthTabs( }); // objectstack#27055, Target 8 — a list that is the record's own body // (`isBody`, else `isPrimary`) is a table section of the Details tab; every - // other list is a side card in the one `Related` tab. Body tables keep the + // other list is a tab of its own (objectstack#35595). Body tables keep the // order the host passed (the object's `relatedLists`, then the derived // order — objectstack#27069), unless a field group places one // (`bodyTablePlacement`). @@ -982,41 +983,44 @@ function synthTabs( const isBody = (rel: (typeof related)[number]) => rel.isBody ?? rel.isPrimary === true; const bodies = related.filter(isBody).map((rel) => relatedNode(rel, BODY_TABLE_PAGE_SIZE)); const sides = related.filter((rel) => !isBody(rel)); + // objectstack#35595 — the first tab is 「概览」 (the token the tab strip + // localizes as `detail.recordTabOverview`); its value stays `details`, the + // URL token a `?tab=` link already names. const items: any[] = [ { - label: 'Details', + label: 'Overview', value: 'details', children: bodyTablePlacement(def, options.sections, bodyHiddenFields, bodies), }, ]; - // objectstack#27055, Target 3 — the timeline stream is ONE tab for every - // object (objectstack#27524, Target 5: 动态 is a panel, for every object — - // no object-derived default places it). objectstack#34590 — the strip is - // 详情 / 关联 / (审批) / 动态: the stream comes LAST, as the laid-out page - // draws it last in its right column, its stack and its tab row - // (「「动态」在最后」, superseding objectstack#27524 Targets 5 and 8's - // 动态-second). Attachments close the Related tab, as they close the related - // panels. The stream tab's token is `Activity stream`, which the strip reads - // as `detail.timeline` (「动态」); a bare `Timeline` is an author's word. + // objectstack#35595 — EVERY ordinary related list is a tab of its own, in + // the order the host passed (the object's `relatedLists`, then the derived + // order), whether or not it has records: one table, one tab, one count. The + // value is `related:.`, the list's relationship id, so two + // lists over one child object stay two tabs. A tab merging several tables + // is an authored page's (it carries no count, `page:tabs`). Then + // Attachments, Approvals and the timeline stream, each its own tab + // (objectstack#34590 kept the stream last). The stream tab's token is + // `Activity stream`, which the strip reads as `detail.timeline` (「动态」); a + // bare `Timeline` is an author's word. const timeline = options.timeline ?? (options.hideDiscussion ? [] : [buildDefaultTimeline()]); + for (const rel of sides) { + items.push({ + label: rel.title ?? rel.objectName, + value: `related:${rel.objectName}.${rel.relationshipField}`, + children: [relatedNode(rel)], + }); + } // Attachments (objectstack#4358) — for `enable.files: true` objects; the // tab strip's count badge reads the `record:attachments` node. - const relatedChildren = [ - ...sides.map((rel) => relatedNode(rel)), - ...(def?.enable?.files === true && !options.hideAttachments ? [buildDefaultAttachments()] : []), - ]; - if (relatedChildren.length > 0) { - items.push({ label: 'Related', value: 'related', children: relatedChildren }); + if (def?.enable?.files === true && !options.hideAttachments) { + items.push({ label: 'Attachments', value: 'attachments', children: [buildDefaultAttachments()] }); } // Approvals tab (objectui#3461) — emitted only when the host reports the // record actually HAS approval requests, so approval-free records carry no - // dead tab. A peer of Details/Related for the same reason as Attachments - // below: footer placement buried the one thing a submitter opens the - // record to learn ("who is this waiting on"). The English label localizes - // in the tab strip, which reads the pack key for a well-known token - // (`detail.approvalsPanelTitle` → 审批 / 承認 / Aprobaciones …). That claim - // used to name `KNOWN_LABEL_DICT`, which shipped zh arms only and so was - // true for Chinese and silently false everywhere else — objectui#4645. + // dead tab. The English label localizes in the tab strip, which reads the + // pack key for a well-known token (`detail.approvalsPanelTitle` → 审批 / + // 承認 / Aprobaciones …) — objectui#4645. if (options.approvals) { items.push({ label: 'Approvals', @@ -1025,7 +1029,7 @@ function synthTabs( children: [componentNode('record:approvals', { ...(options.approvals.node || {}) })], }); } - // objectstack#34590 — the 动态 tab closes the strip (see above). + // objectstack#34590 — the 动态 tab closes the strip. if (timeline.length > 0) items.push({ label: 'Activity stream', value: 'timeline', children: timeline }); return componentNode('page:tabs', { items }); } diff --git a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts index 5f0608439d3..832c10e4090 100644 --- a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts +++ b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts @@ -16,17 +16,19 @@ * one rule wherever it is drawn (the page, the split pane, the overlay drawer, * the maximized pane, a phone): * - * - 760 px and up: details | the right column (320 px) — the related - * panels, then the 动态 panel last (objectstack#34590); + * - 760 px and up: details | the right rail (320 px) — the 概览 tab's + * summary of the other tabs (objectstack#35596: 审批, 附件, 最近动态, then + * the related lists with records); * - 1120 px and up: the same, wide — the details field grid takes three - * columns, the right column 380 px, the 动态 panel five entries; - * - below 760 px: ONE column — the details sections, then the right - * column's panels in their order. + * columns, the right rail 380 px; + * - below 760 px: ONE column — the details sections, then the rail. * - * (Container widths — see the two constants for how they are derived.) There - * is no tabbed tier: the strip's blocks are always laid out - * (objectstack#27524 retired it with the three-column tier and the related - * rail), and the 动态 stream is a panel, never a column. + * (Container widths — see the two constants for how they are derived.) Above + * the columns sit the header, the record's tab row — 概览, one tab per related + * list, 附件, 审批, 动态 (objectstack#35595) — and, on 概览 only, the strip + * (`record:path`, `record:highlights`) across the whole width. Every other + * tab draws its block in full in place of the columns; the 动态 stream is a + * tab, never a column. * * ## Why the layout is derived, never authored * @@ -36,11 +38,11 @@ * author — or an AI — could write and the spec could not judge, and a Studio * seed carrying it would be refused at save. The layout is therefore read off * the synthesized page itself, by the stable semantic `value` every tab item - * carries (`buildDefaultTabs`, objectui#2257): `details` is the details - * column, `timeline` (the one stream, objectstack#27055) is the right - * column's 动态 panel, and `related`, `approvals` and `attachments` are its - * panels before it (objectstack#34590: 动态 is drawn last, and the strip - * lists it last too). The synthesized page has one region (`main`); a page with + * carries (`buildDefaultTabs`, objectui#2257): `details` is the 概览 tab + * (its path and highlights are the strip, the rest the details column), + * `timeline` (the one stream, objectstack#27055) is the 动态 tab, and each + * `related:object.field`, `approvals` and `attachments` is a tab of its own + * (objectstack#35595; 动态 last, objectstack#34590). The synthesized page has one region (`main`); a page with * any other region is not the synthesized page (objectstack#27055 removed the * opt-in rail and the `rightRail` slot that used to add an `aside`). * @@ -168,11 +170,17 @@ export function recordPageColumnOfTab(value: unknown): RecordPageColumn | null { export interface DefaultPageColumns { /** * The record header: every node the page places before its tab strip - * (`page:header`, the actions / alerts slots, highlights, the stage path). - * The same nodes an authored strip draws above it — one header for every - * tier. + * (`page:header`, the actions / alerts slots) but the strip below. The same + * nodes an authored strip draws above it — one header for every tier. */ header: any[]; + /** + * The highlight strip and the stage path the page places before its tab + * strip (`record:highlights`, `record:path`), in their order. objectstack#35595: + * they are the 概览 tab's, drawn at its top across the whole width, and on no + * other tab. + */ + strip: any[]; /** The Details tab's body. */ details: any[]; /** @@ -191,6 +199,11 @@ const asNode = (value: unknown): PageNode | null => const nodeList = (value: unknown): any[] => (Array.isArray(value) ? value.filter((n) => n != null) : []); +/** The node types the 概览 tab draws at its top (objectstack#35595). */ +const STRIP_NODE_TYPES: ReadonlySet = new Set(['record:highlights', 'record:path']); + +const isStripNode = (node: unknown): boolean => STRIP_NODE_TYPES.has(asNode(node)?.type); + /** * Partition a synthesized default record page (`buildDefaultPageSchema`'s * output, after any host pruning) into its header, details, 动态 and related @@ -235,8 +248,10 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul else relatedLists.push(...children); } + const before = components.slice(0, tabIndex); return { - header: components.slice(0, tabIndex), + header: before.filter((node) => !isStripNode(node)), + strip: before.filter(isStripNode), details, timeline: [...components.slice(tabIndex + 1), ...timelineTabs], related: [...relatedLists, ...relatedPanels], diff --git a/ui/packages/plugin-detail/src/synth/recordTabRow.ts b/ui/packages/plugin-detail/src/synth/recordTabRow.ts index c6f3853ba32..331d8824709 100644 --- a/ui/packages/plugin-detail/src/synth/recordTabRow.ts +++ b/ui/packages/plugin-detail/src/synth/recordTabRow.ts @@ -9,7 +9,7 @@ /** * The record page's tab row, laid out by the width it has * (objectstack#27524, Target 8): 「概览」, then one tab per panel, as many as - * fit; the rest go into the 「+N ▾」 dropdown. + * fit; the rest go into the 「更多 N ▾」 dropdown. * * Pure, so the rule reads and tests apart from any layout engine: the * component measures its tabs and its container, and asks this which tabs @@ -25,9 +25,9 @@ * dropdown, it takes the row's last slot and the tab it displaced goes * into the dropdown instead. * - * Which tabs are candidates for the row at all is {@link arrangeRecordTabRow}'s - * answer (objectstack#28469): the related lists with records come first, and - * the empty ones wait in the dropdown. + * Every tab is a candidate for the row, in its order, whether its list has + * records or not (objectstack#35595, superseding objectstack#28469's + * empty-lists-in-the-dropdown): the width is the only thing that folds a tab. */ export interface RecordTabRowLayoutInput { /** Each tab's width, in the row's order; index 0 is 「概览」. */ @@ -36,7 +36,7 @@ export interface RecordTabRowLayoutInput { available: number; /** The space between two tabs, and between the last tab and the trigger. */ gap: number; - /** The dropdown trigger's width (「+N ▾」). */ + /** The dropdown trigger's width (「更多 N ▾」). */ moreWidth: number; /** The active tab's index into `widths`. */ activeIndex: number; @@ -86,51 +86,3 @@ export function layoutRecordTabRow(input: RecordTabRowLayoutInput): RecordTabRow const overflow = all.filter((index) => !chosen.has(index)); return { shown, overflow }; } - -/** What the arrangement reads of a tab: its id and its count. */ -export interface ArrangedRecordTab { - id: string; - /** The panel's count; absent or `null` while it is not known. */ - count?: number | null; -} - -/** - * The related panels' tabs split by whether their list has records - * (objectstack#28469, Target 1) — the rule the right column already applies to - * its panels (objectstack#27524, Target 2), so the two surfaces agree on the - * same lists. - * - * A stable partition of the reader's arrangement: every panel whose count is - * not `0` keeps its relative order (a reader's drag still decides among them), - * then every panel whose count is `0`, in the same order. A count that is not - * known yet (loading, or a refused read) is not `0`: that tab stays where the - * arrangement puts it. Computed when the row is drawn and never written back - * into the stored arrangement. - */ -export function partitionRecordTabsByRecords( - panels: readonly T[], -): { withRecords: T[]; empty: T[] } { - const withRecords: T[] = []; - const empty: T[] = []; - for (const panel of panels) (panel.count === 0 ? empty : withRecords).push(panel); - return { withRecords, empty }; -} - -/** - * The tabs the row may show and the empty tabs its dropdown lists - * (objectstack#28469, Targets 1 and 3). - * - * An empty list's tab never takes a slot on the row, even when the row has - * room for it — except the active one: a link that opens an empty list (a - * `?related=` deep link) keeps that tab on the row, after every other - * candidate, so {@link layoutRecordTabRow} draws it in the row's last slot. - */ -export function arrangeRecordTabRow( - tabs: readonly T[], - emptyTabs: readonly T[], - activeId: string, -): { row: T[]; empty: T[] } { - const active = emptyTabs.find((tab) => tab.id === activeId); - if (!active) return { row: [...tabs], empty: [...emptyTabs] }; - return { row: [...tabs, active], empty: emptyTabs.filter((tab) => tab !== active) }; -}