Skip to content

Commit 04f9861

Browse files
feat(record-page): a desktop comment panel beside the record, opened from a header icon; 动态 keeps system entries (#36075) (#36114)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu7W7AujnHuifjn8Luh1TnAA)_ repo:objectstack#1 · os-sales · session_01L6bhgXXdtDHm8mLZYX8Bsb Part of #36075 Clause-②: yes (widening): `@object-ui/plugin-detail` adds exports (`CommentsPanel`, `CommentsButton`, `CommentThread`, `CommentItem`, `CommentComposer`, `CommentHoverActions`, `useRecordComments`, `buildCommentThreads`, `latestRepliers`, `RecordCommentsInPanelContext`) and their types (`CommentsPanelProps`, `CommentsButtonProps`, `RecordCommentThreadProps`, `CommentItemProps`, `CommentItemActions`, `CommentComposerProps`, `CommentHoverActionsProps`, `CommentThreadData`, `RecordCommentsData`), and an optional `reservedWidth` on `useRecordPageTier`. `RichTextCommentInput` (exported) now takes the `Esc` that closes its @ list (`preventDefault` and `stopPropagation`), so nothing round it acts on that key. `RecordActivityTimeline` draws no chip group when it is handed no chips. `@object-ui/components` adds an optional `comments` slot to `RecordTopBar` and `NavigationOverlay`, and the drawer leaves an `Esc` pressed inside a `[data-owns-escape]` region to that region. `@object-ui/i18n` adds five keys to every pack: `detail.closeComments`, `detail.collapseReplies`, `detail.commentActions`, `detail.commentsEmptyHint`, `detail.resolveThread`. Nothing existing is removed or re-typed. Metadata-protocol: none ## 维护者速读 - 电脑端的记录页和记录抽屉,头部(编辑按钮左边)多了一个评论图标,旁边是这条记录的评论数(顶层评论条数;#36071 合并后改成未解决的线程数)。点一下打开评论栏,再点一下关上;开着还是关着,浏览器会记住,记录页和抽屉各记各的。 - 评论栏宽 380:顶上「评论」和 ✕,中间是评论线程(最早的在上),评论框固定在最下面。一条评论有回复时显示「N 条回复」和最近回复人的头像,点开在原地展开,下面有回复框;在任意一条上点「回复」会展开这个线程、光标直接进回复框。 - 鼠标移到一条评论上,右上角出现一排操作:回复、表情、更多(自己的评论才有编辑、删除)。「已解决」按钮已经做好,等 #36071 合并后再接上,现在不显示。 - 窗口 1280 及以上,评论栏放在记录右边,记录内容让出 380;窗口小于 1280,评论栏盖在记录右侧。抽屉默认宽 720,评论栏盖住整个抽屉内容(✕ 或 Esc 回到记录,焦点回到评论图标;从列表打开的抽屉也一样,抽屉本身不关);抽屉宽到 760 及以上才左右并排。 - 「动态」页签只剩系统条目(活动、字段变更),没有评论框,也没有「全部 / 活动 / 讨论」这三个筛选(卡上点名去掉的三个)。「变更」筛选照旧保留:记录开着字段历史时才有,点一下只看字段变更,再点一下回到全部。动态的数字也不再算评论。 - 只在平台默认记录页和只填插槽的页面上出现(方案 C,13:24Z)。完全手写的记录页不动:showcase 的 project-detail、sys-queue、sys-audit-log 三个页面照旧在页脚放讨论区;对象关了评论(`enable.feeds: false`)就没有图标。手机端这次不改,评论还在动态页签里,等 #36076。 ## What changes **The comment components** (`@object-ui/plugin-detail`, new `src/comments/`) - `useRecordComments()` reads the record's discussion off the host's `DiscussionContext` (the rows and the writes every feed block already gets) and returns the threads, the icon's count (`null` while unknown: loading, refused or failed), the loading, refused and failed states, and each write exactly where the host hands it. Nothing reads or writes any other way, so the phone's comment page (#36076) can reuse every piece. - `buildCommentThreads(items)`: the `comment` rows only, threads oldest first, replies oldest first; a reply to a reply joins its thread; a reply whose parent is not held (deleted) stays as a thread of its own, so a delete never hides another member's reply. - `CommentItem` (avatar, name, time, edited mark, text, reactions with the viewer's own marked; an inline editor where Esc cancels and Ctrl/⌘+Enter saves, the draft kept when the save is refused), `CommentThread` (`expand` for the panel, `summary` for the phone's list; actions handed out per comment through `renderActions`), `CommentComposer` (keeps the draft when the write is refused; `focusSignal` puts the caret in it), `CommentHoverActions` (the desktop's one action row), `CommentsPanel`, `CommentsButton`. Every face is #36070's shared `CommentAuthorAvatar`. - `RecordCommentsInPanelContext`: while the host sets it, the default page's `record:activity` stream (the 动态 tab and the 概览 rail's 最近动态 card) drops comment rows, its 全部 / 活动 / 讨论 chips and its composer (the 变更 chip stays, on #30074's rule, and pressed again goes back to every entry), ignores a refused or failed comments read, and the tab row's count probe (`RecordTimelineCountProbe`) counts the same rows. An authored `record:activity` is untouched. - **Esc** (L1-c rework at `09b716c8`): an `Esc` in the panel closes it and puts the focus back on the comments icon. The `@` list's `Esc` closes the list only (`RichTextCommentInput` now takes the key), so the draft is kept. The panel closes on an `Esc` whose target is in its own DOM; its portaled menus close themselves. `defaultPrevented` no longer decides, because the drawer marks the key to hold itself open. The section carries `data-owns-escape`. - `useRecordPageTier(el, { reservedWidth })`: the tier is measured on the width left after the panel takes its 380. **The record page and the drawer** (`@object-ui/app-shell`) - One predicate, `commentsPanelOffered`, in `RecordDetailView`: an object definition with `enable.feeds !== false`, a page that takes the default columns (no assigned page, not a blocked named page: option C), not a phone, and a record id. It is the only place the rule lives. - While the panel is offered, the discussion rides the record's open request (`streamDiscussion`), so the icon's count is known without opening the 动态 tab; activity stays lazy as before (`activityFeedWanted` is the old `feedWanted`). - `recordCommentsPanel.tsx`: the widths and thresholds (`COMMENTS_PANEL_WIDTH` 380, `COMMENTS_PANEL_BESIDE_MIN_WINDOW` 1280, `COMMENTS_PANEL_DRAWER_SPLIT_MIN_WIDTH` 760), `commentsPanelPlacement` (`beside` / `over` / `cover`), the open state kept in `localStorage` (`os:record-comments-panel:page` and `:drawer`, every access guarded), and `RecordCommentsAside`. - The icon sits in `RecordTopBar`'s new `comments` slot, ahead of the button group, on the page; the drawer portals it into the same slot through `RecordPaneBarApi.commentsSlot` (`RecordPaneBarComments`); a pane without the bar draws it in the page header's trailing controls. **Drawer width chosen**: the default drawer is `md` (720), under the 760 split threshold, so the panel covers the drawer's body there; a drawer at 760 or wider splits, leaving the record at least as wide as the panel. **Strings**: `detail.closeComments`, `collapseReplies`, `commentActions`, `commentsEmptyHint`, `resolveThread` in all eleven packs and the provider-less defaults; everything else reuses existing keys. **Docs**: the plugin-detail README and `content/docs/frontend/plugins/plugin-detail.mdx` describe the panel. ## Why Card #36075 (phase 1 of epic #36062): comments were buried in the 动态 tab beside system entries, so a reader had to switch tabs to see or join a discussion. The card asks for a standalone comment panel on the desktop record page and drawer, reached from a header icon, and an Activity tab of system entries only. ## Side effects reviewers should know - **Hand-written pages keep their old discussion** (option C, seat 13:24Z): showcase `project-detail`, `sys-queue` and `sys-audit-log` still place a footer `record:discussion`, and get no icon. `sys-user` and `sys-organization` have feeds off; `sys-approval-request` has no discussion block on purpose. How a hand-written page opts into the panel is a phase 2 card. - **The 动态 tab keeps one chip on the desktop, 变更** (seat L2, 16:44Z): the card removes 全部 / 活动 / 讨论 only, and 变更 (objectstack#30074) is merged behaviour, offered on the same rule (only where the record shows its field history). With no 全部 beside it, the chip is a toggle: pressed again, it goes back to every entry. The phone keeps all its chips. - **The 动态 count leaves the comments out** wherever the panel is offered (page payload total less the comments it counted). - The panel draws every comment the read holds, oldest first, with no 20-row page: a conversation is read to its end. - Not in this PR: the resolved UI, the filter menu and the unresolved count (wait #36071, wired in a second PR if #36071 is slow); until then this PR is `Part of #36075`. The shared avatar and the delete toast from #36070 are in: main was merged after #36105 landed at 16:04Z. Reactor names on hover are not on the card. ## Verification **New tests (all pass)** - `plugin-detail/src/comments/commentThreads.test.ts` (6): comment rows only, oldest first; replies and a reply to a reply nested; an orphan reply kept; same-instant order; a parent loop loses nothing; latest repliers. - `plugin-detail/src/comments/CommentsPanel.test.tsx` (13): oldest first, system rows left out; collapse and expand; Reply focuses the reply box and answers the thread's first comment; Edit and Delete only on the viewer's own comment; More → Delete, More → Edit saves; React; read-only offers no actions and no box; add, and the draft kept on a refused write; ✕ and Esc; empty; refused and failed with Retry; the icon's count and pressed state. - `plugin-detail/src/__tests__/recordActivity.commentsInPanel-36075.test.tsx` (7): no comments or composer in the stream and 变更 the one chip, with the control; the lone 变更 chip toggles back to every entry; no chip where the record shows no field history; a refused comment read does not replace the system entries; the count probe counts system entries only, with the control; an authored `record:activity` untouched. - `app-shell/src/views/recordCommentsPanel.drawerEscape-36075.test.tsx` (8): the REAL `NavigationOverlay` around the REAL panel, at the stack's root (a record opened from the list) and below it. Esc in the comment box and on ✕ closes the panel, the drawer stays at its level, and the focus returns to the icon. Esc in the `@` list closes the list only. CONTROL: Esc on a record control outside the panel does what the drawer always did. With either fix removed, its pins fail (4 of 8 without the drawer change). - `CommentsPanel.test.tsx` +2: Esc in the `@` list keeps the panel and the draft, and the next Esc closes the panel; Esc in the More menu closes the menu only. Both fail with their fix removed. - `RecordDetailView.commentsPanel-36075.test.tsx` +1: Delete in the panel goes through the page's confirm and toasts 「Comment deleted」 (#36070). - `app-shell/src/views/recordCommentsPanel-36075.test.ts` (2): the 1280 and 760 thresholds. - `components/src/__tests__/record-top-bar-comments-36075.test.tsx` (2): the slot sits ahead of the button group in both bar shapes. - `app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx` (8), the real `RecordDetailView`: icon and count on the default page; open beside at 1440 and close; over at 1100; kept open for the next record; drawer cover, remembered apart from the page; the stream draws no comment and the panel does, once; no icon with feeds off; no icon on a hand-written page, which keeps its discussion. **Changed tests**: 38 cases in 11 `RecordDetailView.*` files read the default page's comments off the 动态 stream; they now read them in the comment panel (same rows, same reads, same grants), and the counts drop the comments: `feedLoading`, `feedRecordScope`, `feedLoadFailure-29188`, `harness` (feedRefusal-11195), `replyCountOnRead-12144`, `discussionExplicitComposition-7298`, `discussionFallbackPipeline-8983`, `recordOpenOneRequest-28470`, `recordOpenWaves-13010`, `recordPageTiers-26678` (变更 alone, a toggle, where `trackHistory` is on and the audit read answers; no chip without it or on a 403), `timelineCount-28737`. Authored-page cases in those files are unchanged. No test deleted or skipped. **Local runs**: every `app-shell/src/views/RecordDetailView.*`, `recordDrawer*` and `components/src/custom` test file (98 files) pass, the 11 above after their change and three that first failed to resolve `@objectstack/client` before its build on a re-run; every new file above passes. The whole app-shell, plugin-detail and components suites (3,274 files) did not fit a local run and were stopped; CI is the full reading. `type-check` (src and tests) clean for plugin-detail, components and app-shell; ESLint on every changed file: 0 errors; `check:i18n-keys`, `check:i18n-drift`, `check:new-line-citations` pass; `overlap-check.mjs`: clean against main and the 6 open PRs that share a file. **Browser evidence** (CRM example on `objectstack dev`, console on Vite, zh-CN, an account seeded with three threads, one with two replies): `/mnt/project-files/build-seat1/36075/` (seat-side folder). | Reading | Result | |---|---| | Page, 1440, light and dark, panel closed → open | icon 「3」, pressed when open; panel `beside`, 380 wide at x 1060; the record columns narrow to leave it the width | | Page, 1100, light and dark | panel `over`, 380 wide at the right edge, record columns keep their width | | Drawer (list → Initech), light and dark | the icon in the drawer's record row; panel `cover`, the drawer body's whole width (718) | | Thread states | 「2 条回复」 with the replier's face; expanded with the reply box and 「收起回复」; hover row (回复, 表情, 更多) with 编辑 / 删除 open | | 动态 tab | no 全部 / 活动 / 讨论 chips, no composer, no comment rows (shot taken before the 变更 chip was kept) | | A record with no comments | empty state with the hint, composer at the foot | ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block is the maintainer's summary, in the maintainer's language). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. Branch name is the harness-assigned `claude/project-thread-ks7hy1`. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgXXdtDHm8mLZYX8Bsb)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgXXdtDHm8mLZYX8Bsb <!-- signed: repo:objectstack#1 · os-sales · session_01L6bhgXXdtDHm8mLZYX8Bsb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2c93001 commit 04f9861

56 files changed

Lines changed: 2774 additions & 190 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/plugin-detail': patch
4+
'@object-ui/components': patch
5+
'@object-ui/i18n': patch
6+
---
7+
8+
feat(record-page): a record's comments move out of the 动态 tab into a comment panel of their own on the desktop
9+
10+
Clause-②: yes (widening) — `@object-ui/plugin-detail` adds exports (`CommentsPanel`, `CommentsButton`, `CommentThread`, `CommentItem`, `CommentComposer`, `CommentHoverActions`, `useRecordComments`, `buildCommentThreads`, `latestRepliers`, `RecordCommentsInPanelContext`) and their types (`CommentsPanelProps`, `CommentsButtonProps`, `RecordCommentThreadProps`, `CommentItemProps`, `CommentItemActions`, `CommentComposerProps`, `CommentHoverActionsProps`, `CommentThreadData`, `RecordCommentsData`), and an optional `reservedWidth` on `useRecordPageTier`. `RichTextCommentInput` (exported) now takes the `Esc` that closes its @ list (`preventDefault` and `stopPropagation`), so nothing round it acts on that key. `RecordActivityTimeline` draws no chip group when it is handed no chips. `@object-ui/components` adds an optional `comments` slot to `RecordTopBar` and `NavigationOverlay`, and the drawer leaves an `Esc` pressed inside a `[data-owns-escape]` region to that region. `@object-ui/i18n` adds five keys to every pack: `detail.closeComments`, `detail.collapseReplies`, `detail.commentActions`, `detail.commentsEmptyHint`, `detail.resolveThread`. Nothing existing is removed or re-typed.
11+
Metadata-protocol: none
12+
Skills-docs: none — no skill under `skills/**` teaches where the console draws a record's comments; `content/docs/frontend/plugins/plugin-detail.mdx` and the plugin-detail README gain the panel in this change.
13+
14+
On the desktop record page and in the record drawer, the record header gains a comments icon with the number of top-level comments. A press opens the record's comment panel, the next one closes it, and the browser remembers whether it was left open (once for the page, once for the drawer).
15+
16+
- The panel is 380 px wide: 「评论」 and ✕ at the top, the threads oldest first, the comment box docked at the foot. A thread's replies fold to 「N 条回复」 with the latest repliers' faces and open in place, with a reply box under them; Reply on any comment of a thread opens it with the caret in that box.
17+
- A comment's actions sit in one row at its top right while the pointer is over it, or focus is in it: Reply, an emoji, and More with Edit and Delete on the viewer's own comments. Every write is offered under the same grants as before.
18+
- From a 1280 px window the panel sits beside the record and the record gives way; in a narrower window it is drawn over the record's right edge. In a drawer narrower than 760 px (the default 720 px drawer) it covers the drawer's body; a wider drawer splits.
19+
- Esc in the panel closes it and returns the focus to the comments icon, in a drawer too: the drawer neither closes nor steps back on it. Esc in the panel's @ list closes the list only and keeps the draft.
20+
- While the panel holds the comments, the 动态 tab and panel hold the system entries only: activity and field changes, with no comment box and no All / Activity / Discussion chips; the Changes chip stays where the record shows its field history, and pressed again it goes back to every entry. Their count leaves the comments out.
21+
22+
Unchanged: a record page authored in full keeps the feed blocks it places (`record:discussion`, `record:activity`) as they were and shows no icon; an object with `enable.feeds: false` shows no icon; the phone keeps the comments in its 动态 tab.

‎content/docs/frontend/plugins/plugin-detail.mdx‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,41 @@ declare const handleAddComment: (text: string) => void;
195195
- **Positioning**: Panel can be placed at `bottom`, `right`, or `left` of the record view
196196
- **Collapsible**: Optional collapse/expand with configurable default state
197197

198+
## The record's comment panel
199+
200+
On the desktop console, a record's comments live in a panel of their own,
201+
opened from the comments icon in the record header (on the record page and in
202+
the record drawer), and no longer inside the 动态 (Activity) tab
203+
(objectstack#36075):
204+
205+
- **The icon** shows how many top-level comments the record holds. A press
206+
opens the panel, the next one closes it, and the browser remembers whether it
207+
was left open, once for the record page and once for the drawer.
208+
- **The panel** is 380 px wide: 「评论」 and ✕ at the top, the threads oldest
209+
first, the comment box at the foot. A thread's replies fold to 「N 条回复」
210+
and open in place. A comment's actions (Reply, an emoji, and More with Edit
211+
and Delete on your own comments) appear at its top right while the pointer is
212+
over it.
213+
- **Where it sits**: beside the record from a 1280 px window, the record giving
214+
way; over the record's right edge in a narrower window. In a drawer narrower
215+
than 760 px (the default drawer is 720) it covers the drawer's body, and ✕ or
216+
Esc returns to the record.
217+
- **The 动态 tab** then holds the system entries only: activity and field
218+
changes, with no comment box and no All / Activity / Discussion chips. The
219+
Changes chip stays where the record shows its field history; pressed again,
220+
it goes back to every entry. The tab's count leaves the comments out.
221+
222+
The panel and the icon come with the default record page and with a page that
223+
only fills its slots. A record page you author in full keeps the feed blocks it
224+
places (`record:discussion`, `record:activity`) exactly as before, and an object
225+
with `enable.feeds: false` shows no icon. On a phone the comments stay in the
226+
动态 tab.
227+
228+
The components are exported from `@object-ui/plugin-detail` (`CommentsPanel`,
229+
`CommentsButton`, `CommentThread`, `CommentItem`, `CommentComposer`,
230+
`useRecordComments`); each reads the discussion off the host's
231+
`DiscussionContext`, as the feed blocks do.
232+
198233
## The `record:activity` block
199234

200235
`RecordActivityTimeline` is a presenter: you hand it `items`. The SDUI block
Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#36075 — the record's comments move out of the 动态 tab into a
5+
* panel of their own, opened from a comments icon in the record header.
6+
*
7+
* Pinned through the REAL `RecordDetailView`:
8+
*
9+
* - The icon is in the header of the default record page, with the number of
10+
* top-level comments; a press opens 「评论」 and the next one closes it.
11+
* - Whether the panel is open is kept in this browser: a record opened later
12+
* opens with the panel as it was left.
13+
* - Where it is drawn: beside the record from a 1280 window (the record gives
14+
* way), over the record's right edge in a narrower one, and over the whole
15+
* body of a drawer too narrow to split.
16+
* - The comments are the panel's: the page's 动态 stream no longer draws them.
17+
* - No icon where the panel is not offered: an object with feeds off, and a
18+
* page authored by hand (option C, seat 13:24Z): that page keeps its own
19+
* discussion block as it was.
20+
*/
21+
22+
import * as React from 'react';
23+
import '@testing-library/jest-dom/vitest';
24+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
25+
import { render, cleanup, within, act, waitFor, fireEvent } from '@testing-library/react';
26+
import { MemoryRouter } from 'react-router-dom';
27+
28+
vi.mock('@object-ui/auth', async (importOriginal) => ({
29+
...(await importOriginal<Record<string, unknown>>()),
30+
useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }),
31+
createAuthenticatedFetch: () => vi.fn(),
32+
}));
33+
vi.mock('@object-ui/collaboration', async (importOriginal) => ({
34+
...(await importOriginal<Record<string, unknown>>()),
35+
useRecordPresence: () => [],
36+
PresenceAvatars: () => null,
37+
}));
38+
vi.mock('sonner', () => ({
39+
toast: Object.assign(vi.fn(), {
40+
success: vi.fn(),
41+
error: vi.fn(),
42+
info: vi.fn(),
43+
warning: vi.fn(),
44+
loading: vi.fn(),
45+
dismiss: vi.fn(),
46+
}),
47+
}));
48+
vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null }));
49+
vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null }));
50+
vi.mock('./FlowRunner', () => ({ FlowRunner: () => null }));
51+
vi.mock('./MetadataInspector', () => ({
52+
MetadataPanel: () => null,
53+
useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }),
54+
}));
55+
56+
import { I18nProvider } from '@object-ui/i18n';
57+
import { MetadataCtx } from '@object-ui/react';
58+
import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions';
59+
import { toast } from 'sonner';
60+
import { RecordDetailView } from './RecordDetailView';
61+
62+
const OBJECT_NAME = 'crm_case';
63+
const NO_FEEDS = 'crm_note';
64+
const RECORD_ID = 'case-41';
65+
const THREAD = `${OBJECT_NAME}:${RECORD_ID}`;
66+
67+
const ADA_BODY = 'Ada: customer called back about the outage';
68+
const GRACE_BODY = 'Grace: escalated to tier two';
69+
const REPLY_BODY = 'Grace: tier two confirmed';
70+
71+
const ROWS = [
72+
{ id: 'c-ada', thread_id: THREAD, author_id: 'u-ada', author_name: 'Ada', body: ADA_BODY, created_at: '2026-10-01T08:00:00.000Z' },
73+
{ id: 'c-grace', thread_id: THREAD, author_id: 'u-grace', author_name: 'Grace', body: GRACE_BODY, created_at: '2026-10-01T09:00:00.000Z' },
74+
{
75+
id: 'c-reply',
76+
thread_id: THREAD,
77+
parent_id: 'c-ada',
78+
author_id: 'u-grace',
79+
author_name: 'Grace',
80+
body: REPLY_BODY,
81+
created_at: '2026-10-01T10:00:00.000Z',
82+
},
83+
];
84+
85+
const FIELDS = { id: { type: 'text', label: 'Id' }, subject: { type: 'text', label: 'Subject' } };
86+
const OBJECTS = [
87+
{ name: OBJECT_NAME, label: 'Case', fields: FIELDS },
88+
{ name: NO_FEEDS, label: 'Note', fields: FIELDS, enable: { feeds: false } },
89+
];
90+
91+
const AUTHORED_PAGE = {
92+
name: 'case_detail_page',
93+
type: 'record',
94+
object: OBJECT_NAME,
95+
regions: [
96+
{
97+
name: 'main',
98+
components: [{ type: 'page:header', properties: { title: '{subject}' } }, { type: 'record:discussion' }],
99+
},
100+
],
101+
};
102+
103+
function makeDataSource() {
104+
return {
105+
find: vi.fn(async (objectName: string) => {
106+
if (objectName === 'sys_comment') return { data: ROWS.map((r) => ({ ...r })) };
107+
return { data: [] };
108+
}),
109+
findOne: vi.fn(async (_o: string, id: string) => ({ id, subject: `Case ${id}` })),
110+
create: vi.fn(async (_o: string, data: any) => ({ id: 'c-new', ...data })),
111+
update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })),
112+
delete: vi.fn(async () => true),
113+
} as any;
114+
}
115+
116+
function metadataFor(pages: unknown[]) {
117+
return {
118+
objects: OBJECTS,
119+
pages,
120+
loading: false,
121+
error: null,
122+
refresh: async () => {},
123+
invalidate: () => {},
124+
ensureType: async () => pages,
125+
getItem: async () => null,
126+
getItemsByType: (type: string) => (type === 'page' ? pages : type === 'object' ? OBJECTS : []),
127+
getTypeStatus: () => 'ready',
128+
} as any;
129+
}
130+
131+
const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true };
132+
const PERMS = {
133+
authenticated: true,
134+
userId: 'u-ada',
135+
tenantId: null,
136+
positions: ['member'],
137+
hasAnyQueue: false,
138+
objectsUsingQueues: [],
139+
permissionSets: ['member'],
140+
objects: { [OBJECT_NAME]: FULL, [NO_FEEDS]: FULL, sys_comment: FULL },
141+
fields: {},
142+
} as MePermissionsAuthenticatedResponse;
143+
144+
interface MountOptions {
145+
objectName?: string;
146+
pages?: unknown[];
147+
embedded?: boolean;
148+
}
149+
150+
async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false }: MountOptions = {}) {
151+
const rendered = render(
152+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>
153+
<MePermissionsProvider initialPermissions={PERMS}>
154+
<MemoryRouter initialEntries={[`/app/service/${objectName}/${RECORD_ID}`]}>
155+
<MetadataCtx.Provider value={metadataFor(pages)}>
156+
<RecordDetailView
157+
dataSource={makeDataSource()}
158+
objects={OBJECTS}
159+
onEdit={() => {}}
160+
objectNameOverride={objectName}
161+
recordIdOverride={RECORD_ID}
162+
embedded={embedded}
163+
/>
164+
</MetadataCtx.Provider>
165+
</MemoryRouter>
166+
</MePermissionsProvider>
167+
</I18nProvider>,
168+
);
169+
await within(rendered.container).findByText(`Case ${RECORD_ID}`, undefined, { timeout: 4000 }).catch(() => undefined);
170+
await act(async () => {});
171+
return rendered;
172+
}
173+
174+
const button = (root: HTMLElement) => root.querySelector('[data-comments-button]') as HTMLButtonElement | null;
175+
const panel = (root: HTMLElement) => root.querySelector('[data-comments-panel]') as HTMLElement | null;
176+
const placement = (root: HTMLElement) =>
177+
root.querySelector('[data-comments-placement]')?.getAttribute('data-comments-placement') ?? null;
178+
179+
function setWindowWidth(width: number) {
180+
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width });
181+
window.dispatchEvent(new Event('resize'));
182+
}
183+
184+
beforeEach(() => {
185+
window.localStorage.clear();
186+
setWindowWidth(1440);
187+
vi.stubGlobal(
188+
'fetch',
189+
vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })),
190+
);
191+
});
192+
193+
afterEach(() => {
194+
cleanup();
195+
vi.unstubAllGlobals();
196+
vi.clearAllMocks();
197+
});
198+
199+
describe('the record comment panel (objectstack#36075)', () => {
200+
it('the default page header carries the icon with the number of top-level comments', async () => {
201+
const { container } = await mount();
202+
await waitFor(() => expect(button(container)).not.toBeNull());
203+
await waitFor(() => expect(button(container)!.querySelector('[data-comments-count]')).toHaveTextContent('2'));
204+
expect(button(container)).toHaveAttribute('aria-pressed', 'false');
205+
expect(panel(container)).toBeNull();
206+
});
207+
208+
it('a press opens the panel beside the record from a 1280 window, the next press closes it', async () => {
209+
const { container } = await mount();
210+
await waitFor(() => expect(button(container)).not.toBeNull());
211+
fireEvent.click(button(container)!);
212+
expect(panel(container)).not.toBeNull();
213+
expect(placement(container)).toBe('beside');
214+
expect(button(container)).toHaveAttribute('aria-pressed', 'true');
215+
const p = within(panel(container)!);
216+
expect(await p.findByText(ADA_BODY)).toBeInTheDocument();
217+
expect(p.getByText(GRACE_BODY)).toBeInTheDocument();
218+
fireEvent.click(button(container)!);
219+
expect(panel(container)).toBeNull();
220+
});
221+
222+
it('the panel draws over the record in a window under 1280', async () => {
223+
setWindowWidth(1100);
224+
const { container } = await mount();
225+
await waitFor(() => expect(button(container)).not.toBeNull());
226+
fireEvent.click(button(container)!);
227+
expect(placement(container)).toBe('over');
228+
});
229+
230+
it('the panel is kept open in this browser for the next record opened', async () => {
231+
const first = await mount();
232+
await waitFor(() => expect(button(first.container)).not.toBeNull());
233+
fireEvent.click(button(first.container)!);
234+
cleanup();
235+
const second = await mount();
236+
await waitFor(() => expect(panel(second.container)).not.toBeNull());
237+
});
238+
239+
it('a drawer too narrow to split gives the panel its whole body, and remembers it apart from the page', async () => {
240+
const page = await mount();
241+
await waitFor(() => expect(button(page.container)).not.toBeNull());
242+
fireEvent.click(button(page.container)!);
243+
cleanup();
244+
const drawer = await mount({ embedded: true });
245+
await waitFor(() => expect(button(drawer.container)).not.toBeNull());
246+
// The page was left open; the drawer opens closed.
247+
expect(panel(drawer.container)).toBeNull();
248+
fireEvent.click(button(drawer.container)!);
249+
expect(placement(drawer.container)).toBe('cover');
250+
});
251+
252+
it('the 动态 stream no longer draws the comments', async () => {
253+
const { container } = await mount();
254+
await waitFor(() => expect(button(container)).not.toBeNull());
255+
await act(async () => {});
256+
expect(within(container).queryByText(ADA_BODY)).toBeNull();
257+
fireEvent.click(button(container)!);
258+
expect(await within(panel(container)!).findByText(ADA_BODY)).toBeInTheDocument();
259+
// Exactly once on the page: in the panel.
260+
expect(within(container).getAllByText(ADA_BODY)).toHaveLength(1);
261+
});
262+
263+
it("Delete in the panel goes through the page's confirm and says it went through (#36070's toast)", async () => {
264+
const { container } = await mount();
265+
await waitFor(() => expect(button(container)).not.toBeNull());
266+
fireEvent.click(button(container)!);
267+
const p = panel(container)!;
268+
await within(p).findByText(ADA_BODY);
269+
const own = Array.from(p.querySelectorAll('[data-comment-item]')).find((el) => el.textContent?.includes(ADA_BODY)) as HTMLElement;
270+
fireEvent.pointerDown(own.querySelector('[data-comment-action="more"]')!, { button: 0, ctrlKey: false, pointerType: 'mouse' });
271+
fireEvent.click(await within(document.body).findByRole('menuitem', { name: 'Delete' }));
272+
const dialog = await within(document.body).findByRole('alertdialog');
273+
await act(async () => {
274+
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
275+
});
276+
await waitFor(() => expect(within(panel(container)!).queryByText(ADA_BODY)).toBeNull());
277+
expect(toast.success).toHaveBeenCalledWith('Comment deleted');
278+
});
279+
280+
it('no icon on an object with feeds off', async () => {
281+
const { container } = await mount({ objectName: NO_FEEDS });
282+
await act(async () => {});
283+
expect(button(container)).toBeNull();
284+
});
285+
286+
it('no icon on a hand-written page, which keeps its own discussion block', async () => {
287+
const { container } = await mount({ pages: [AUTHORED_PAGE], embedded: true });
288+
expect(await within(container).findByText(ADA_BODY)).toBeInTheDocument();
289+
expect(button(container)).toBeNull();
290+
expect(panel(container)).toBeNull();
291+
});
292+
});

0 commit comments

Comments
 (0)