diff --git a/.changeset/36075-record-comments-panel.md b/.changeset/36075-record-comments-panel.md new file mode 100644 index 00000000000..b40d9f0c448 --- /dev/null +++ b/.changeset/36075-record-comments-panel.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/components': patch +'@object-ui/i18n': patch +--- + +feat(record-page): a record's comments move out of the 动态 tab into a comment panel of their own on the desktop + +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 +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. + +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). + +- 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. +- 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. +- 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. +- 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. +- 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. + +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. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index f9e160e2638..2bb06c67db9 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -195,6 +195,41 @@ declare const handleAddComment: (text: string) => void; - **Positioning**: Panel can be placed at `bottom`, `right`, or `left` of the record view - **Collapsible**: Optional collapse/expand with configurable default state +## The record's comment panel + +On the desktop console, a record's comments live in a panel of their own, +opened from the comments icon in the record header (on the record page and in +the record drawer), and no longer inside the 动态 (Activity) tab +(objectstack#36075): + +- **The icon** shows how many top-level comments the record holds. A press + opens the panel, the next one closes it, and the browser remembers whether it + was left open, once for the record page and once for the drawer. +- **The panel** is 380 px wide: 「评论」 and ✕ at the top, the threads oldest + first, the comment box at the foot. A thread's replies fold to 「N 条回复」 + and open in place. A comment's actions (Reply, an emoji, and More with Edit + and Delete on your own comments) appear at its top right while the pointer is + over it. +- **Where it sits**: beside the record from a 1280 px window, the record giving + way; over the record's right edge in a narrower window. In a drawer narrower + than 760 px (the default drawer is 720) it covers the drawer's body, and ✕ or + Esc returns to the record. +- **The 动态 tab** then holds 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; pressed again, + it goes back to every entry. The tab's count leaves the comments out. + +The panel and the icon come with the default record page and with a page that +only fills its slots. A record page you author in full keeps the feed blocks it +places (`record:discussion`, `record:activity`) exactly as before, and an object +with `enable.feeds: false` shows no icon. On a phone the comments stay in the +动态 tab. + +The components are exported from `@object-ui/plugin-detail` (`CommentsPanel`, +`CommentsButton`, `CommentThread`, `CommentItem`, `CommentComposer`, +`useRecordComments`); each reads the discussion off the host's +`DiscussionContext`, as the feed blocks do. + ## The `record:activity` block `RecordActivityTimeline` is a presenter: you hand it `items`. The SDUI block diff --git a/ui/packages/app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx new file mode 100644 index 00000000000..a04559d1318 --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx @@ -0,0 +1,292 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36075 — the record's comments move out of the 动态 tab into a + * panel of their own, opened from a comments icon in the record header. + * + * Pinned through the REAL `RecordDetailView`: + * + * - The icon is in the header of the default record page, with the number of + * top-level comments; a press opens 「评论」 and the next one closes it. + * - Whether the panel is open is kept in this browser: a record opened later + * opens with the panel as it was left. + * - Where it is drawn: beside the record from a 1280 window (the record gives + * way), over the record's right edge in a narrower one, and over the whole + * body of a drawer too narrow to split. + * - The comments are the panel's: the page's 动态 stream no longer draws them. + * - No icon where the panel is not offered: an object with feeds off, and a + * page authored by hand (option C, seat 13:24Z): that page keeps its own + * discussion block as it was. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, within, act, waitFor, fireEvent } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { toast } from 'sonner'; +import { RecordDetailView } from './RecordDetailView'; + +const OBJECT_NAME = 'crm_case'; +const NO_FEEDS = 'crm_note'; +const RECORD_ID = 'case-41'; +const THREAD = `${OBJECT_NAME}:${RECORD_ID}`; + +const ADA_BODY = 'Ada: customer called back about the outage'; +const GRACE_BODY = 'Grace: escalated to tier two'; +const REPLY_BODY = 'Grace: tier two confirmed'; + +const ROWS = [ + { id: 'c-ada', thread_id: THREAD, author_id: 'u-ada', author_name: 'Ada', body: ADA_BODY, created_at: '2026-10-01T08:00:00.000Z' }, + { id: 'c-grace', thread_id: THREAD, author_id: 'u-grace', author_name: 'Grace', body: GRACE_BODY, created_at: '2026-10-01T09:00:00.000Z' }, + { + id: 'c-reply', + thread_id: THREAD, + parent_id: 'c-ada', + author_id: 'u-grace', + author_name: 'Grace', + body: REPLY_BODY, + created_at: '2026-10-01T10:00:00.000Z', + }, +]; + +const FIELDS = { id: { type: 'text', label: 'Id' }, subject: { type: 'text', label: 'Subject' } }; +const OBJECTS = [ + { name: OBJECT_NAME, label: 'Case', fields: FIELDS }, + { name: NO_FEEDS, label: 'Note', fields: FIELDS, enable: { feeds: false } }, +]; + +const AUTHORED_PAGE = { + name: 'case_detail_page', + type: 'record', + object: OBJECT_NAME, + regions: [ + { + name: 'main', + components: [{ type: 'page:header', properties: { title: '{subject}' } }, { type: 'record:discussion' }], + }, + ], +}; + +function makeDataSource() { + return { + find: vi.fn(async (objectName: string) => { + if (objectName === 'sys_comment') return { data: ROWS.map((r) => ({ ...r })) }; + return { data: [] }; + }), + findOne: vi.fn(async (_o: string, id: string) => ({ id, subject: `Case ${id}` })), + create: vi.fn(async (_o: string, data: any) => ({ id: 'c-new', ...data })), + update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })), + delete: vi.fn(async () => true), + } as any; +} + +function metadataFor(pages: unknown[]) { + return { + objects: OBJECTS, + pages, + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => pages, + getItem: async () => null, + getItemsByType: (type: string) => (type === 'page' ? pages : type === 'object' ? OBJECTS : []), + getTypeStatus: () => 'ready', + } as any; +} + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const PERMS = { + authenticated: true, + userId: 'u-ada', + tenantId: null, + positions: ['member'], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['member'], + objects: { [OBJECT_NAME]: FULL, [NO_FEEDS]: FULL, sys_comment: FULL }, + fields: {}, +} as MePermissionsAuthenticatedResponse; + +interface MountOptions { + objectName?: string; + pages?: unknown[]; + embedded?: boolean; +} + +async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false }: MountOptions = {}) { + const rendered = render( + + + + + {}} + objectNameOverride={objectName} + recordIdOverride={RECORD_ID} + embedded={embedded} + /> + + + + , + ); + await within(rendered.container).findByText(`Case ${RECORD_ID}`, undefined, { timeout: 4000 }).catch(() => undefined); + await act(async () => {}); + return rendered; +} + +const button = (root: HTMLElement) => root.querySelector('[data-comments-button]') as HTMLButtonElement | null; +const panel = (root: HTMLElement) => root.querySelector('[data-comments-panel]') as HTMLElement | null; +const placement = (root: HTMLElement) => + root.querySelector('[data-comments-placement]')?.getAttribute('data-comments-placement') ?? null; + +function setWindowWidth(width: number) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); + window.dispatchEvent(new Event('resize')); +} + +beforeEach(() => { + window.localStorage.clear(); + setWindowWidth(1440); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })), + ); +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe('the record comment panel (objectstack#36075)', () => { + it('the default page header carries the icon with the number of top-level comments', async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + await waitFor(() => expect(button(container)!.querySelector('[data-comments-count]')).toHaveTextContent('2')); + expect(button(container)).toHaveAttribute('aria-pressed', 'false'); + expect(panel(container)).toBeNull(); + }); + + it('a press opens the panel beside the record from a 1280 window, the next press closes it', async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + fireEvent.click(button(container)!); + expect(panel(container)).not.toBeNull(); + expect(placement(container)).toBe('beside'); + expect(button(container)).toHaveAttribute('aria-pressed', 'true'); + const p = within(panel(container)!); + expect(await p.findByText(ADA_BODY)).toBeInTheDocument(); + expect(p.getByText(GRACE_BODY)).toBeInTheDocument(); + fireEvent.click(button(container)!); + expect(panel(container)).toBeNull(); + }); + + it('the panel draws over the record in a window under 1280', async () => { + setWindowWidth(1100); + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + fireEvent.click(button(container)!); + expect(placement(container)).toBe('over'); + }); + + it('the panel is kept open in this browser for the next record opened', async () => { + const first = await mount(); + await waitFor(() => expect(button(first.container)).not.toBeNull()); + fireEvent.click(button(first.container)!); + cleanup(); + const second = await mount(); + await waitFor(() => expect(panel(second.container)).not.toBeNull()); + }); + + it('a drawer too narrow to split gives the panel its whole body, and remembers it apart from the page', async () => { + const page = await mount(); + await waitFor(() => expect(button(page.container)).not.toBeNull()); + fireEvent.click(button(page.container)!); + cleanup(); + const drawer = await mount({ embedded: true }); + await waitFor(() => expect(button(drawer.container)).not.toBeNull()); + // The page was left open; the drawer opens closed. + expect(panel(drawer.container)).toBeNull(); + fireEvent.click(button(drawer.container)!); + expect(placement(drawer.container)).toBe('cover'); + }); + + it('the 动态 stream no longer draws the comments', async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + await act(async () => {}); + expect(within(container).queryByText(ADA_BODY)).toBeNull(); + fireEvent.click(button(container)!); + expect(await within(panel(container)!).findByText(ADA_BODY)).toBeInTheDocument(); + // Exactly once on the page: in the panel. + expect(within(container).getAllByText(ADA_BODY)).toHaveLength(1); + }); + + it("Delete in the panel goes through the page's confirm and says it went through (#36070's toast)", async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + fireEvent.click(button(container)!); + const p = panel(container)!; + await within(p).findByText(ADA_BODY); + const own = Array.from(p.querySelectorAll('[data-comment-item]')).find((el) => el.textContent?.includes(ADA_BODY)) as HTMLElement; + fireEvent.pointerDown(own.querySelector('[data-comment-action="more"]')!, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + fireEvent.click(await within(document.body).findByRole('menuitem', { name: 'Delete' })); + const dialog = await within(document.body).findByRole('alertdialog'); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' })); + }); + await waitFor(() => expect(within(panel(container)!).queryByText(ADA_BODY)).toBeNull()); + expect(toast.success).toHaveBeenCalledWith('Comment deleted'); + }); + + it('no icon on an object with feeds off', async () => { + const { container } = await mount({ objectName: NO_FEEDS }); + await act(async () => {}); + expect(button(container)).toBeNull(); + }); + + it('no icon on a hand-written page, which keeps its own discussion block', async () => { + const { container } = await mount({ pages: [AUTHORED_PAGE], embedded: true }); + expect(await within(container).findByText(ADA_BODY)).toBeInTheDocument(); + expect(button(container)).toBeNull(); + expect(panel(container)).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.discussionExplicitComposition-7298.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.discussionExplicitComposition-7298.test.tsx index 1b9d1765cc1..2646c08d9c5 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.discussionExplicitComposition-7298.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.discussionExplicitComposition-7298.test.tsx @@ -56,7 +56,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataCtx } from '@object-ui/react'; @@ -216,6 +216,7 @@ async function settled() { beforeEach(() => { cleanup(); + window.localStorage.clear(); // Unrelated chrome on this view reaches for the platform API; in jsdom that // is a real socket. Answer it locally so the feed read is the only asynchrony. vi.stubGlobal( @@ -281,17 +282,22 @@ describe('objectui#7298 — the discussion panel is composed, never appended', ( expect(composerCount()).toBe(0); }); - it('the SYNTHESIZED default page still shows the discussion — its 动态 stream declares it', async () => { - // No authored page ⇒ `buildDefaultPageSchema`, which composes the 动态 - // stream itself (objectstack#27055: discussion, activity and changes in - // one `record:activity`; its whole face is the 动态 tab since - // objectstack#27524). The ruling removes the host's append, not the - // default page's discussion. + it('the SYNTHESIZED default page still shows the discussion — in its comment panel', async () => { + // No authored page ⇒ `buildDefaultPageSchema`. The ruling removes the + // host's append, not the default page's discussion: since objectstack#36075 + // the default page's comments are its comment panel's, opened from the + // header's comments icon, with the composer at the panel's foot. renderDetail({ objects: OBJECTS_FEEDS_ON, pages: [], comments: ONE_COMMENT, search: '?related=timeline' }); await settled(); + const button = await waitFor(() => { + const el = document.querySelector('[data-comments-button]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + fireEvent.click(button); await waitFor(() => expect(count(COMMENT_MARKER)).toBeGreaterThan(0)); - expect(composerCount()).toBeGreaterThan(0); + expect(document.querySelector('[data-comments-panel] [data-comments-composer] textarea')).not.toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.discussionFallbackPipeline-8983.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.discussionFallbackPipeline-8983.test.tsx index 6680b499837..1563e9d8573 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.discussionFallbackPipeline-8983.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.discussionFallbackPipeline-8983.test.tsx @@ -66,6 +66,12 @@ * `onLoadMore` renders a button that does nothing, which reads as "paging * works" to every assertion that only counts it. * + * ⚠️ SINCE objectstack#36075 the synthesized default page draws the record's + * comments in its comment panel, not in the 动态 stream. The synthesized route + * is read here as both of its surfaces: the stream (system entries, on the + * pipeline's declared config) and the panel (every comment, oldest first, a + * conversation read to its end rather than a paged feed). + * * ## Resolution * * Nothing here resolves through any `dist/`: `./RecordDetailView` is this @@ -316,8 +322,28 @@ async function readSurface(fixture: Fixture, pages: any[]) { } const viaAuthoredBlock = (fixture: Fixture) => readSurface(fixture, [AUTHORED_PAGE_WITH_DISCUSSION]); -/** No authored page ⇒ the synthesized default, which composes the block. */ -const viaSynthesizedBlock = (fixture: Fixture) => readSurface(fixture, []); +/** + * No authored page ⇒ the synthesized default. Its comments are the comment + * panel's (objectstack#36075): what the stream draws is read before the panel + * opens, then what the panel draws. + */ +async function viaSynthesizedBlock(fixture: Fixture) { + renderDetail(fixture, []); + await settled(); + const stream = { rows: renderedRows(fixture), loadMore: loadMoreCount() }; + const button = await waitFor(() => { + const el = document.querySelector('[data-comments-button]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + fireEvent.click(button); + const panel = document.querySelector('[data-comments-panel]') as HTMLElement; + await waitFor(() => expect(panel.querySelectorAll('[data-comment-thread]').length).toBeGreaterThan(0)); + const panelRows = Array.from(panel.querySelectorAll('[data-comment-thread] > [data-comment-item] p')).map( + (el) => el.textContent ?? '', + ); + return { stream, panelRows }; +} function readPreFixShape(fixture: Fixture) { render(); @@ -326,6 +352,7 @@ function readPreFixShape(fixture: Fixture) { beforeEach(() => { cleanup(); + window.localStorage.clear(); // Unrelated chrome on this view reaches for the platform API; in jsdom that // is a real socket. Answer it locally so the feed reads are the only // asynchrony under test. @@ -359,9 +386,11 @@ describe('both composition routes render the same feed (objectui#8983)', () => { // node DECLARES `showCompleted: true` — a stream shows what happened. It // still runs the one pipeline: the completed row is there because the // declared config says so, and the paging case below holds the window. + // Its comments are the comment panel's (objectstack#36075). cleanup(); const synthesized = await viaSynthesizedBlock(fixture); - expect(synthesized.rows).toEqual([...expected, TASK_MARKER]); + expect(synthesized.stream.rows).toEqual([TASK_MARKER]); + expect(synthesized.panelRows).toEqual(expected); // PRE-FIX CONTROL — the same feed, the shape the retired fallback had. cleanup(); @@ -381,11 +410,14 @@ describe('both composition routes render the same feed (objectui#8983)', () => { expect(authored.rows).toEqual(expected); expect(authored.loadMore).toBe(1); + // The synthesized page's comment panel is a conversation, read to its + // end: every comment, oldest first, and the stream holds none of them to + // page (objectstack#36075). cleanup(); const synthesized = await viaSynthesizedBlock(fixture); - expect(synthesized.rows).toEqual(expected); - expect(synthesized.loadMore).toBe(1); - expect(authored.rows).toEqual(synthesized.rows); + expect(synthesized.stream.rows).toEqual([]); + expect(synthesized.stream.loadMore).toBe(0); + expect(synthesized.panelRows).toEqual(Array.from({ length: 25 }, (_, i) => commentMarker(i + 1))); // PRE-FIX CONTROL — no pipeline, so no window and no paging affordance. cleanup(); @@ -409,7 +441,8 @@ describe('both composition routes render the same feed (objectui#8983)', () => { cleanup(); const synthesized = await viaSynthesizedBlock(fixture); - expect(synthesized.rows).toEqual(expected); + expect(synthesized.stream.rows).toEqual([]); + expect(synthesized.panelRows).toEqual(expected); cleanup(); const preFix = readPreFixShape(fixture); 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 c6fbd1dccc5..6b7bf2d3e33 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 @@ -17,8 +17,8 @@ * * Pinned here, on the rendered page: * 1. a 500 on the comments read (payload part, and direct GET) shows the - * load-failure notice with a Retry, never the empty state, and the 动态 - * tab names no count; + * load-failure notice with a Retry, never the empty state, and names no + * count (since objectstack#36075 in the comment panel, and on its icon); * 2. the same for the activity read; * 3. Retry re-reads only the failed source, directly, and the comments * replace the notice once the server answers; @@ -194,6 +194,7 @@ beforeEach(() => { __resetRecordApprovalsStore(); RelatedCountStore._reset(); Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }); + window.localStorage.clear(); }); afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); @@ -240,9 +241,28 @@ const faceOf = (c: HTMLElement) => c.querySelector('[data-related-enlarged="time 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; -/** The 动态 tab's label, badge included. */ -const timelineTab = (c: HTMLElement) => - Array.from(c.querySelectorAll('[role="tab"]')).find((t) => /^Activity/.test(t.textContent ?? ''))?.textContent; +/** + * objectstack#36075 — on the default page the record's comments are the + * comment panel's, and so is a failed or refused comments read: the panel, + * opened from the header's comments icon (it stays open across a record + * switch). + */ +async function commentsPanelOf(c: HTMLElement, held: Held[]): Promise { + if (!c.querySelector('[data-comments-panel]')) { + const button = c.querySelector('[data-comments-button]') as HTMLElement | null; + expect(button, 'the header offers the comments icon').not.toBeNull(); + await act(async () => { fireEvent.click(button!); }); + await settle(held); + } + return c.querySelector('[data-comments-panel]') as HTMLElement; +} +const commentsNote = (panel: HTMLElement) => + panel.querySelector('[data-comments-note]')?.getAttribute('data-comments-note') ?? null; +const panelRetry = (panel: HTMLElement) => + panel.querySelector('[data-comments-note="failed"] button') as HTMLButtonElement | null; +const panelEmpty = (panel: HTMLElement) => panel.querySelector('[data-comments-empty]') !== null; +/** The header icon's number, or `null` when it names none. */ +const commentsCount = (c: HTMLElement) => c.querySelector('[data-comments-count]')?.textContent ?? null; /** Open the record over an adapter that reads every stream on its own. */ async function bootDirect(answers: Answers, search = '') { const booted = await boot(answers, search); @@ -255,25 +275,27 @@ describe('objectstack#29188 — a failed comments read shows the load-failure no const { held, open } = await boot({ discussion: FAIL, activity: NO_ACTIVITY, attachments: { total: 0, records: [] } }); const view = open(); await settle(held); - const peek = peekOf(view.container); - expect(failedSources(peek)).toEqual(['comments']); - expect(peek.textContent).toContain(COMMENTS_FAILED); - expect(peek.textContent).not.toContain(EMPTY_ACTIVITY); - expect(retryButton(peek)).not.toBeNull(); + // The comments icon names no count: unknown, not 0. + expect(commentsCount(view.container)).toBeNull(); + const panel = await commentsPanelOf(view.container, held); + expect(commentsNote(panel)).toBe('failed'); + expect(panel.textContent).toContain(COMMENTS_FAILED); + expect(panelEmpty(panel)).toBe(false); + expect(panelRetry(panel)).not.toBeNull(); // Only the sentence: no status code, no server text, no table name. - expect(peek.textContent).not.toMatch(/500|DATABASE_ERROR|db down|sys_comment/); - // The stream's count is unknown, not 0. - expect(timelineTab(view.container)).toBe('Activity'); + expect(panel.textContent).not.toMatch(/500|DATABASE_ERROR|db down|sys_comment/); + // The 动态 stream holds no comments, so a failed comments read is not its to report. + expect(failedSources(view.container).filter((s) => s === 'comments')).toEqual([]); }); it('a 500 on a direct sys_comment read shows the same notice', async () => { const { held, open } = await bootDirect({ failGet: ['sys_comment'] }); const view = open(); await settle(held); - const peek = peekOf(view.container); - expect(failedSources(peek)).toEqual(['comments']); - expect(peek.textContent).not.toContain(EMPTY_ACTIVITY); - expect(timelineTab(view.container)).toBe('Activity'); + expect(commentsCount(view.container)).toBeNull(); + const panel = await commentsPanelOf(view.container, held); + expect(commentsNote(panel)).toBe('failed'); + expect(panelEmpty(panel)).toBe(false); }); it('Retry re-reads only the failed comments, directly, and draws them once the server answers', async () => { @@ -282,9 +304,10 @@ describe('objectstack#29188 — a failed comments read shows the load-failure no const view = open(); await settle(held); expect(streamReads(held)).toEqual([]); - expect(retryButton(peekOf(view.container))).not.toBeNull(); + const panel = await commentsPanelOf(view.container, held); + expect(panelRetry(panel)).not.toBeNull(); - await act(async () => { fireEvent.click(retryButton(peekOf(view.container))!); }); + await act(async () => { fireEvent.click(panelRetry(panel)!); }); await settle(held); // One direct comment read (and its reactions), never the activity again. @@ -292,21 +315,21 @@ describe('objectstack#29188 — a failed comments read shows the load-failure no expect(readsOf(held, 'sys_activity')).toHaveLength(0); // The direct read answers an empty thread in this rig: the notice goes and // the empty state may speak now. - const peek = peekOf(view.container); - expect(failedSources(peek)).toEqual([]); - expect(retryButton(peek)).toBeNull(); - expect(peek.textContent).toContain(EMPTY_ACTIVITY); + expect(commentsNote(panel)).toBeNull(); + expect(panelRetry(panel)).toBeNull(); + expect(panelEmpty(panel)).toBe(true); }); it('a retry that fails again keeps the notice', async () => { const { held, open } = await bootDirect({ failGet: ['sys_comment'] }); const view = open(); await settle(held); - await act(async () => { fireEvent.click(retryButton(peekOf(view.container))!); }); + const panel = await commentsPanelOf(view.container, held); + await act(async () => { fireEvent.click(panelRetry(panel)!); }); await settle(held); expect(readsOf(held, 'sys_comment').length).toBeGreaterThanOrEqual(2); - expect(failedSources(peekOf(view.container))).toEqual(['comments']); - expect(peekOf(view.container).textContent).not.toContain(EMPTY_ACTIVITY); + expect(commentsNote(panel)).toBe('failed'); + expect(panelEmpty(panel)).toBe(false); }); }); @@ -318,8 +341,11 @@ describe('objectstack#29188 — a failed activity read shows the load-failure no const peek = peekOf(view.container); expect(failedSources(peek)).toEqual(['activity']); expect(peek.textContent).toContain(ACTIVITY_FAILED); - // The comment the discussion part carried still draws. - expect(peek.textContent).toContain('hello from the payload'); + // The comment the discussion part carried still draws, in the comment + // panel (objectstack#36075), with no notice there. + const panel = await commentsPanelOf(view.container, held); + expect(panel.textContent).toContain('hello from the payload'); + expect(commentsNote(panel)).toBeNull(); }); it('a 500 on a direct sys_activity read shows the notice', async () => { @@ -357,10 +383,12 @@ describe('objectstack#29188 — controls', () => { }); const view = open(); await settle(held); - const peek = peekOf(view.container); - expect(peek.querySelector('[data-denied-source="comments"]')).not.toBeNull(); - expect(failedSources(peek)).toEqual([]); - expect(retryButton(peek)).toBeNull(); + const panel = await commentsPanelOf(view.container, held); + expect(commentsNote(panel)).toBe('denied'); + expect(panelRetry(panel)).toBeNull(); + expect(panel.querySelector('[data-comments-composer]')).toBeNull(); + expect(failedSources(view.container)).toEqual([]); + expect(retryButton(view.container)).toBeNull(); }); }); @@ -387,15 +415,16 @@ describe('objectstack#30145 — navigating away from a failed feed read does not }); const view = open(); await settle(held); - expect(failedSources(peekOf(view.container))).toEqual(['comments']); + const panel = await commentsPanelOf(view.container, held); + expect(commentsNote(panel)).toBe('failed'); await act(async () => { navigate(view, 'c2'); }); await settle(held); - const peek = peekOf(view.container); - expect(failedSources(peek)).toEqual([]); - expect(retryButton(peek)).toBeNull(); - expect(peek.textContent).not.toContain(COMMENTS_FAILED); - expect(peek.textContent).toContain(EMPTY_ACTIVITY); + const after = await commentsPanelOf(view.container, held); + expect(commentsNote(after)).toBeNull(); + expect(panelRetry(after)).toBeNull(); + expect(after.textContent).not.toContain(COMMENTS_FAILED); + expect(panelEmpty(after)).toBe(true); }); it('record A settled on a failure; record B, answered with rows, draws its rows and no notice', async () => { @@ -404,14 +433,17 @@ describe('objectstack#30145 — navigating away from a failed feed read does not }); const view = open(); await settle(held); - expect(failedSources(peekOf(view.container)).sort()).toEqual(['activity', 'comments']); + expect(failedSources(peekOf(view.container))).toEqual(['activity']); + const panel = await commentsPanelOf(view.container, held); + expect(commentsNote(panel)).toBe('failed'); await act(async () => { navigate(view, 'c2'); }); await settle(held); - const peek = peekOf(view.container); - expect(failedSources(peek)).toEqual([]); - expect(peek.textContent).not.toMatch(/couldn't load/); - expect(peek.textContent).toContain('hello from the payload'); + expect(failedSources(view.container)).toEqual([]); + expect(view.container.textContent).not.toMatch(/couldn't load/); + const after = await commentsPanelOf(view.container, held); + expect(commentsNote(after)).toBeNull(); + expect(after.textContent).toContain('hello from the payload'); }); it('A\'s read is still outstanding when B is opened: B shows its own state, and A\'s failure settling late stays off B', async () => { 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 9d103cf9a82..1d3c31b2dcb 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.feedLoading.test.tsx @@ -48,7 +48,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataCtx } from '@object-ui/react'; @@ -170,6 +170,21 @@ function makeMetadata(pages: any[]) { } as any; } +/** + * objectstack#36075 — on the synthesized page the record's comments are the + * comment panel's, opened from the header's comments icon; the 动态 stream + * keeps the activity. + */ +async function openComments(): Promise { + const button = await waitFor(() => { + const el = document.querySelector('[data-comments-button]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + fireEvent.click(button); + return document.querySelector('[data-comments-panel]') as HTMLElement; +} + 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. @@ -190,6 +205,9 @@ function renderDetail(dataSource: any, pages: any[] = []) { beforeEach(() => { cleanup(); + // The comment panel's open state is kept in this browser (objectstack#36075): + // each case opens on a closed panel. + window.localStorage.clear(); // Unrelated chrome on this view (approvals, favourites, …) reaches for the // platform API. In jsdom that is a real socket to :3000 — noisy, slow and // machine-dependent. Answering it locally keeps the only asynchrony in this @@ -292,9 +310,10 @@ describe('RecordDetailView — the feed fetch produces a loading signal (#3209)' renderDetail(dataSource); - expect(await screen.findByText('First comment on the record')).toBeTruthy(); - expect(screen.queryByTestId('activity-loading')).toBeNull(); - expect(screen.queryByText(EMPTY_COMMENTS)).toBeNull(); + const panel = await openComments(); + expect(await within(panel).findByText('First comment on the record')).toBeTruthy(); + await waitFor(() => expect(screen.queryByTestId('activity-loading')).toBeNull()); + expect(panel.querySelector('[data-comments-empty]')).toBeNull(); }); // ── A rejected read is an ANSWER, not a permanent spinner ─────────────── @@ -311,11 +330,14 @@ describe('RecordDetailView — the feed fetch produces a loading signal (#3209)' renderDetail(dataSource); - // The refused comment read settles on its no-permission line, the 404 on - // nothing: an answer either way, never a spinner. - const notice = await screen.findByTestId('activity-access-denied'); - expect(notice.querySelector('[data-denied-source="comments"]')).not.toBeNull(); + // The 404 settles the stream on its empty copy and the refused comment + // read settles the comment panel on its no-permission line: an answer + // either way, never a spinner. + expect(await screen.findByText(EMPTY_COMMENTS)).toBeTruthy(); expect(screen.queryByTestId('activity-loading')).toBeNull(); + const panel = await openComments(); + await waitFor(() => expect(panel.querySelector('[data-comments-note="denied"]')).not.toBeNull()); + expect(within(panel).queryByRole('status')).toBeNull(); }); it('leaves the loading state when only one read rejects and the other resolves empty', async () => { @@ -348,7 +370,8 @@ describe('RecordDetailView — the feed fetch produces a loading signal (#3209)' renderDetail(dataSource); - expect(await screen.findByText('Survived the failed activity read')).toBeTruthy(); + const panel = await openComments(); + expect(await within(panel).findByText('Survived the failed activity read')).toBeTruthy(); await waitFor(() => expect(screen.queryByTestId('activity-loading')).toBeNull()); }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.feedRecordScope.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.feedRecordScope.test.tsx index 42e9afbe0ce..55d02634abe 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.feedRecordScope.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.feedRecordScope.test.tsx @@ -253,6 +253,16 @@ afterEach(() => { }); describe('RecordDetailView — the feed does not follow the user to the next record (#3268)', () => { + // objectstack#36075 — on the synthesized page the record's comments are the + // comment panel's: these open the drawer with it open (the reader left it + // so), and it stays open across the record→record navigation. + beforeEach(() => { + window.localStorage.setItem('os:record-comments-panel:drawer', 'open'); + }); + afterEach(() => { + window.localStorage.clear(); + }); + it('drops record A’s comment when the view navigates to record B', async () => { // The defect, verbatim from the issue: A’s comment stayed on B’s panel. const dataSource = makeDataSource({ @@ -330,6 +340,8 @@ describe('RecordDetailView — the feed does not follow the user to the next rec rerender(tree(dataSource, REC_B)); expect(await screen.findByText(EMPTY_COMMENTS)).toBeTruthy(); + // The comment panel settles on B's own empty state too. + await waitFor(() => expect(document.querySelector('[data-comments-panel] [data-comments-empty]')).not.toBeNull()); expect(screen.queryByText(commentFor(REC_A))).toBeNull(); await waitFor(() => expect(screen.queryByTestId('activity-loading')).toBeNull()); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index a6b8621667d..1c6a162683d 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -1577,7 +1577,8 @@ describe('RecordDetailView.relatedListTitlePlural-11733', () => { * for it; since objectstack#29188 it shows the load-failure notice, not * the empty state; * 5. a refused `sys_comment` read beside an answered `sys_activity` read - * keeps the activity rows and says the comments are withheld. + * keeps the activity rows and says the comments are withheld (since + * objectstack#36075 in the comment panel, which holds the comments). * * The harness is `RecordDetailView.feedLoading.test.tsx`'s: the synthesized * record page composes `record:discussion`, so the panel arrives through the @@ -1809,14 +1810,25 @@ describe('RecordDetailView.feedRefusal-11195', () => { }), }); + window.localStorage.clear(); renderDetail(dataSource); expect(await screen.findByText('Stage moved to qualified')).toBeTruthy(); - const notice = await screen.findByTestId('activity-access-denied'); - expect(notice.textContent).toContain(COMMENTS_DENIED); - expect(notice.textContent).not.toContain(ACTIVITY_DENIED); - expect(notice.querySelector('[data-denied-source="comments"]')).not.toBeNull(); - expect(notice.querySelector('[data-denied-source="activity"]')).toBeNull(); + // The 动态 stream holds no comments, so their refusal is not its to say. + expect(screen.queryByTestId('activity-access-denied')).toBeNull(); + const button = await waitFor(() => { + const el = document.querySelector('[data-comments-button]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + // The icon names no count for comments it may not read. + expect(button.querySelector('[data-comments-count]')).toBeNull(); + fireEvent.click(button); + const panel = document.querySelector('[data-comments-panel]') as HTMLElement; + expect(panel.querySelector('[data-comments-note="denied"]')).not.toBeNull(); + expect(panel.textContent).toContain(COMMENTS_DENIED); + expect(panel.textContent).not.toContain(ACTIVITY_DENIED); + expect(panel.querySelector('[data-comments-composer]')).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 3b4f00602ef..cf8abdfdc0b 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 @@ -183,8 +183,18 @@ beforeEach(() => { __resetRecordApprovalsStore(); RelatedCountStore._reset(); Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }); + window.localStorage.clear(); }); -afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); +afterEach(() => { cleanup(); vi.unstubAllGlobals(); window.localStorage.clear(); }); + +/** objectstack#36075 — the record's comments are drawn in the comment panel, opened from the header's icon. */ +async function openComments(container: HTMLElement, held: Held[]) { + const button = container.querySelector('[data-comments-button]') as HTMLElement | null; + expect(button, 'the header offers the comments icon').not.toBeNull(); + await act(async () => { fireEvent.click(button!); }); + await settle(held); + return container.querySelector('[data-comments-panel]') as HTMLElement; +} async function boot(answers: Answers = {}) { const { fetch, held } = heldTransport(answers); @@ -232,11 +242,15 @@ describe('objectstack#28470 — one record open is one request', () => { }); expect(page.body.related).toEqual([expect.objectContaining({ object: CHILD, field: 'contact', expand: ['owner'] })]); - // Every part is drawn from the payload: the comment, the attachment row - // and its badge's count. - expect(view.container.textContent).toContain('hello from the payload'); + // Every part is drawn from the payload: the comment (in the comment + // panel, which reads nothing more as it opens), the attachment row and its + // badge's count. expect(view.container.textContent).toContain('contract.pdf'); expect(RelatedCountStore.get('sys_attachment', recordAttachmentsCountField(OBJECT), 'c1')).toBe(3); + const before = held.length; + const panel = await openComments(view.container, held); + expect(panel.textContent).toContain('hello from the payload'); + expect(held.slice(before).filter((h) => !isMeta(h))).toEqual([]); }); it('reads the mention list on the composer\'s first focus, once', async () => { @@ -245,15 +259,13 @@ describe('objectstack#28470 — one record open is one request', () => { await settle(held); expect(mentionReads(held)).toEqual([]); - // objectstack#35595 / #35596 — the 概览 rail's 动态 card is read-only; the - // composer is the 动态 tab's. + // objectstack#35595 / #35596 — the 概览 rail's 动态 card is read-only; + // since objectstack#36075 the composer is the comment panel'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); + const panel = await openComments(view.container, 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(); + const editor = panel.querySelector('[data-comments-composer] textarea') as HTMLTextAreaElement | null; + expect(editor, 'the comment panel draws the composer').not.toBeNull(); await act(async () => { fireEvent.focus(editor!); }); await settle(held); expect(mentionReads(held)).toHaveLength(1); @@ -268,7 +280,8 @@ describe('objectstack#28470 — one record open is one request', () => { const view = open(); await settle(held); expect(view.container.querySelector('[data-denied-source="activity"]')).not.toBeNull(); - expect(view.container.textContent).toContain('hello from the payload'); + const panel = await openComments(view.container, held); + expect(panel.textContent).toContain('hello from the payload'); expect(streamReads(held)).toEqual([]); }); 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 84cd90ded22..d5b8fac7ed5 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 @@ -411,6 +411,7 @@ beforeEach(() => { __clearRecordEditableCache(); __resetRecordApprovalsStore(); RelatedCountStore._reset(); + window.localStorage.clear(); }); afterEach(() => { cleanup(); @@ -710,7 +711,16 @@ describe('the timeline, comments, attachments and user list wait for their panel for (const isRead of [isActivityRead, isCommentRead, isUserListRead]) { expect(held.filter(isRead), table).toEqual([]); } - expect(screen.getByText('Ping the buyer on Friday')).toBeTruthy(); + // objectstack#36075 — the comment is the comment panel's, drawn from the + // same payload: opening the panel reads nothing. + const commentsButton = document.querySelector('[data-comments-button]') as HTMLElement; + expect(commentsButton, table).not.toBeNull(); + await act(async () => { fireEvent.click(commentsButton); }); + const panel = document.querySelector('[data-comments-panel]') as HTMLElement; + expect(panel.textContent).toContain('Ping the buyer on Friday'); + for (const isRead of [isActivityRead, isCommentRead, isUserListRead]) { + expect(held.filter(isRead), table).toEqual([]); + } }); it('CONTROL: the synthesized page opened on its 动态 tab (?related=timeline) asks the feed with its page at open', async () => { 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 9322f8420ff..e798f70a8bf 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 @@ -34,7 +34,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { act, render, screen, cleanup, waitFor } from '@testing-library/react'; +import { act, render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { MetadataCtx } from '@object-ui/react'; import { RelatedCountStore } from '@object-ui/components'; @@ -373,7 +373,7 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta await expectTabRowOnly(); }); - it('`?tab=` addresses no strip on a laid-out page; `?related=timeline` is the 动态 tab: the full stream with its chips', async () => { + it('`?tab=` addresses no strip on a laid-out page; `?related=timeline` is the 动态 tab: the full stream', async () => { const tabbed = renderPage({ width: 720, search: '?tab=related' }); await screen.findAllByText('Tasks', undefined, { timeout: 5000 }); expect(tierOf(tabbed.container)).toBe('stack'); @@ -391,6 +391,8 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta { timeout: 5000 }, ); expect(face.getAttribute('aria-label')).toBe('Activity'); + // objectstack#36075 — the comment panel holds the comments, so the stream + // holds the system entries alone: of its chips only 变更 stays. expect(face.querySelector('[data-stream-filters]')).not.toBeNull(); expect(face.querySelector('[data-record-timeline-peek]')).toBeNull(); await expectTabRowOnly('timeline'); @@ -400,17 +402,22 @@ describe('RecordDetailView — one record page, laid out by its width (objectsta }); }); -describe('RecordDetailView — the 动态 tab offers 变更 only while the record shows its field history (objectstack#30074)', () => { +/** + * objectstack#30074 offers the 动态 tab's 变更 chip only while the record shows + * its field history. Since objectstack#36075 the comment panel holds the + * comments on the desktop, so 全部 / 活动 / 讨论 go and 变更 alone stays, on + * the same rule; pressed again it goes back to every entry. + */ +describe('RecordDetailView — the 动态 tab offers 变更 only while the record shows its field history (objectstack#30074, objectstack#36075)', () => { /** The full stream's chips, in order, once the 动态 tab has drawn. */ - const streamChips = async (container: HTMLElement) => - waitFor( - () => { - const chips = container.querySelectorAll('[data-related-enlarged="timeline"] [data-stream-filter]'); - expect(chips.length).toBeGreaterThan(0); - return Array.from(chips).map((chip) => chip.getAttribute('data-stream-filter')); - }, - { timeout: 5000 }, + const streamChips = async (container: HTMLElement) => { + await waitFor(() => expect(container.querySelector('[data-related-enlarged="timeline"]')).not.toBeNull(), { + timeout: 5000, + }); + return Array.from(container.querySelectorAll('[data-related-enlarged="timeline"] [data-stream-filter]')).map((chip) => + chip.getAttribute('data-stream-filter'), ); + }; /** The chips once this reader's audit read has gone out and settled. */ const streamChipsAfterAuditRead = async (container: HTMLElement) => { @@ -422,27 +429,32 @@ describe('RecordDetailView — the 动态 tab offers 变更 only while the recor return streamChips(container); }; - it('an object with `enable.trackHistory`, its audit read answered: 全部 / 活动 / 讨论 / 变更', async () => { + it('an object with `enable.trackHistory`, its audit read answered: 变更 alone, a toggle', async () => { const { container } = renderPage({ width: 1440, search: '?related=timeline' }); - expect(await streamChipsAfterAuditRead(container)).toEqual(['all', 'activity', 'discussion', 'changes']); + await waitFor(async () => expect(await streamChipsAfterAuditRead(container)).toEqual(['changes']), { timeout: 5000 }); + const chip = container.querySelector('[data-related-enlarged="timeline"] [data-stream-filter="changes"]') as HTMLElement; + expect(chip.getAttribute('aria-pressed')).toBe('false'); + fireEvent.click(chip); + expect(chip.getAttribute('aria-pressed')).toBe('true'); + fireEvent.click(chip); + expect(chip.getAttribute('aria-pressed')).toBe('false'); }); - it('the same object without it: no 变更 chip, and no audit read', async () => { + it('the same object without it: no chip, and no audit read', async () => { const untracked = OBJECTS.map((o) => (o.name === PARENT ? { ...o, enable: undefined } : o)) as typeof OBJECTS; const { container } = renderPage({ width: 1440, search: '?related=timeline', objects: untracked }); - expect(await streamChips(container)).toEqual(['all', 'activity', 'discussion']); + expect(await streamChips(container)).toEqual([]); expect(auditReads()).toBe(0); }); - // objectstack#30344 — the field history this record page shows is the one - // THIS reader's audit read answers: a reader the server refuses it to has + // objectstack#30344 — a reader the server refuses the audit read to has // nothing for 变更 to hold, so the chip is not offered, as with history off. - it('a reader whose audit read is refused (403): no 变更 chip, as with history off', async () => { + it('a reader whose audit read is refused (403): no chip, as with history off', async () => { const { container } = renderPage({ width: 1440, search: '?related=timeline', auditRead: () => Promise.reject(rejection(403, 'PERMISSION_DENIED')), }); - expect(await streamChipsAfterAuditRead(container)).toEqual(['all', 'activity', 'discussion']); + expect(await streamChipsAfterAuditRead(container)).toEqual([]); }); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.replyCountOnRead-12144.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.replyCountOnRead-12144.test.tsx index 85085a79bed..55df9f37278 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.replyCountOnRead-12144.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.replyCountOnRead-12144.test.tsx @@ -20,6 +20,13 @@ * `onAddReply` for, replies or not. Its reply LIST still shows only under a * `replyCount` above zero, the one gate it had. * + * Since objectstack#36075 the default page draws the record's comments in its + * comment panel, opened from the header's comments icon: a thread folds its + * replies to 「N replies」 there and opens them in place, and a comment's Reply + * opens the thread's reply box. The same read, the same counts and the same + * grant decide what it offers; an authored page's feed block (the control + * below) is as it was. + * * Real subjects: `RecordDetailView` rendering the SYNTHESIZED default record * page (no authored page, so `buildDefaultPageSchema` composes * `record:discussion`), over a fake data source answering the `sys_comment` @@ -190,6 +197,15 @@ async function mount(comments: Record[], options: MountOptions const perms = options.perms ?? null; const rendered = render(perms ? {page} : page); const view = within(rendered.container); + if (!options.pages?.length) { + // The default page: its comments are the comment panel's. + const button = await waitFor(() => { + const el = rendered.container.querySelector('[data-comments-button]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + fireEvent.click(button); + } await view.findByText(String(comments[0].body)); await waitFor(() => expect(view.queryByTestId('activity-loading')).toBeNull()); await act(async () => {}); @@ -214,19 +230,22 @@ const replyInputs = (view: View) => { /** The reply-count toggle `ThreadedReplies` draws above a comment's replies. */ const replyToggles = (view: View) => view.queryAllByRole('button', { name: /\d+ repl/ }); -/** - * The feed row a body sits in: the element the timeline keys per root item, - * which holds the item's own row and, after it, its `ThreadedReplies`. - */ -function rootRowOf(view: View, body: string): HTMLElement { - openReplies(); - // The keyed comment (or one-line) row since the dense rows (objectstack#35602). - const row = view.getByText(body).closest('[data-stream-comment-row],[data-stream-row]'); - if (!row) throw new Error(`no feed row holds ${JSON.stringify(body)}`); - return row as HTMLElement; +/** The comment panel, and one thread in it by its first comment's text. */ +const panelOf = () => document.querySelector('[data-comments-panel]') as HTMLElement; +function threadOf(body: string): HTMLElement { + const thread = within(panelOf()).getByText(body).closest('[data-comment-thread]'); + if (!thread) throw new Error(`no thread holds ${JSON.stringify(body)}`); + return thread as HTMLElement; } +/** A comment's own Reply in its action row, or `null` where none is offered. */ +const replyActionOf = (body: string) => { + const item = within(panelOf()).getByText(body).closest('[data-comment-item]') as HTMLElement; + return item.querySelector(':scope > [data-comment-actions] [data-comment-action="reply"]') as HTMLButtonElement | null; +}; +const panelReplyActions = () => panelOf().querySelectorAll('[data-comment-action="reply"]'); beforeEach(() => { + window.localStorage.clear(); vi.stubGlobal( 'fetch', vi.fn(async () => @@ -242,67 +261,64 @@ afterEach(() => { }); describe('a stored reply shows under its parent on the default record page (objectui#12144)', () => { - it('a read with a parent and one child shows the child under the parent, not as a row of its own', async () => { - const { view } = await mount([PARENT, CHILD]); - // Collapsed until asked: the reply is not on screen yet, and not as a root row either. - expect(view.queryByText(CHILD_BODY)).toBeNull(); - // `rootRowOf` presses 「回复」, which expands the replies first (objectstack#36070). - const parentRow = rootRowOf(view, PARENT_BODY); - expect(within(parentRow).getByText(CHILD_BODY)).toBeInTheDocument(); - expect(replyToggles(view)).toHaveLength(1); - // The count toggle still folds them away. - fireEvent.click(within(parentRow).getByRole('button', { name: /1 reply/ })); - expect(view.queryByText(CHILD_BODY)).toBeNull(); + it('a read with a parent and one child shows the child under the parent, not as a thread of its own', async () => { + await mount([PARENT, CHILD]); + const thread = threadOf(PARENT_BODY); + // Collapsed until asked: the reply is not on screen yet, and not as a thread either. + expect(within(panelOf()).queryByText(CHILD_BODY)).toBeNull(); + expect(panelOf().querySelectorAll('[data-comment-thread]')).toHaveLength(1); + fireEvent.click(within(thread).getByRole('button', { name: /1 reply/ })); + expect(within(thread).getByText(CHILD_BODY)).toBeInTheDocument(); }); it('the count is the children in the read: two stored replies read as two', async () => { const second = { ...CHILD, id: 'c-child-2', body: 'Second stored reply', created_at: '2026-10-01T09:30:00.000Z' }; - const { view } = await mount([PARENT, CHILD, second]); - const parentRow = rootRowOf(view, PARENT_BODY); - // Expanded by 「回复」 (objectstack#36070); the toggle reads the count. - expect(within(parentRow).getByRole('button', { name: /2 replies/ })).toBeInTheDocument(); - expect(within(parentRow).getByText(CHILD_BODY)).toBeInTheDocument(); - expect(within(parentRow).getByText('Second stored reply')).toBeInTheDocument(); + await mount([PARENT, CHILD, second]); + const thread = threadOf(PARENT_BODY); + fireEvent.click(within(thread).getByRole('button', { name: /2 replies/ })); + expect(within(thread).getByText(CHILD_BODY)).toBeInTheDocument(); + expect(within(thread).getByText('Second stored reply')).toBeInTheDocument(); }); }); -describe('a comment read from the server offers the reply input where the caller may post one (objectui#12144)', () => { - it('under a create grant on sys_comment every comment row offers it, a comment with no replies included', async () => { - const { view } = await mount([PARENT, CHILD, LONE], { perms: answer(CREATE_ONLY) }); - expect(within(rootRowOf(view, LONE_BODY)).queryByPlaceholderText(REPLY_PLACEHOLDER)).not.toBeNull(); - expect(within(rootRowOf(view, PARENT_BODY)).queryByPlaceholderText(REPLY_PLACEHOLDER)).not.toBeNull(); - expect(replyInputs(view)).toHaveLength(2); +describe('a comment read from the server offers Reply where the caller may post one (objectui#12144)', () => { + it('under a create grant on sys_comment every comment offers it, a comment with no replies included', async () => { + await mount([PARENT, CHILD, LONE], { perms: answer(CREATE_ONLY) }); + expect(replyActionOf(LONE_BODY)).not.toBeNull(); + expect(replyActionOf(PARENT_BODY)).not.toBeNull(); + // Reply opens the thread with its reply box. + fireEvent.click(replyActionOf(LONE_BODY)!); + expect(within(threadOf(LONE_BODY)).getByPlaceholderText(REPLY_PLACEHOLDER)).toBeInTheDocument(); }); - it('a row that is not a comment offers none: a reply is stored as a sys_comment under a comment', async () => { + it('a row that is not a comment is not the panel\'s: a reply is stored as a sys_comment under a comment', async () => { const { view } = await mount([LONE], { activities: [UPDATED] }); await view.findByText(ACTIVITY_BODY); - expect(within(rootRowOf(view, ACTIVITY_BODY)).queryByPlaceholderText(REPLY_PLACEHOLDER)).toBeNull(); - expect(replyInputs(view)).toHaveLength(1); + expect(within(panelOf()).queryByText(ACTIVITY_BODY)).toBeNull(); + expect(panelReplyActions()).toHaveLength(1); }); it('the first reply on a comment posts from the page, under that comment, and then shows there', async () => { - const { view, dataSource } = await mount([LONE], { perms: answer(CREATE_ONLY) }); - const loneRow = rootRowOf(view, LONE_BODY); - fireEvent.change(within(loneRow).getByPlaceholderText(REPLY_PLACEHOLDER), { target: { value: NEW_REPLY } }); + const { dataSource } = await mount([LONE], { perms: answer(CREATE_ONLY) }); + fireEvent.click(replyActionOf(LONE_BODY)!); + const box = within(threadOf(LONE_BODY)).getByPlaceholderText(REPLY_PLACEHOLDER); + fireEvent.change(box, { target: { value: NEW_REPLY } }); await act(async () => { - fireEvent.click(within(loneRow).getByRole('button', { name: 'Send reply' })); + fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true }); }); expect(dataSource.create).toHaveBeenCalledTimes(1); expect(dataSource.create.mock.calls[0][0]).toBe(COMMENT); expect(dataSource.create.mock.calls[0][1]).toMatchObject({ thread_id: THREAD, parent_id: 'c-lone', body: NEW_REPLY }); - // The reply opened behind 「回复」 expanded the thread (objectstack#36070), so - // the new reply shows at once under its count. - expect(within(loneRow).getByRole('button', { name: /1 reply/ })).toBeInTheDocument(); - expect(within(loneRow).getByText(NEW_REPLY)).toBeInTheDocument(); + await waitFor(() => expect(within(threadOf(LONE_BODY)).getByText(NEW_REPLY)).toBeInTheDocument()); }); - it('without the create grant no row offers it, and a stored reply still shows under its parent', async () => { - const { view } = await mount([PARENT, CHILD, LONE], { perms: answer(READ_ONLY) }); - expect(replyInputs(view)).toHaveLength(0); - const parentRow = rootRowOf(view, PARENT_BODY); - fireEvent.click(within(parentRow).getByRole('button', { name: /1 reply/ })); - expect(within(parentRow).getByText(CHILD_BODY)).toBeInTheDocument(); + it('without the create grant no comment offers it, and a stored reply still shows under its parent', async () => { + await mount([PARENT, CHILD, LONE], { perms: answer(READ_ONLY) }); + expect(panelReplyActions()).toHaveLength(0); + expect(panelOf().querySelector('[data-comments-composer]')).toBeNull(); + const thread = threadOf(PARENT_BODY); + fireEvent.click(within(thread).getByRole('button', { name: /1 reply/ })); + expect(within(thread).getByText(CHILD_BODY)).toBeInTheDocument(); }); }); 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 ecc5447a942..87b2a548b4c 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 @@ -242,7 +242,9 @@ describe('objectstack#28737 — the 动态 count is the server\'s, and the page const [page] = held.filter(isPage); expect(page.body.activity).toEqual({ top: 5 }); expect(page.body.timeline).toEqual({ discussion: true, activity: true, fieldChanges: false }); - expect(chipOf(view.container)).toBe('341'); + // objectstack#36075 — the comment panel holds the record's one comment, + // so the 动态 count is the served total without it. + expect(chipOf(view.container)).toBe('340'); expect(activityReads(held)).toEqual([]); // The 动态 tab draws the whole stream: it reads the window once, and the @@ -252,7 +254,7 @@ describe('objectstack#28737 — the 动态 count is the server\'s, and the page await settle(held); expect(activityReads(held)).toHaveLength(1); expect(activityReads(held)[0].path).toMatch(/[?&]\$?top=200\b/); - expect(view.container.textContent).toContain('341'); + expect(view.container.textContent).toContain('340'); }); it('a record with none shows 0 and makes no fallback read, the 动态 tab opened included', async () => { @@ -285,8 +287,9 @@ describe('objectstack#28737 — the 动态 count is the server\'s, and the page const { held, open } = await boot({ activity: { total: 330, records: ROWS(5) } }); const view = open(); await settle(held); - // One comment + five activity rows: what the page holds, not the record's stream. - expect(chipOf(view.container)).toBe('6'); + // Five activity rows: what the page holds, not the record's stream; the + // one comment is the comment panel's (objectstack#36075). + expect(chipOf(view.container)).toBe('5'); }); }); @@ -334,7 +337,8 @@ describe('objectstack#30035 — the 动态 stream is read again after a save', ( const { held, open, ds } = await boot(answers, undefined, ALL, embedded); const view = open(); await settle(held); - expect(chipOf(view.container)).toBe('2'); + // The served 2 less the comment the comment panel holds (objectstack#36075). + expect(chipOf(view.container)).toBe('1'); expect(view.container.textContent).not.toContain('changed the amount'); const before = held.length; @@ -349,7 +353,7 @@ describe('objectstack#30035 — the 动态 stream is read again after a save', ( for (const [surface, embedded] of [['the record page', false], ['the drawer', true]] as const) { 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'); + expect(chipOf(view.container)).toBe('2'); // 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'); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index af008bd9c31..9a86e2e3c4a 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -10,7 +10,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; -import { activityRowToFeedItem, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, isRefusedFeedRead, recordPageTierHasRightColumn, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, isRefusedFeedRead, recordPageTierHasRightColumn, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; import { Empty, EmptyTitle, EmptyDescription, Button, PageHeaderActions, PageHeaderPhoneContext, PageHeaderTrailingContext, PanelToggles, ObjectIconTile, RecordHeaderBarContext, RecordHeaderStateContext, RecordTopBar, RecordTopBarButton, cn, useRecordStepKeys, type PanelToggleItem, type RecordHeaderBar, type RecordHeaderGroupParts, type RecordHeaderState, type RecordTopBarStepper } from '@object-ui/components'; import { isActingApprover } from '../utils/approvalDecisionFold.js'; import { useAuth, createAuthenticatedFetch } from '@object-ui/auth'; @@ -41,7 +41,8 @@ import { RecordEditStateController, bodyTablesSaveTogether, isMasterDetailChild, import { isRecordPagePushed, useRecordPageScrollMemory } from './recordPagePush.js'; import { phoneRecordHeader } from './recordPhoneHeader.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; -import { PrefetchUpcomingRelatedCounts, RecordDrawerUpcomingContext, RecordPageDrawerHost, RecordPaneBarToggles, useRecordPane, useRecordPaneBar, useRecordPageReturn } from './recordDrawerStack.js'; +import { PrefetchUpcomingRelatedCounts, RecordDrawerUpcomingContext, RecordPageDrawerHost, RecordPaneBarComments, RecordPaneBarToggles, useRecordPane, useRecordPaneBar, useRecordPageReturn } from './recordDrawerStack.js'; +import { COMMENTS_PANEL_WIDTH, RecordCommentsAside, commentsPanelPlacement, useCommentsPanelOpen, useElementWidth, useWindowWidth } from './recordCommentsPanel.js'; import { RECORD_PAGE_ACTIVITY_ROWS, RECORD_PAGE_ATTACHMENT_ROWS, @@ -1265,7 +1266,31 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // one commit rather than drawn at a width it does not have. const [pageRootEl, setPageRootEl] = useState(null); const pageColumnsEligible = !assignedPage && !namedPageBlocked; - const recordPageTier = useRecordPageTier(pageRootEl, { enabled: pageColumnsEligible }); + // ─── The record's comment panel (objectstack#36075) ────────────────── + // Offered on the desktop, page and drawer, wherever the page draws the + // platform's own 动态 stream: the default page and a slotted one. That is + // where the stream gives its comments up to the panel; a page whose author + // composed it keeps its discussion where the author put it (a page is what + // its author composes), and an object with feeds off has none. The phone's + // comment page is its own surface. Open or closed is the reader's, kept per + // page and per drawer; beside the record it takes 380 px from the page, + // whose tier is judged on what is left. + const commentsPhone = usePhoneViewport(); + const commentsPanelOffered = + !!objectDef && objectDef.enable?.feeds !== false && pageColumnsEligible && !commentsPhone && !!pureRecordId; + const [commentsOpenChosen, setCommentsOpen] = useCommentsPanelOpen(embedded ? 'drawer' : 'page'); + const commentsOpen = commentsPanelOffered && commentsOpenChosen; + const commentsWindowWidth = useWindowWidth(); + const commentsHostWidth = useElementWidth(embedded ? pageRootEl : null); + const commentsPlacement = commentsPanelPlacement({ + embedded: !!embedded, + windowWidth: commentsWindowWidth, + hostWidth: commentsHostWidth, + }); + const recordPageTier = useRecordPageTier(pageRootEl, { + enabled: pageColumnsEligible, + reservedWidth: commentsOpen && commentsPlacement === 'beside' ? COMMENTS_PANEL_WIDTH : 0, + }); const pageLaidOut = recordPageTier !== null; const pageHasRightColumn = recordPageTierHasRightColumn(recordPageTier); // ─── The reader's right-column switch ⊟ (objectstack#27052, #27524) ── @@ -2678,7 +2703,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // it opens later (the window effect below). const timelineDrawnOnOpen = feedOnOpen && pageColumnsEligible && !!feedPageOnOpen && buildDefaultPageColumns(feedPageOnOpen) !== null; const timelinePeekOnOpen = timelineDrawnOnOpen && enlargedRelatedParam !== RECORD_PAGE_TIMELINE_PANEL; - const streamDiscussion = feedOnOpen && objectDef?.enable?.feeds !== false; + const streamDiscussion = (feedOnOpen || commentsPanelOffered) && objectDef?.enable?.feeds !== false; const streamActivity = feedOnOpen && objectDef?.enable?.activities !== false; const recordPageStreams = { ...(streamDiscussion ? { discussion: true } : {}), @@ -2959,7 +2984,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // Recorded during render, React's pattern for state derived from an earlier // render: no effect, and no render that reads the latch unset. if (feedConsumerOnScreen && !feedConsumerShown) setFeedConsumerShown(true); - const feedWanted = feedConsumerOnScreen || feedConsumerShown; + // The activity is read for a block that draws it; the discussion also for + // the comment panel (objectstack#36075), whose icon counts the threads at + // open, panel closed — so the discussion rides the open's payload. + const activityFeedWanted = feedConsumerOnScreen || feedConsumerShown; + const feedWanted = activityFeedWanted || commentsPanelOffered; // The host's own Attachments panel, appended at the page foot for a page // that places none (below), is mounted on every open but drawn below the @@ -3317,8 +3346,14 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const feedRecordKey = objectName && pureRecordId ? `${objectName}:${pureRecordId}` : null; const feedItems = (feedRecordKey ? feedItemsByRecord[feedRecordKey] : undefined) ?? EMPTY_FEED; const feedVerdict = feedRecordKey ? feedVerdictByRecord[feedRecordKey] : undefined; + // objectstack#36075 — the feed is read in two steps where the comment panel + // asks the discussion before any block asks the activity: the key moves + // when the activity joins, so the feed shows its loading state again until + // that read answers (the panel keeps the threads it holds meanwhile). const feedFetchKey = - dataSource && feedRecordKey && (feedsEnabled || activitiesEnabled) ? feedRecordKey : null; + dataSource && feedRecordKey && (feedsEnabled || activitiesEnabled) + ? (activityFeedWanted || !activitiesEnabled ? feedRecordKey : `${feedRecordKey}#discussion`) + : null; const [settledFeedKey, setSettledFeedKey] = useState(null); const feedLoading = feedFetchKey !== null && settledFeedKey !== feedFetchKey; @@ -3611,7 +3646,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // activity to sees the panel say so, not "no activity". The verdict is // `isRefusedFeedRead`, the one the `record:activity` block's self-fetch // uses, so the two surfaces cannot disagree about what a refusal is. - const activityRead: Promise | null = !activitiesEnabled || (retrying && !retrying.has('activity')) + const activityRead: Promise | null = !activitiesEnabled || !activityFeedWanted || (retrying && !retrying.has('activity')) ? null : fromPage?.activity // objectstack#28470 — the payload's activity: the newest rows it @@ -3684,7 +3719,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // objectstack#30035 — `recordInvalidationNonce`: a change to this record // reads its feed again (#2269, refresh data in place), as it reads the // record again in the record-load effect above. - }, [dataSource, objectName, pureRecordId, currentUser, feedsEnabled, activitiesEnabled, feedFetchKey, reactionStore, feedWanted, feedPlanReady, feedRetryNonce, recordInvalidationNonce]); + }, [dataSource, objectName, pureRecordId, currentUser, feedsEnabled, activitiesEnabled, activityFeedWanted, feedFetchKey, reactionStore, feedWanted, feedPlanReady, feedRetryNonce, recordInvalidationNonce]); // objectstack#29188 — the load-failure notice's Retry: read this record's // FAILED feed reads again, and only those. The feed shows its loading state @@ -3746,9 +3781,19 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // comment writes. `null` (no count answered): the stream counts its rows. const timelineServed = feedRecordKey ? timelineCountByRecord[feedRecordKey] ?? null : null; const heldCommentCount = useMemo(() => feedItems.filter((item) => item.type === 'comment').length, [feedItems]); + // objectstack#36075 — where the comment panel holds the comments, the 动态 + // stream names its system entries alone. const timelineTotal = timelineServed - ? Math.max(0, timelineServed.total - timelineServed.comments + heldCommentCount) + ? Math.max(0, timelineServed.total - timelineServed.comments + (commentsPanelOffered ? 0 : heldCommentCount)) : null; + // The comments icon's number: the record's threads (its top-level comments), + // unknown while the read was refused or failed. + const commentThreadCount = useMemo(() => buildCommentThreads(feedItems).length, [feedItems]); + const commentsCount = + feedVerdict?.comments === 'refused' || feedVerdict?.comments === 'failed' ? null : commentThreadCount; + const commentsButton = commentsPanelOffered ? ( + + ) : null; /** * Note: comment-mention → notification fan-out lives on the server @@ -5464,6 +5509,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri stepper={pageStepper} actionSlotRef={setBarActionSlot} toggles={approvalQueueSwitch || panelToggles ? <>{approvalQueueSwitch}{panelToggles} : undefined} + comments={commentsButton} frame={pageFrame} record={pageRecordRow} /> @@ -5622,6 +5668,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri {pageBar} {/* In a pane, the record's ⊟ goes into the pane's own top bar. */} {embedded && paneBar && {panelToggles}} + {embedded && paneBar && {commentsButton}} {/* On a print page the shared chrome joins the print chrome row below, so the row's buttons are not drawn under it. On the page it sits under the top bar, where it sat before the bar. */} @@ -5766,6 +5813,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri {/* objectstack#27055 — the field changes of the timeline stream, for the synthesized page's `record:activity`; on an assigned page, for its feed blocks (objectstack#33996). */} + {/* objectstack#30074 — whether this record shows its field history (objectstack#30344: to this reader, whose audit read answered): @@ -5805,7 +5853,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri onModal={modalHandler} handlers={{ api: apiActionHandler, flow: flowHandler, script: serverActionHandler, modal: modalActionHandler }} > -
+
{/* objectstack#35745 — no top padding here: the record page under it pads its own top (`RecordPageColumns`, the `page` root), so the tab row sits 12px under the header instead of under a 48px @@ -5912,7 +5960,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // A record drawn with no top bar of its own (a host's plain // overlay, not the console's pane) keeps its ⊟ at the end of // the header's action row. - + {commentsButton}{panelToggles} : null} + > }
+ {/* objectstack#36075 — the record's comment panel: beside the + record (which gives it the width), or over it. */} + {commentsOpen && ( + setCommentsOpen(false)} /> + )} + diff --git a/ui/packages/app-shell/src/views/recordCommentsPanel-36075.test.ts b/ui/packages/app-shell/src/views/recordCommentsPanel-36075.test.ts new file mode 100644 index 00000000000..0992c2492cd --- /dev/null +++ b/ui/packages/app-shell/src/views/recordCommentsPanel-36075.test.ts @@ -0,0 +1,31 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36075, item 4 — where the comment panel is drawn: beside the + * record from a 1280 window (the record gives way 380), over its right edge + * below that; inside a drawer, beside the record from a 760 drawer body + * (the record keeps at least the panel's width), over the whole body below. + */ + +import { describe, it, expect } from 'vitest'; +import { + COMMENTS_PANEL_BESIDE_MIN_WINDOW, + COMMENTS_PANEL_DRAWER_SPLIT_MIN_WIDTH, + COMMENTS_PANEL_WIDTH, + commentsPanelPlacement, +} from './recordCommentsPanel'; + +describe('commentsPanelPlacement', () => { + it('the page: beside from a 1280 window, over below it', () => { + expect(COMMENTS_PANEL_WIDTH).toBe(380); + expect(COMMENTS_PANEL_BESIDE_MIN_WINDOW).toBe(1280); + expect(commentsPanelPlacement({ embedded: false, windowWidth: 1280, hostWidth: 0 })).toBe('beside'); + expect(commentsPanelPlacement({ embedded: false, windowWidth: 1279, hostWidth: 2000 })).toBe('over'); + }); + + it('the drawer: beside from a 760 body, a cover of the body below it (the default 720 drawer)', () => { + expect(COMMENTS_PANEL_DRAWER_SPLIT_MIN_WIDTH).toBe(760); + expect(commentsPanelPlacement({ embedded: true, windowWidth: 1920, hostWidth: 760 })).toBe('beside'); + expect(commentsPanelPlacement({ embedded: true, windowWidth: 1920, hostWidth: 720 })).toBe('cover'); + }); +}); diff --git a/ui/packages/app-shell/src/views/recordCommentsPanel.drawerEscape-36075.test.tsx b/ui/packages/app-shell/src/views/recordCommentsPanel.drawerEscape-36075.test.tsx new file mode 100644 index 00000000000..e11e980957a --- /dev/null +++ b/ui/packages/app-shell/src/views/recordCommentsPanel.drawerEscape-36075.test.tsx @@ -0,0 +1,129 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36075 — in the record drawer, Esc pressed in the comment panel + * closes the panel and returns to the record, as ✕ does: the drawer neither + * closes nor steps back on it, at the stack's root (a record opened from the + * list) or below it. The focus goes back to the comments icon. + * + * Pinned through the REAL drawer (`NavigationOverlay`, whose dialog layer + * hears Esc on the document in the capture phase, ahead of the panel) around + * the REAL panel (`RecordCommentsAside` → `CommentsPanel`). The CONTROL: an + * Esc pressed in the record outside the panel still does what it did. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; +import { NavigationOverlay, type NavigationOverlayProps } from '@object-ui/components'; +import { DiscussionContextProvider } from '@object-ui/react'; +import { RecordCommentsAside } from './recordCommentsPanel'; + +const ITEMS = [ + { id: 'c1', type: 'comment', actor: 'Ada', body: 'first thread', createdAt: '2026-10-01T08:00:00.000Z' }, +]; + +function Record() { + const [open, setOpen] = React.useState(true); + return ( + +
+ + + {open && setOpen(false)} />} +
+
+ ); +} + +function renderDrawer(props: Partial = {}) { + const setIsOpen = vi.fn(); + const close = vi.fn(); + render( + list
} + close={close} + setIsOpen={setIsOpen} + title="Account" + {...props} + > + {() => } + , + ); + return { setIsOpen, close }; +} + +const panel = () => document.querySelector('[data-comments-panel]') as HTMLElement | null; +const composer = () => within(document.querySelector('[data-comments-composer]') as HTMLElement).getByRole('textbox'); +const esc = (target: Element) => fireEvent.keyDown(target, { key: 'Escape' }); + +beforeEach(() => { + try { + window.localStorage.clear(); + } catch { + /* private mode */ + } +}); +afterEach(cleanup); + +describe.each([ + ['at the stack’s root (a record opened from the list)', false], + ['below the root', true], +])('the record drawer, %s', (_label, below) => { + it.each([ + ['the comment box', () => composer()], + ['the panel’s ✕', () => screen.getByRole('button', { name: 'Close comments' })], + ])('Esc in %s closes the panel and returns to the record', (_where, target) => { + const onBack = vi.fn(); + const { setIsOpen, close } = renderDrawer(below ? { onBack } : {}); + const el = target(); + el.focus(); + esc(el); + expect(panel()).toBeNull(); + expect(onBack).not.toHaveBeenCalled(); + expect(setIsOpen).not.toHaveBeenCalledWith(false); + expect(close).not.toHaveBeenCalled(); + expect(screen.getByRole('dialog', { name: 'Account' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Comments icon' })).toHaveFocus(); + }); + + it('Esc in the @ list closes the list only: the panel and the drawer stay', () => { + const onBack = vi.fn(); + const { setIsOpen } = renderDrawer(below ? { onBack } : {}); + const box = composer(); + box.focus(); + fireEvent.change(box, { target: { value: 'ask @', selectionStart: 5 } }); + expect(screen.getByRole('button', { name: /Zoe/ })).toBeInTheDocument(); + esc(box); + expect(screen.queryByRole('button', { name: /Zoe/ })).toBeNull(); + expect(panel()).not.toBeNull(); + expect(box).toHaveValue('ask @'); + expect(onBack).not.toHaveBeenCalled(); + expect(setIsOpen).not.toHaveBeenCalledWith(false); + }); + + it('CONTROL: Esc on a record control outside the panel does what the drawer always did', () => { + const onBack = vi.fn(); + const { setIsOpen, close } = renderDrawer(below ? { onBack } : {}); + const action = screen.getByRole('button', { name: 'Record action' }); + action.focus(); + esc(action); + if (below) { + expect(onBack).toHaveBeenCalledTimes(1); + } else { + expect(setIsOpen.mock.calls.some(([v]) => v === false) || close.mock.calls.length > 0).toBe(true); + } + }); +}); diff --git a/ui/packages/app-shell/src/views/recordCommentsPanel.tsx b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx new file mode 100644 index 00000000000..15b8015002b --- /dev/null +++ b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx @@ -0,0 +1,143 @@ +/** + * 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 { useCallback, useEffect, useRef, useState } from 'react'; +import { cn } from '@object-ui/components'; +import { CommentsPanel } from '@object-ui/plugin-detail'; + +/** The comment panel's width on the desktop (objectstack#36075, item 4). */ +export const COMMENTS_PANEL_WIDTH = 380; + +/** + * From this window width the record page gives the panel its 380 px; a + * narrower window draws the panel over the page instead. + */ +export const COMMENTS_PANEL_BESIDE_MIN_WINDOW = 1280; + +/** + * From this drawer width the panel sits beside the record inside the drawer, + * leaving the record at least as wide as the panel; a narrower drawer (the + * default `md`, 720) gives the panel the whole drawer body. + */ +export const COMMENTS_PANEL_DRAWER_SPLIT_MIN_WIDTH = 2 * COMMENTS_PANEL_WIDTH; + +/** + * Where the open panel is drawn: `beside` the record, which gives it the + * width; `over` the page's right edge (a window under 1280); or as a `cover` + * of the whole drawer body (a drawer under 760). + */ +export type CommentsPanelPlacement = 'beside' | 'over' | 'cover'; + +export function commentsPanelPlacement({ + embedded, + windowWidth, + hostWidth, +}: { + /** The record is drawn in a drawer or pane, not on its own page. */ + embedded: boolean; + windowWidth: number; + /** The width of the record view itself (the drawer's body when embedded). */ + hostWidth: number; +}): CommentsPanelPlacement { + if (embedded) return hostWidth >= COMMENTS_PANEL_DRAWER_SPLIT_MIN_WIDTH ? 'beside' : 'cover'; + return windowWidth >= COMMENTS_PANEL_BESIDE_MIN_WINDOW ? 'beside' : 'over'; +} + +/** + * Whether the reader keeps the comment panel open (objectstack#36075, item 2): + * a preference, kept in this browser, one for the record page and one for + * the drawer, so the drawer (where the panel may cover the record) does not + * open on the comments because the page was left with them open. + */ +export function useCommentsPanelOpen(surface: 'page' | 'drawer'): [boolean, (open: boolean) => void] { + const key = `os:record-comments-panel:${surface}`; + const [open, setOpenState] = useState(() => { + try { + return typeof window !== 'undefined' && window.localStorage.getItem(key) === 'open'; + } catch { + return false; + } + }); + const setOpen = useCallback( + (next: boolean) => { + setOpenState(next); + try { + if (next) window.localStorage.setItem(key, 'open'); + else window.localStorage.removeItem(key); + } catch { + // Storage refused (a private window): the panel still opens and closes. + } + }, + [key], + ); + return [open, setOpen]; +} + +/** The window's width now and on every resize. */ +export function useWindowWidth(): number { + const read = () => (typeof window === 'undefined' ? 0 : window.innerWidth); + const [width, setWidth] = useState(read); + useEffect(() => { + if (typeof window === 'undefined') return undefined; + const onResize = () => setWidth(read()); + window.addEventListener('resize', onResize); + onResize(); + return () => window.removeEventListener('resize', onResize); + }, []); + return width; +} + +/** An element's rendered width, re-read whenever it resizes; 0 before it mounts. */ +export function useElementWidth(element: Element | null): number { + const [width, setWidth] = useState(0); + useEffect(() => { + if (!element) return undefined; + const read = () => setWidth(element.getBoundingClientRect().width); + read(); + if (typeof ResizeObserver === 'undefined') return undefined; + const observer = new ResizeObserver(read); + observer.observe(element); + return () => observer.disconnect(); + }, [element]); + return width; +} + +const PLACEMENT_CLASS: Record = { + beside: 'relative w-[380px] shrink-0 border-l border-border', + over: 'absolute inset-y-0 right-0 z-30 w-[380px] max-w-full border-l border-border shadow-xl', + cover: 'absolute inset-0 z-30', +}; + +/** The record's comment panel, in its place beside or over the record. */ +export function RecordCommentsAside({ + placement, + onClose, +}: { + placement: CommentsPanelPlacement; + onClose: () => void; +}) { + const ref = useRef(null); + // Closed from inside (✕, Esc), the focus goes back to the record: to the + // comments icon that opened the panel, the nearest one round it (the page's + // header, or the drawer's record row). + const close = useCallback(() => { + const el = ref.current; + const hadFocus = !!el && el.contains(document.activeElement); + let button: HTMLElement | null = null; + for (let node = el?.parentElement; node && !button; node = node.parentElement) { + button = node.querySelector('[data-comments-button]'); + } + onClose(); + if (hadFocus) button?.focus(); + }, [onClose]); + return ( +
+ +
+ ); +} diff --git a/ui/packages/app-shell/src/views/recordDrawerContext.ts b/ui/packages/app-shell/src/views/recordDrawerContext.ts index f040123fa4a..95f1d3f9199 100644 --- a/ui/packages/app-shell/src/views/recordDrawerContext.ts +++ b/ui/packages/app-shell/src/views/recordDrawerContext.ts @@ -64,6 +64,11 @@ export function useRecordPane(): RecordPaneApi | null { export interface RecordPaneBarApi { /** The bar's element the record portals its panel switches into; `null` until it mounts. */ toggleSlot: HTMLElement | null; + /** + * The bar's element the record portals its comments switch into, before its + * button group (objectstack#36075); `null` until it mounts. + */ + commentsSlot?: HTMLElement | null; /** The title of the record `recordId` names, once its row has loaded. */ reportTitle(recordId: string, title: string | undefined): void; } diff --git a/ui/packages/app-shell/src/views/recordDrawerStack.tsx b/ui/packages/app-shell/src/views/recordDrawerStack.tsx index 0442795d335..0a3233f3dea 100644 --- a/ui/packages/app-shell/src/views/recordDrawerStack.tsx +++ b/ui/packages/app-shell/src/views/recordDrawerStack.tsx @@ -512,6 +512,7 @@ export function RecordStackDrawer({ // reported, by level key: the breadcrumb names the record, and an ancestor // that was not opened with a title is still named by the one it reported. const [toggleSlot, setToggleSlot] = useState(null); + const [commentsSlot, setCommentsSlot] = useState(null); const [titles, setTitles] = useState>>({}); // objectstack#35593 / objectstack#35853 — the record header draws the // record's name and tags, and its button group, into the bar's record row @@ -527,13 +528,14 @@ export function RecordStackDrawer({ const bar = useMemo( () => ({ toggleSlot, + commentsSlot, reportTitle: (recordId: string, title: string | undefined) => { if (!currentObject || !title) return; const key = `${currentObject}:${recordId}`; setTitles((prev) => (prev[key] === title ? prev : { ...prev, [key]: title })); }, }), - [toggleSlot, currentObject], + [toggleSlot, commentsSlot, currentObject], ); const defOf = (objectName: string) => objects.find((o) => (o as { name?: unknown } | null)?.name === objectName); @@ -623,6 +625,7 @@ export function RecordStackDrawer({ recordRow={recordRow} onExpand={pane ? () => pane.openAsPage() : undefined} toggles={} + comments={} > {() => ( @@ -658,6 +661,13 @@ export function RecordPaneBarToggles({ children }: { children: ReactNode }) { return createPortal(children, bar.toggleSlot); } +/** The record's comments switch, drawn into its pane's bar before the button group (objectstack#36075). */ +export function RecordPaneBarComments({ children }: { children: ReactNode }) { + const bar = useContext(RecordPaneBarContext); + if (!bar?.commentsSlot || children == null || children === false) return null; + return createPortal(children, bar.commentsSlot); +} + /** * The page the record header's 「Open as full page」 opens from a pane level: * the record's route, with the levels below it as the `?from=` trail its back diff --git a/ui/packages/components/src/__tests__/record-top-bar-comments-36075.test.tsx b/ui/packages/components/src/__tests__/record-top-bar-comments-36075.test.tsx new file mode 100644 index 00000000000..5e2cac85543 --- /dev/null +++ b/ui/packages/components/src/__tests__/record-top-bar-comments-36075.test.tsx @@ -0,0 +1,52 @@ +/** + * 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#36075, item 2 — the record's comments switch sits in the record + * row of the top bar, ahead of the record's button group, on the page and in + * the drawer (`NavigationOverlay` hands it on); the one-row bar draws it + * ahead of the button group too. + */ + +import * as React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { RecordTopBar } from '../custom/record-top-bar'; + +afterEach(() => cleanup()); + +function Bar({ twoRows }: { twoRows: boolean }) { + const [, setSlot] = React.useState(null); + return ( + Wayne Enterprise License : undefined} + actionSlotRef={setSlot} + comments={} + toggles={⊟} + /> + ); +} + +const follows = (a: Element, b: Element) => !!(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING); + +describe('the comments switch in the record top bar', () => { + it('two rows: in the record row, ahead of the button group', () => { + render(); + const row = document.querySelector('[data-record-top-bar-record]') as HTMLElement; + const comments = screen.getByTestId('comments'); + expect(row.contains(comments)).toBe(true); + expect(follows(comments, row.querySelector('[data-record-top-bar-actions]')!)).toBe(true); + }); + + it('one row: ahead of the button group', () => { + render(); + const comments = screen.getByTestId('comments'); + expect(follows(comments, document.querySelector('[data-record-top-bar-actions]')!)).toBe(true); + }); +}); diff --git a/ui/packages/components/src/custom/navigation-overlay.tsx b/ui/packages/components/src/custom/navigation-overlay.tsx index 7d307c70560..c6a8dd0706f 100644 --- a/ui/packages/components/src/custom/navigation-overlay.tsx +++ b/ui/packages/components/src/custom/navigation-overlay.tsx @@ -271,6 +271,11 @@ export interface NavigationOverlayProps { * host's to decide. */ toggles?: React.ReactNode; + /** + * The record's comment switch (objectstack#36075), drawn in the bar before + * the record's button group (`RecordTopBar`'s `comments`). + */ + comments?: React.ReactNode; /** * The record header's one-row bar (objectstack#35593): handed the bar's * element the record's button group is drawn into, after the step pair. @@ -348,6 +353,17 @@ function escapeOwnedByTarget(target: EventTarget | null, pane?: Element | null): return !!owner && owner !== pane; } +/** + * Whether an `Esc` was pressed inside a region of the record that owns its + * own `Esc` (`[data-owns-escape]`, such as the record's comment panel), which + * then acts on it itself. Only a region inside the pane counts. + */ +function escapeOwnedByRegion(target: EventTarget | null, pane?: Element | null): boolean { + if (!target || !(target instanceof Element)) return false; + const region = target.closest('[data-owns-escape]'); + return !!region && (!pane || pane.contains(region)); +} + /** * Pane resize state — drag handle on the left edge, value persisted to * localStorage so the same user gets a consistent width across sessions / @@ -480,6 +496,7 @@ export const NavigationOverlay: React.FC = ({ trail, stepper, toggles, + comments, actionSlotRef, stepperHidden = false, recordRow, @@ -521,8 +538,17 @@ export const NavigationOverlay: React.FC = ({ // or a menu owns it, is not. It still holds the sheet open — left // unprevented, the layer would dismiss the whole drawer on it. const sheetRef = React.useRef(null); + // + // A region inside the record that owns its `Esc` (`[data-owns-escape]`: the + // record's comment panel, objectstack#36075) gets the key at every level, + // the root too: the drawer holds itself open and leaves the region to act. const handleDrawerEscape = (e: KeyboardEvent) => { if (e.defaultPrevented) return; + if (escapeOwnedByRegion(e.target, sheetRef.current)) { + e.preventDefault(); + return; + } + if (!onBack) return; e.preventDefault(); if (escapeOwnedByTarget(e.target, sheetRef.current)) return; handleEscape(); @@ -593,6 +619,7 @@ export const NavigationOverlay: React.FC = ({ actionSlotRef={actionSlotRef} record={recordRow} toggles={toggles} + comments={comments} frame={ <> {onExpand && ( @@ -634,7 +661,9 @@ export const NavigationOverlay: React.FC = ({ // objectstack#26679 — below the root of an in-place stack, `Esc` goes // back one level. Only the root's `Esc` closes. objectstack#28156 — a // field's `Esc` stays the field's ({@link escapeOwnedByTarget}). - onEscapeKeyDown={onBack ? handleDrawerEscape : undefined} + // objectstack#36075 — at every level, a region's `Esc` stays the + // region's ({@link escapeOwnedByRegion}). + onEscapeKeyDown={handleDrawerEscape} ref={sheetRef} className={cn( // Mobile: full width (no inline cap, no max-w from base sheet). diff --git a/ui/packages/components/src/custom/record-top-bar.tsx b/ui/packages/components/src/custom/record-top-bar.tsx index e2e15d2a5d2..494df5fc3cc 100644 --- a/ui/packages/components/src/custom/record-top-bar.tsx +++ b/ui/packages/components/src/custom/record-top-bar.tsx @@ -98,6 +98,12 @@ export interface RecordTopBarProps { actionSlotRef?: React.Ref; /** The panel switches (the right column's ⊟), after the step group. */ toggles?: React.ReactNode; + /** + * The record's comment switch (objectstack#36075): the comments icon and its + * count, drawn before the record's button group. A host that hands nothing + * (feeds off, a page with its own discussion) draws nothing there. + */ + comments?: React.ReactNode; /** The frame controls — ⤢ (a drawer), ✕ — at the right end. */ frame?: React.ReactNode; /** @@ -195,7 +201,7 @@ export function useRecordStepKeys( * The record's top bar (objectstack#27524, Target 7). See the module doc for * the anatomy; `data-record-top-bar` marks it on every face. */ -export function RecordTopBar({ leading, leadingTestId, stepper, actionSlotRef, toggles, frame, record, className }: RecordTopBarProps) { +export function RecordTopBar({ leading, leadingTestId, stepper, actionSlotRef, toggles, comments, frame, record, className }: RecordTopBarProps) { const { t } = useTopBarTranslation(); const position = stepper?.position && stepper.position.total > 0 && stepper.position.index >= 0 && stepper.position.index < stepper.position.total @@ -285,6 +291,7 @@ export function RecordTopBar({ leading, leadingTestId, stepper, actionSlotRef, t {record}
+ {comments} {actionSlotRef && ( <> )} + {comments} {actionSlotRef && ( <> + + {open && setOpen(false)} />} + + ); +} +``` + ## Reference Rail on an authored page The "Reference Rail" is a right-hand column of summary cards for related diff --git a/ui/packages/plugin-detail/src/ReactionPicker.tsx b/ui/packages/plugin-detail/src/ReactionPicker.tsx index dd758129b27..f5b46b2f295 100644 --- a/ui/packages/plugin-detail/src/ReactionPicker.tsx +++ b/ui/packages/plugin-detail/src/ReactionPicker.tsx @@ -12,7 +12,7 @@ import { SmilePlus } from 'lucide-react'; import type { Reaction } from '@object-ui/types'; import { useDetailTranslation } from './useDetailTranslation'; -const DEFAULT_EMOJI_OPTIONS = ['👍', '❤️', '🎉', '😂', '😮', '😢']; +export const DEFAULT_EMOJI_OPTIONS = ['👍', '❤️', '🎉', '😂', '😮', '😢']; export interface ReactionPickerProps { /** Existing reactions on the feed item */ diff --git a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx index 900fc59b303..630720e4acd 100644 --- a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx +++ b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx @@ -1228,7 +1228,7 @@ export const RecordActivityTimeline: React.FC = ({ )}
- {isStream && ( + {isStream && streamFilters.length > 0 && (
= ({ return; } if (e.key === 'Escape') { + // The key closes the list and nothing else: a panel or drawer + // round the box must not close on it too (objectstack#36075). + e.preventDefault(); + e.stopPropagation(); setShowMentions(false); return; } diff --git a/ui/packages/plugin-detail/src/__tests__/recordActivity.commentsInPanel-36075.test.tsx b/ui/packages/plugin-detail/src/__tests__/recordActivity.commentsInPanel-36075.test.tsx new file mode 100644 index 00000000000..630adfcca26 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/recordActivity.commentsInPanel-36075.test.tsx @@ -0,0 +1,123 @@ +/** + * 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#36075, item 5 — where the comment panel holds the record's + * comments, the default page's 动态 stream holds the system entries only: no + * comment rows, no 全部 / 活动 / 讨论 chips (变更 stays, objectstack#30074), + * no comment box, and a refused comment read is not the stream's to report. + * + * Measured against a CONTROL: the same stream without the panel keeps all of + * them, and an authored `record:activity` (a hand-written page, not the + * default stream) is untouched by the flag. + */ + +import React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import { DiscussionContextProvider } from '@object-ui/react'; +import type { FeedItem } from '@object-ui/types'; +import { RecordCommentsInPanelContext, RecordFieldHistoryContext } from '../recordTimelineStream'; +import { RecordActivityRenderer, RecordTimelineCountProbe } from '../renderers/record-activity'; +import { DefaultRecordPageContext } from '../defaultRecordPage'; + +afterEach(cleanup); + +const comment: FeedItem = { id: 'c1', type: 'comment', actor: 'Ada', body: 'Budget is set', createdAt: '2026-10-23T10:00:00Z' }; +const call: FeedItem = { id: 'a1', type: 'task', actor: 'Dev', body: 'Logged a call', createdAt: '2026-10-28T10:20:00Z' }; + +function mount({ inPanel, onDefaultPage = true, commentsDenied = false }: { inPanel: boolean; onDefaultPage?: boolean; commentsDenied?: boolean }) { + return render( + + + undefined} + > + + + + , + ); +} + +describe('record:activity while the comments are in the panel (objectstack#36075)', () => { + it('draws the system entries only: no comments, 变更 the one chip, no comment box', () => { + const { container } = mount({ inPanel: true }); + expect(screen.getByText('Logged a call')).toBeTruthy(); + expect(screen.queryByText('Budget is set')).toBeNull(); + const chips = Array.from(container.querySelectorAll('[data-stream-filter]')).map((c) => c.getAttribute('data-stream-filter')); + expect(chips).toEqual(['changes']); + expect(container.querySelector('textarea')).toBeNull(); + }); + + it('the lone 变更 chip is a toggle: pressed it holds the field changes, pressed again every entry', () => { + const { container } = mount({ inPanel: true }); + const chip = container.querySelector('[data-stream-filter="changes"]') as HTMLElement; + fireEvent.click(chip); + expect(chip.getAttribute('aria-pressed')).toBe('true'); + expect(screen.queryByText('Logged a call')).toBeNull(); + fireEvent.click(chip); + expect(chip.getAttribute('aria-pressed')).toBe('false'); + expect(screen.getByText('Logged a call')).toBeTruthy(); + }); + + it('no chip at all where the record shows no field history', () => { + const { container } = render( + + + + + + + + + , + ); + expect(container.querySelector('[data-stream-filters]')).toBeNull(); + }); + + it('CONTROL — without the panel the stream keeps comments, chips and the comment box', () => { + const { container } = mount({ inPanel: false }); + expect(screen.getByText('Budget is set')).toBeTruthy(); + expect(container.querySelector('[data-stream-filters]')).toBeTruthy(); + expect(container.querySelector('textarea')).toBeTruthy(); + }); + + it('a refused comment read does not replace the system entries', () => { + mount({ inPanel: true, commentsDenied: true }); + expect(screen.getByText('Logged a call')).toBeTruthy(); + }); + + it("the tab row's count, read while no face is drawn, counts the system entries alone", () => { + const counts: Array = []; + const probe = (inPanel: boolean) => ( + + + counts.push(count)} + /> + + + ); + render(probe(true)); + expect(counts.at(-1)).toBe(1); + cleanup(); + // CONTROL: without the panel the comment is counted too. + render(probe(false)); + expect(counts.at(-1)).toBe(2); + }); + + it('an authored record:activity off the default page is untouched by the flag', () => { + mount({ inPanel: true, onDefaultPage: false }); + expect(screen.getByText('Budget is set')).toBeTruthy(); + }); +}); diff --git a/ui/packages/plugin-detail/src/comments/CommentComposer.tsx b/ui/packages/plugin-detail/src/comments/CommentComposer.tsx new file mode 100644 index 00000000000..79679720b4b --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentComposer.tsx @@ -0,0 +1,76 @@ +/** + * 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 { cn } from '@object-ui/components'; +import type { DiscussionMentionSuggestion } from '@object-ui/react'; +import { RichTextCommentInput } from '../RichTextCommentInput'; + +export interface CommentComposerProps { + /** Writes the comment (or the reply). A rejection means nothing was written: the draft stays. */ + onSubmit: (text: string) => void | Promise; + placeholder?: string; + mentionSuggestions?: DiscussionMentionSuggestion[]; + onMentionSuggestionsWanted?: () => void; + /** + * Moves the caret into the box each time it changes to a new value above + * zero: a press on 「回复」 lands the caret here, the draft kept. + */ + focusSignal?: number; + className?: string; +} + +/** + * The comment box (objectstack#36075): one line until used, the record + * timeline's composer in full once focused — the same toolbar, mentions and + * send as everywhere else. The desktop panel docks it at its foot; a thread + * draws one under its replies. + */ +export const CommentComposer: React.FC = ({ + onSubmit, + placeholder, + mentionSuggestions, + onMentionSuggestionsWanted, + focusSignal = 0, + className, +}) => { + const boxRef = React.useRef(null); + React.useEffect(() => { + if (focusSignal > 0) boxRef.current?.querySelector('textarea')?.focus(); + }, [focusSignal]); + const [text, setText] = React.useState(''); + const [submitting, setSubmitting] = React.useState(false); + const submit = React.useCallback(async () => { + const trimmed = text.trim(); + if (!trimmed || submitting) return; + setSubmitting(true); + try { + await onSubmit(trimmed); + setText(''); + } catch { + // Not written: the host reports why; the draft stays for another try. + } finally { + setSubmitting(false); + } + }, [text, submitting, onSubmit]); + return ( +
+ +
+ ); +}; diff --git a/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx b/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx new file mode 100644 index 00000000000..f8e539c689a --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx @@ -0,0 +1,161 @@ +/** + * 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 { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + Popover, + PopoverContent, + PopoverTrigger, + cn, +} from '@object-ui/components'; +import { Check, MoreHorizontal, Pencil, Reply, SmilePlus, Trash2 } from 'lucide-react'; +import { useDetailTranslation } from '../useDetailTranslation'; +import { DEFAULT_EMOJI_OPTIONS } from '../ReactionPicker'; + +export interface CommentHoverActionsProps { + /** Opens the reply box under the thread, the caret in it. */ + onReply?: () => void; + /** Adds (or takes back) the viewer's reaction. */ + onReact?: (emoji: string) => void; + /** Marks the thread resolved; offered only where the deployment stores it. */ + onResolve?: () => void; + /** The author's Edit; under 更多. */ + onEdit?: () => void; + /** The author's Delete; under 更多, the host confirms first. */ + onDelete?: () => void; +} + +const ICON_BUTTON = + 'inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +/** + * A comment's actions on the desktop (objectstack#36075, item 6): ONE row at + * the comment's top right — 回复, 表情, 已解决, 更多 (编辑, 删除) — shown while + * the pointer is over the comment, focus is in the row, or one of its menus is + * open. Each control is drawn only where its handler is handed; a row with + * none draws nothing. + */ +export const CommentHoverActions: React.FC = ({ + onReply, + onReact, + onResolve, + onEdit, + onDelete, +}) => { + const { t } = useDetailTranslation(); + const [pickerOpen, setPickerOpen] = React.useState(false); + const [menuOpen, setMenuOpen] = React.useState(false); + if (!onReply && !onReact && !onResolve && !onEdit && !onDelete) return null; + const held = pickerOpen || menuOpen; + return ( +
+ {onReply && ( + + )} + {onReact && ( + + + + + + {DEFAULT_EMOJI_OPTIONS.map((emoji) => ( + + ))} + + + )} + {onResolve && ( + + )} + {(onEdit || onDelete) && ( + + + + + + {onEdit && ( + + + {t('detail.edit')} + + )} + {onDelete && ( + + + {t('detail.delete')} + + )} + + + )} +
+ ); +}; diff --git a/ui/packages/plugin-detail/src/comments/CommentItem.tsx b/ui/packages/plugin-detail/src/comments/CommentItem.tsx new file mode 100644 index 00000000000..adbebb6cd35 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentItem.tsx @@ -0,0 +1,170 @@ +/** + * 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 { Button, Textarea, cn } from '@object-ui/components'; +import { useDisplayLocale } from '@object-ui/i18n'; +import type { FeedItem } from '@object-ui/types'; +import { useDetailTranslation } from '../useDetailTranslation'; +import { CommentAuthorAvatar } from '../CommentAuthorAvatar'; +import { formatCommentTime } from './commentTime'; + +export interface CommentItemProps { + item: FeedItem; + /** + * The comment's actions, drawn at its top right (the desktop's hover row, + * `CommentHoverActions`). A surface that reaches them another way (the + * phone's long press) hands none. + */ + actions?: React.ReactNode; + /** The comment's text is an editor while this is true. */ + editing?: boolean; + /** + * Stores the edited text. A rejection means nothing was stored: the editor + * stays open with the draft. + */ + onSaveEdit?: (text: string) => void | Promise; + onCancelEdit?: () => void; + /** Toggles the viewer's own reaction; absent, the reactions are read-only. */ + onToggleReaction?: (emoji: string) => void; + /** What sits under the comment: a thread's 「N 条回复」, or its replies. */ + footer?: React.ReactNode; + className?: string; +} + +/** + * One comment (objectstack#36075): its author's face, name and when on one + * line, what they wrote, and the reactions under it — the viewer's own ones + * marked. The desktop panel and the phone's comment page draw the same item; + * only where its actions are reached differs. + */ +export const CommentItem: React.FC = ({ + item, + actions, + editing = false, + onSaveEdit, + onCancelEdit, + onToggleReaction, + footer, + className, +}) => { + const { t } = useDetailTranslation(); + const locale = useDisplayLocale(); + const reactions = item.reactions ?? []; + return ( +
+
+ + {item.actor} + + {formatCommentTime(item.createdAt, t, locale)} + + {item.edited && {t('detail.edited')}} +
+ {actions} +
+ {editing && onSaveEdit ? ( + onCancelEdit?.()} + /> + ) : ( + item.body && ( +

+ {item.body} +

+ ) + )} + {reactions.length > 0 && ( +
+ {reactions.map((reaction) => { + const label = t('detail.reactionCount', { emoji: reaction.emoji, count: reaction.count }); + return ( + + ); + })} +
+ )} + {footer} +
+
+ ); +}; + +/** The editor a comment's text turns into: Save stores the trimmed draft, Esc or Cancel leaves it. */ +const CommentEditor: React.FC<{ + initial: string; + onSave: (text: string) => void | Promise; + onCancel: () => void; +}> = ({ initial, onSave, onCancel }) => { + const { t } = useDetailTranslation(); + const [draft, setDraft] = React.useState(initial); + const [saving, setSaving] = React.useState(false); + const trimmed = draft.trim(); + const canSave = trimmed !== '' && trimmed !== initial.trim(); + const save = async () => { + if (!canSave) return; + setSaving(true); + try { + await onSave(trimmed); + } catch { + // Not stored: the host reports why; the draft stays for another try. + } finally { + setSaving(false); + } + }; + return ( +
+