diff --git a/.changeset/36076-phone-comment-page.md b/.changeset/36076-phone-comment-page.md new file mode 100644 index 00000000000..3a6d6d7a0a3 --- /dev/null +++ b/.changeset/36076-phone-comment-page.md @@ -0,0 +1,22 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +feat(record-page): on a phone, the record's comments open as a page of their own: the threads first, a thread's replies inside it, the comment box docked at the foot, and a long press for a comment's actions + +Clause-②: yes (widening) — `@object-ui/plugin-detail` adds the export `CommentsPage` and its type `CommentsPageProps`; `CommentThread` takes a third `mode`, `'page'`, and optional `itemInteraction`, `heldId` and `onHeldActions`; `CommentItem` an optional `interactionProps`; `CommentComposer` and `RichTextCommentInput` (exported) an optional `layout` (`'default' | 'phone'`). `@object-ui/app-shell` reserves the console URL parameter `comments` (`RECORD_COMMENTS_PARAM`, in `RESERVED_URL_PARAMS`). `@object-ui/i18n` adds four keys to every pack: `detail.addReactionEmoji`, `detail.commentThread`, `detail.formatBold`, `detail.formatItalic` (the toolbar's names without their shortcut). Nothing existing is removed or re-typed; the desktop's panel, toolbar and labels are unchanged. +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 phone's page in this change. + +On a phone the record page's top bar gains the comments icon, with the number of unresolved threads. A press opens the record's comments as a page over the record, which stays where it was under it; 「‹」 and the browser's Back return to it. + +- The page lists each thread's first comment with 「N 条回复」 under it; a tap opens the thread, the comment first and its replies after it. 「‹ 评论」 returns to the list. +- The comment box is docked at the foot of the screen and stands on the keyboard while it is up. One line until tapped; then a row under the text holds mention, bold, italic, list and code, and send at the right end. In the list it writes a comment, in a thread a reply. No 「Ctrl+Enter」 hint. +- A long press on a comment (or its context menu) raises a sheet from the bottom: six reactions, 「标记已解决」 on a thread's first comment, 「编辑」 and 「删除」 (red, confirmed first), each offered exactly where the desktop's hover row offers it. +- The filter at the top right is the desktop's: 「显示已解决」 and 「只看我参与的」. +- The 动态 tab holds the system entries alone, as on the desktop. On a phone the comments live on this page: this replaces the lines of the two objectstack#36075 entries (the record comment panel, and resolved threads) that said the phone keeps the comments in its 动态 tab, or keeps its feed as before. +- The page is in the URL (`?comments=` for the list, `?comments=` for a thread), so a link or a reload opens it where it was. + +Unchanged: the desktop; who may write, resolve, edit or delete a comment (the phone offers each exactly where the desktop does); a record page authored in full and an object with `enable.feeds: false` show no icon. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 8e013c9c525..a2b792968c6 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -239,12 +239,38 @@ the record drawer), and no longer inside the 动态 (Activity) tab 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. +with `enable.feeds: false` shows no icon. + +### On a phone + +On a phone the same icon sits at the right of the record page's top bar, with +the same number, and opens the record's comments as a page of their own over +the record (objectstack#36076). The record stays where it was under it: 「‹」 +and the browser's Back return to it as it was scrolled. + +- **Two levels.** The page lists each thread's first comment, with the faces of + the latest repliers and 「N 条回复」 under it; replies are not on the list. A + tap on a comment opens its thread: the comment first, then the replies, + oldest first. 「‹ 评论」 goes back to the list. +- **The comment box** stays at the foot of the screen, and above the keyboard + while it is up. One line until you tap it; then a row under the text holds + mention, bold, italic, list and code, with send at the right end. In the list + it writes a new comment; in a thread, a reply. It names no keyboard shortcut. +- **A long press** on a comment raises its actions from the bottom: six + reactions on one row, then 「标记已解决」 (on a thread's first comment), 「编辑」 + and 「删除」, red, which asks before deleting. Each appears exactly where the + desktop's hover row would offer it. The comment's reactions show under its + text with their counts, yours marked; a tap on one adds yours or takes it back. +- **The filter** at the list's top right is the desktop's: 「显示已解决」 and + 「只看我参与的」. +- **The 动态 tab** holds the system entries only, as on the desktop. + +The page is addressed by the URL (`?comments=` for the list, `?comments=` +for a thread), so a link or a reload opens it where it was. The components are exported from `@object-ui/plugin-detail` (`CommentsPanel`, -`CommentsButton`, `CommentThread`, `CommentItem`, `CommentComposer`, -`useRecordComments`); each reads the discussion off the host's +`CommentsPage`, `CommentsButton`, `CommentThread`, `CommentItem`, +`CommentComposer`, `useRecordComments`); each reads the discussion off the host's `DiscussionContext`, as the feed blocks do. ## The `record:activity` block diff --git a/ui/packages/app-shell/src/urlParams.ts b/ui/packages/app-shell/src/urlParams.ts index 6b3c2ca6bdb..14d28045ed5 100644 --- a/ui/packages/app-shell/src/urlParams.ts +++ b/ui/packages/app-shell/src/urlParams.ts @@ -51,6 +51,9 @@ import { NAV_RUN_ACTION_PARAM } from '@object-ui/layout'; * | | objectui#2257). Never stacks history. | | * | `palette` | Command palette overlay (alias `cmdk`). | replace | * | `shortcuts` | Keyboard-shortcuts dialog overlay. | replace | + * | `comments` | The phone's comment page over a record route: | push (open), | + * | | empty = the threads, a top-level comment's id | pop (close) | + * | | = that thread (objectstack#36076). | | * | `from` | Ancestor breadcrumb trail for a record route, | push (with | * | | so drilling record→related-record keeps a | the drill-in) | * | | clickable path back (`Account → #p → Invoice`).| | @@ -127,6 +130,20 @@ export const RECORD_RELATED_ENLARGE_PUSHED_STATE = '__relatedEnlargePushed'; */ export const NAV_DRAWER_OPEN_STATE = '__navDrawerOpen'; +/** + * The phone's comment page over the record page (`?comments=`, objectstack#36076): + * present and empty, the record's threads; a top-level comment's id, that + * thread. Read by `RecordDetailView` on a phone's record page only. + */ +export const RECORD_COMMENTS_PARAM = 'comments'; + +/** + * History-state flag beside {@link RECORD_COMMENTS_PARAM}: the record view + * pushed this `?comments=` entry, so 「‹」 pops it. Not a URL parameter; an + * entry reached by a reload or a shared link carries none, and 「‹」 replaces. + */ +export const RECORD_COMMENTS_PUSHED_STATE = '__commentsPushed'; + /** Command palette overlay (ADR-0054 Phase 1; alias `cmdk`). */ export const COMMAND_PALETTE_PARAM = 'palette'; @@ -170,6 +187,7 @@ export const RESERVED_URL_PARAMS: readonly string[] = [ RECORD_FORM_LINK_PARAM, RECORD_DETAIL_TAB_PARAM, RECORD_RELATED_ENLARGE_PARAM, + RECORD_COMMENTS_PARAM, COMMAND_PALETTE_PARAM, KEYBOARD_SHORTCUTS_PARAM, RECORD_TRAIL_PARAM, 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 index 707d80fd5e1..8732e7066f4 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.commentsPanel-36075.test.tsx @@ -25,7 +25,7 @@ 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'; +import { MemoryRouter, useLocation } from 'react-router-dom'; vi.mock('@object-ui/auth', async (importOriginal) => ({ ...(await importOriginal>()), @@ -60,6 +60,7 @@ import { MetadataCtx } from '@object-ui/react'; import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; import { toast } from 'sonner'; import { RecordDetailView } from './RecordDetailView'; +import { __clearRecordEditableCache } from '../../../plugin-detail/src/useRecordEditable'; const OBJECT_NAME = 'crm_case'; const NO_FEEDS = 'crm_note'; @@ -147,13 +148,22 @@ interface MountOptions { objectName?: string; pages?: unknown[]; embedded?: boolean; + /** The record route's query, `?comments=…` for the phone's comment page. */ + search?: string; } -async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false }: MountOptions = {}) { +/** The router's location now, for the phone's `?comments=` entries. */ +function LocationProbe() { + const location = useLocation(); + return ; +} + +async function mount({ objectName = OBJECT_NAME, pages = [], embedded = false, search = '' }: MountOptions = {}) { const rendered = render( - + + { expect(await within(panel(container)!).findByText(ADA_BODY)).toBeInTheDocument(); }); }); + +/** + * objectstack#36076 — the phone's comment page, through the REAL + * `RecordDetailView` at 375 wide: + * + * - The icon is in the phone's top bar with the number of threads; a press + * pushes `?comments=` and draws the page over the record, which stays + * mounted under it. + * - The list shows top-level comments only; a tap pushes the thread + * (`?comments=`), which shows the comment and its reply. 「‹」 pops back + * to the list, then to the record, and the focus returns to the icon. + * - A link or a reload straight to a thread: 「‹」 replaces the URL one level up. + * - The 动态 tab keeps the system entries alone, as on the desktop. + * - No icon on an object with feeds off. + */ +describe("the phone's comment page (objectstack#36076)", () => { + beforeEach(() => setWindowWidth(375)); + + const page = () => document.querySelector('[data-comments-page]') as HTMLElement | null; + const search = () => document.querySelector('[data-testid="location"]')!.getAttribute('data-search'); + + it('the top bar carries the icon with the thread count; a press pushes the page over the record', async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + expect(button(container)!.closest('[data-record-top-bar]')).not.toBeNull(); + await waitFor(() => expect(button(container)!.querySelector('[data-comments-count]')).toHaveTextContent('2')); + expect(panel(container)).toBeNull(); + fireEvent.click(button(container)!); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'list')); + expect(search()).toBe('?comments='); + expect(document.querySelector('[data-testid="location"]')).toHaveAttribute('data-pushed', 'true'); + const list = within(page()!); + expect(await list.findByText(ADA_BODY)).toBeInTheDocument(); + expect(list.getByText(GRACE_BODY)).toBeInTheDocument(); + expect(list.queryByText(REPLY_BODY)).toBeNull(); + expect(list.getByRole('button', { name: /1 reply/ })).toBeInTheDocument(); + // The record is still there, under the page. + expect(within(container).getAllByText(`Case ${RECORD_ID}`).length).toBeGreaterThan(0); + }); + + it('a tap opens the thread; 「‹」 goes back to the list, then to the record, focus on the icon', async () => { + const { container } = await mount(); + await waitFor(() => expect(button(container)).not.toBeNull()); + fireEvent.click(button(container)!); + fireEvent.click(await within(page()!).findByText(ADA_BODY)); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'thread')); + expect(search()).toBe('?comments=c-ada'); + expect(within(page()!).getByText(REPLY_BODY)).toBeInTheDocument(); + fireEvent.click(page()!.querySelector('[data-comments-page-back]')!); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'list')); + expect(search()).toBe('?comments='); + fireEvent.click(page()!.querySelector('[data-comments-page-back]')!); + await waitFor(() => expect(page()).toBeNull()); + expect(search()).toBe(''); + await waitFor(() => expect(document.activeElement).toBe(button(container))); + }); + + it('a link straight to a thread: 「‹」 replaces the URL one level up', async () => { + await mount({ search: '?comments=c-ada' }); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'thread')); + fireEvent.click(page()!.querySelector('[data-comments-page-back]')!); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'list')); + expect(search()).toBe('?comments='); + fireEvent.click(page()!.querySelector('[data-comments-page-back]')!); + await waitFor(() => expect(page()).toBeNull()); + expect(search()).toBe(''); + }); + + it('the 动态 tab keeps the system entries alone', async () => { + const { container } = await mount({ search: '?tab=activity' }); + await waitFor(() => expect(button(container)).not.toBeNull()); + await act(async () => {}); + expect(within(container).queryByText(ADA_BODY)).toBeNull(); + expect(within(container).queryByText('Ctrl+Enter', { exact: false })).toBeNull(); + }); + + it("a moderator's first long press on another's comment: the sheet gains Edit when the late answer lands", async () => { + __clearRecordEditableCache(); + // The record's update is answered at once (the viewer moderates); the row + // floor's answer for a comment the viewer did not write comes later. + let answerFloor!: () => void; + const floor = new Promise((resolve) => { + answerFloor = resolve; + }); + const explained: string[] = []; + const allow = () => + new Response(JSON.stringify({ allowed: true, record: { visible: true } }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string, init?: RequestInit) => { + if (String(url).endsWith('/security/explain')) { + const body = JSON.parse(String(init?.body ?? '{}')); + explained.push(body.object); + if (body.object === 'sys_comment') await floor; + return allow(); + } + return new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } }); + }), + ); + try { + await mount({ search: '?comments=' }); + await waitFor(() => expect(page()).toHaveAttribute('data-comments-page', 'list')); + const grace = (await within(page()!).findByText(GRACE_BODY)).closest('[data-comment-id]') as HTMLElement; + // Opening the page asks nothing about other people's comments. + await act(async () => {}); + expect(explained).not.toContain('sys_comment'); + vi.useFakeTimers(); + fireEvent.pointerDown(grace, { pointerType: 'touch', button: 0, clientX: 10, clientY: 10 }); + act(() => { + vi.advanceTimersByTime(600); + }); + fireEvent.pointerUp(grace, { pointerType: 'touch' }); + vi.useRealTimers(); + // The press asked; the hold opened before the answer. + expect(explained).toContain('sys_comment'); + const sheet = () => document.querySelector('[data-comment-action-sheet]') as HTMLElement | null; + const rows = () => + Array.from(sheet()?.querySelectorAll('[data-comment-action]') ?? []).map((row) => row.getAttribute('data-comment-action')); + await waitFor(() => expect(rows()).toEqual(['delete'])); + await act(async () => { + answerFloor(); + }); + await waitFor(() => expect(rows()).toEqual(['edit', 'delete'])); + } finally { + vi.useRealTimers(); + __clearRecordEditableCache(); + } + }); + + it('no icon on an object with feeds off', async () => { + const { container } = await mount({ objectName: NO_FEEDS }); + await act(async () => {}); + expect(button(container)).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 2a7d53b9d81..5b3e0dd1913 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, 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, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, isRefusedFeedRead, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, 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, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, isRefusedFeedRead, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; // objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. import { unresolvedThreadCount, useRecordVerdict } 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'; @@ -60,7 +60,7 @@ import { import { applySavedRecordEcho } from './recordSaveEcho.js'; import { authoredRecordPageApplies } from './recordPageSurface.js'; import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js'; -import { RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; +import { RECORD_COMMENTS_PARAM, RECORD_COMMENTS_PUSHED_STATE as COMMENTS_PUSHED, RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js'; import { resolveActionParams } from '@object-ui/fields'; import { createConsoleServerActionHandler } from '../utils/consoleServerAction.js'; import { withNewTabUrlFastPath } from '../utils/newTabUrlFastPath.js'; @@ -1311,6 +1311,45 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const commentsPhone = usePhoneViewport(); const commentsPanelOffered = !!objectDef && objectDef.enable?.feeds !== false && pageColumnsEligible && !commentsPhone && !!pureRecordId; + // objectstack#36076 — the phone's comment page, on the same pages: a page + // over the record page, addressed by `?comments=` (empty: the threads; a + // top-level comment's id: that thread). A phone draws no drawer or pane. + const commentsPageOffered = + !!objectDef && objectDef.enable?.feeds !== false && pageColumnsEligible && commentsPhone && !embedded && !!pureRecordId; + // Either surface holds the record's comments, so the 动态 stream gives + // them up and names its system entries alone. + const commentsSurfaceOffered = commentsPanelOffered || commentsPageOffered; + const commentsParam = commentsPageOffered ? tabSearchParams.get(RECORD_COMMENTS_PARAM) : null; + const commentsPageOpen = commentsParam !== null; + const commentsPageThread = commentsParam ? commentsParam : null; + // Opening pushes an entry (Back and 「‹」 return to the record where it was + // scrolled: the record stays mounted under the page), a thread pushes one + // over the list, and 「‹」 pops the entry this view pushed or, on an entry a + // reload or a link reached, replaces the URL one level up. + const openCommentsPage = useCallback((thread?: string) => { + const sp = new URLSearchParams(location.search); + sp.set(RECORD_COMMENTS_PARAM, thread ?? ''); + const state = location.state && typeof location.state === 'object' ? location.state : {}; + setTabSearchParams(sp, { state: { ...(state as object), [COMMENTS_PUSHED]: true } }); + }, [setTabSearchParams, location.search, location.state]); + const leaveCommentsPage = useCallback(() => { + if ((location.state as Record | null)?.[COMMENTS_PUSHED]) { + navigate(-1); + return; + } + const sp = new URLSearchParams(location.search); + if (sp.get(RECORD_COMMENTS_PARAM)) sp.set(RECORD_COMMENTS_PARAM, ''); + else sp.delete(RECORD_COMMENTS_PARAM); + setTabSearchParams(sp, { replace: true, state: location.state }); + }, [setTabSearchParams, location.search, location.state, navigate]); + // Closed, the focus goes back to the comments icon that opened the page. + const commentsPageWasOpen = useRef(false); + useEffect(() => { + if (commentsPageWasOpen.current && !commentsPageOpen) { + document.querySelector('[data-record-top-bar] [data-comments-button]')?.focus({ preventScroll: true }); + } + commentsPageWasOpen.current = commentsPageOpen; + }, [commentsPageOpen]); const [commentsOpenChosen, setCommentsOpen] = useCommentsPanelOpen(embedded ? 'drawer' : 'page'); const commentsOpen = commentsPanelOffered && commentsOpenChosen; const commentsWindowWidth = useWindowWidth(); @@ -2717,7 +2756,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 || commentsPanelOffered) && objectDef?.enable?.feeds !== false; + const streamDiscussion = (feedOnOpen || commentsSurfaceOffered) && objectDef?.enable?.feeds !== false; const streamActivity = feedOnOpen && objectDef?.enable?.activities !== false; const recordPageStreams = { ...(streamDiscussion ? { discussion: true } : {}), @@ -2999,10 +3038,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // render: no effect, and no render that reads the latch unset. if (feedConsumerOnScreen && !feedConsumerShown) setFeedConsumerShown(true); // 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. + // the comment panel (objectstack#36075) and the phone's comment page + // (objectstack#36076), whose icon counts the threads at open, closed — so + // the discussion rides the open's payload. const activityFeedWanted = feedConsumerOnScreen || feedConsumerShown; - const feedWanted = activityFeedWanted || commentsPanelOffered; + const feedWanted = activityFeedWanted || commentsSurfaceOffered; // 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 @@ -3854,10 +3894,11 @@ 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. + // objectstack#36075, objectstack#36076 — where the comment panel or the + // phone's comment page holds the comments, the 动态 stream names its system + // entries alone. const timelineTotal = timelineServed - ? Math.max(0, timelineServed.total - timelineServed.comments + (commentsPanelOffered ? 0 : heldCommentCount)) + ? Math.max(0, timelineServed.total - timelineServed.comments + (commentsSurfaceOffered ? 0 : heldCommentCount)) : null; // The comments icon's number: the record's unresolved threads (#36075 item // 8; every thread where the deployment stores no resolution), unknown while @@ -3868,6 +3909,15 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const commentsButton = commentsPanelOffered ? ( ) : null; + // The phone's icon opens the comment page; at touch size. + const phoneCommentsButton = commentsPageOffered ? ( + openCommentsPage()} + className="h-11 min-w-11 px-2 text-sm" + /> + ) : null; /** * Note: comment-mention → notification fan-out lives on the server @@ -4269,7 +4319,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri objectDef?.name, pureRecordId, 'update', - commentsOpen, + commentsOpen || commentsPageOpen, ) === true; // objectstack#36075 — may the viewer update a comment they did NOT write? @@ -4300,7 +4350,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri COMMENT_OBJECT, foreignRootCommentId, 'update', - commentsOpen && commentsEngaged && foreignRootCommentId != null, + (commentsOpen || commentsPageOpen) && commentsEngaged && foreignRootCommentId != null, ) === true; /** @@ -5702,6 +5752,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri leading={phoneBack} stepper={pageStepper} toggles={approvalQueueSwitch ?? undefined} + comments={phoneCommentsButton} /> {phonePathRow} @@ -6039,7 +6090,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): @@ -6319,6 +6370,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri {/* objectstack#36075 — the record's comment panel: beside the record (which gives it the width), or over it. */} + {/* objectstack#36076 — the phone's comment page, over the record. */} + {commentsPageOpen && ( + + )} {commentsOpen && ( = ({ autoFocus = false, onMentionSuggestionsWanted, compact = false, + layout = 'default', }) => { const { t } = useDetailTranslation(); const [isPreview, setIsPreview] = React.useState(false); @@ -322,20 +330,9 @@ export const RichTextCommentInput: React.FC = ({ [showMentions, filteredMentions, mentionIndex, handleSelectMention, onSubmit], ); - return ( -
setFocused(true) : undefined} - onBlur={ - compact - ? (e) => { - if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false); - } - : undefined - } - > - {/* Toolbar */} + const phone = layout === 'phone'; + // The desktop's toolbar, above the editor. + const toolbar = (
)}
+ ); + // objectstack#36076 — the phone's row, under the editor: the same commands + // at touch size, mention first, send at the right end. + const phoneToolButton = 'h-11 w-11 shrink-0'; + const phoneToolbar = ( +
e.preventDefault()} + data-composer-toolbar="phone" + > + + + + + +
+ {onSubmit && ( + + )} +
+ ); + + return ( +
setFocused(true) : undefined} + onBlur={ + compact + ? (e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(false); + } + : undefined + } + > + {!phone && toolbar} {/* Editor / Preview */}
@@ -432,6 +485,7 @@ export const RichTextCommentInput: React.FC = ({ className={cn( 'w-full px-3 text-sm bg-transparent resize-none focus:outline-none placeholder:text-muted-foreground', collapsed ? 'block h-8 min-h-0 py-1.5 text-sm leading-5' : 'min-h-[80px] py-2', + phone && (collapsed ? 'h-10 py-2 text-base leading-6' : 'min-h-[72px] text-base'), )} rows={collapsed ? 1 : undefined} placeholder={placeholder ?? t('detail.writeComment')} @@ -516,6 +570,7 @@ export const RichTextCommentInput: React.FC = ({ {extraSlot}
)} + {phone && phoneToolbar}
); }; diff --git a/ui/packages/plugin-detail/src/comments/CommentActionSheet.tsx b/ui/packages/plugin-detail/src/comments/CommentActionSheet.tsx new file mode 100644 index 00000000000..cdaa6f61159 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentActionSheet.tsx @@ -0,0 +1,113 @@ +/** + * 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 { Drawer, DrawerContent, DrawerDescription, DrawerTitle, cn } from '@object-ui/components'; +import { Check, Pencil, RotateCcw, Trash2 } from 'lucide-react'; +import { useDetailTranslation } from '../useDetailTranslation'; +import { DEFAULT_EMOJI_OPTIONS } from '../ReactionPicker'; +import type { CommentItemActions } from './CommentThread'; + +export interface CommentActionSheetProps { + /** The held comment's actions; `null` closes the sheet. */ + actions: CommentItemActions | null; + onClose: () => void; +} + +const ROW = + 'flex min-h-12 w-full items-center gap-3 rounded-lg px-3 text-left text-base text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:bg-muted'; + +/** + * The phone's comment actions (objectstack#36076 item 5): a sheet up from the + * bottom of the screen with the six reactions on one row, then 标记已解决 (on + * a thread's top-level comment), 编辑 and 删除, red. Each row is drawn only + * where the comment's actions hand its handler: the gates are the comment + * thread's, the same ones the desktop's hover row draws from. A press picks + * and closes; 删除 then asks the host's confirmation. + */ +export const CommentActionSheet: React.FC = ({ actions, onClose }) => { + const { t } = useDetailTranslation(); + // The last actions stay drawn while the sheet slides away. + const [shown, setShown] = React.useState(actions); + if (actions && actions !== shown) setShown(actions); + const open = actions !== null; + const a = actions ?? shown; + const reacted = new Set((a?.item.reactions ?? []).filter((r) => r.reacted).map((r) => r.emoji)); + const pick = (run: (() => void) | undefined) => () => { + onClose(); + run?.(); + }; + const title = t('detail.commentActions'); + return ( + !next && onClose()} shouldScaleBackground={false}> + + {title} + {title} +
+ {a?.onReact && ( +
+ {DEFAULT_EMOJI_OPTIONS.map((emoji) => ( + + ))} +
+ )} + {a?.onResolve && ( + + )} + {a?.onEdit && ( + + )} + {a?.onDelete && ( + + )} +
+
+
+ ); +}; diff --git a/ui/packages/plugin-detail/src/comments/CommentComposer.tsx b/ui/packages/plugin-detail/src/comments/CommentComposer.tsx index 79679720b4b..658bc76fdb2 100644 --- a/ui/packages/plugin-detail/src/comments/CommentComposer.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentComposer.tsx @@ -22,6 +22,8 @@ export interface CommentComposerProps { * zero: a press on 「回复」 lands the caret here, the draft kept. */ focusSignal?: number; + /** `phone`: the phone's box, its toolbar under the text (`RichTextCommentInput`). */ + layout?: 'default' | 'phone'; className?: string; } @@ -37,6 +39,7 @@ export const CommentComposer: React.FC = ({ mentionSuggestions, onMentionSuggestionsWanted, focusSignal = 0, + layout, className, }) => { const boxRef = React.useRef(null); @@ -70,6 +73,7 @@ export const CommentComposer: React.FC = ({ onMentionSuggestionsWanted={onMentionSuggestionsWanted} disabled={submitting} compact + layout={layout} />
); diff --git a/ui/packages/plugin-detail/src/comments/CommentItem.tsx b/ui/packages/plugin-detail/src/comments/CommentItem.tsx index 4bea8308c15..011ea6bd447 100644 --- a/ui/packages/plugin-detail/src/comments/CommentItem.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentItem.tsx @@ -34,6 +34,13 @@ export interface CommentItemProps { onToggleReaction?: (emoji: string) => void; /** What sits under the comment: a thread's 「N 条回复」, or its replies. */ footer?: React.ReactNode; + /** + * The comment's box answers a press besides its own controls (the phone's + * long press, `useCommentPress`): spread on the box, which then takes no + * text selection and no system callout, so the press is the page's. Not + * while the comment is being edited: the press is then the editor's. + */ + interactionProps?: React.HTMLAttributes; className?: string; } @@ -51,13 +58,23 @@ export const CommentItem: React.FC = ({ onCancelEdit, onToggleReaction, footer, + interactionProps, className, }) => { const { t } = useDetailTranslation(); const locale = useDisplayLocale(); const reactions = item.reactions ?? []; return ( -
+
{item.actor} diff --git a/ui/packages/plugin-detail/src/comments/CommentThread.tsx b/ui/packages/plugin-detail/src/comments/CommentThread.tsx index 04eeb9509d6..ff8d35ae7b7 100644 --- a/ui/packages/plugin-detail/src/comments/CommentThread.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentThread.tsx @@ -60,12 +60,31 @@ export interface RecordCommentThreadProps { * `expand`: the replies open in place, under the comment, with the reply * box after them (the desktop panel). `summary`: the thread stays one * comment and 「N 条回复」, and a press on it calls `onOpen` (the phone's - * list, which opens the thread on its own page). + * list, which opens the thread on its own page). `page`: the thread is the + * page, its comment first and every reply after it, oldest first; the page + * docks its own reply box, so the thread draws none (the phone's thread). + */ + mode?: 'expand' | 'summary' | 'page'; + /** + * `summary`: opens the thread. `page`: 「回复」 was pressed; the host puts + * the caret in its reply box. */ - mode?: 'expand' | 'summary'; onOpen?: () => void; /** Draws a comment's actions; absent, a comment has none on screen. */ renderActions?: (actions: CommentItemActions) => React.ReactNode; + /** + * What a comment answers to besides its own controls: the phone's long + * press and tap (`useCommentPress`). Spread on each comment's box. + */ + itemInteraction?: (actions: CommentItemActions) => React.HTMLAttributes; + /** + * The comment whose actions the surface holds open, by id (the phone's long + * press sheet). While it is one of this thread's, its current actions go to + * `onHeldActions` each time what they offer changes, so a gate that opens + * while the sheet is up (the host's answer to `updatesOthers`) adds its row. + */ + heldId?: string | null; + onHeldActions?: (actions: CommentItemActions) => void; className?: string; } @@ -126,6 +145,9 @@ export const CommentThread: React.FC = ({ mode = 'expand', onOpen, renderActions, + itemInteraction, + heldId, + onHeldActions, className, }) => { const { t } = useDetailTranslation(); @@ -152,7 +174,7 @@ export const CommentThread: React.FC = ({ const resolvedBy = resolved ? resolverName(root, comments.mentionSuggestions) : undefined; const openReply = React.useCallback(() => { - if (mode === 'summary') { + if (mode !== 'expand') { onOpen?.(); return; } @@ -192,12 +214,30 @@ export const CommentThread: React.FC = ({ : undefined, }); - const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode, itemClassName?: string) => ( + // The held comment's actions, reported again whenever what they offer changes. + const heldItem = heldId == null ? undefined : [root, ...replies].find((item) => String(item.id) === heldId); + const held = heldItem ? actionsOf(heldItem, heldItem === root) : undefined; + const heldOffer = held + ? [!!held.onReact, !!held.onResolve, !!held.resolved, !!held.onEdit, !!held.onDelete].join() + : null; + const heldReport = React.useRef({ held, onHeldActions }); + React.useLayoutEffect(() => { + heldReport.current = { held, onHeldActions }; + }); + React.useLayoutEffect(() => { + const { held: current, onHeldActions: report } = heldReport.current; + if (current) report?.(current); + }, [heldItem, heldOffer]); + + const itemOf = (item: FeedItem, isRoot: boolean, footer?: React.ReactNode, itemClassName?: string) => { + const actions = renderActions || itemInteraction ? actionsOf(item, isRoot) : undefined; + return ( = ({ onToggleReaction={onToggleReaction ? (emoji) => void onToggleReaction(item.id, emoji) : undefined} footer={footer} /> - ); + ); + }; + + if (mode === 'page') { + return ( +
+ {resolved && ( +

+

+ )} + {itemOf(root, true)} + {replies.length > 0 && ( +
+ {replies.map((reply) => itemOf(reply, false))} +
+ )} +
+ ); + } const open = mode === 'expand' && expanded; const summary = replies.length > 0 && !open && ( diff --git a/ui/packages/plugin-detail/src/comments/CommentsFilterMenu.tsx b/ui/packages/plugin-detail/src/comments/CommentsFilterMenu.tsx new file mode 100644 index 00000000000..64bbd6f7896 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentsFilterMenu.tsx @@ -0,0 +1,73 @@ +/** + * 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, + DropdownMenuCheckboxItem, + DropdownMenuContent, + DropdownMenuTrigger, + cn, +} from '@object-ui/components'; +import { ListFilter } from 'lucide-react'; +import { useDetailTranslation } from '../useDetailTranslation'; +import type { CommentThreadFilter } from './commentThreads'; + +export interface CommentsFilterMenuProps { + filter: CommentThreadFilter; + onFilterChange: React.Dispatch>; + /** The trigger's box: 28 px in the desktop panel's header, 44 px on the phone. */ + triggerClassName?: string; +} + +/** + * The comment list's filter (objectstack#36075 item 7, objectstack#36076 item + * 7): 「显示已解决」 and 「只看我参与的」, the same menu on the desktop panel + * and the phone's comment page. The trigger reads as active while 「只看我参与的」 + * is on. + */ +export const CommentsFilterMenu: React.FC = ({ filter, onFilterChange, triggerClassName }) => { + const { t } = useDetailTranslation(); + const filtering = filter.onlyMine || !filter.showResolved; + return ( + + + + + + onFilterChange((f) => ({ ...f, showResolved: checked === true }))} + data-comments-filter-option="show-resolved" + > + {t('detail.showResolvedComments')} + + onFilterChange((f) => ({ ...f, onlyMine: checked === true }))} + data-comments-filter-option="only-mine" + > + {t('detail.commentsInvolvingMe')} + + + + ); +}; diff --git a/ui/packages/plugin-detail/src/comments/CommentsPage.test.tsx b/ui/packages/plugin-detail/src/comments/CommentsPage.test.tsx new file mode 100644 index 00000000000..45abc7287ba --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentsPage.test.tsx @@ -0,0 +1,330 @@ +/** + * 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. + */ + +/** + * The phone's comment page (objectstack#36076), drawn from the host's + * `DiscussionContext` alone: + * + * - The list shows the top-level comments, oldest first, each with its + * 「N 条回复」; no reply is on the list. A tap on a comment (or on its reply + * count) opens its thread; a tap on a reaction is the reaction's. + * - A thread shows its comment first and every reply after it. + * - The comment box is docked at the foot: in the list it writes a comment, in + * a thread a reply to the thread's comment. It names no keyboard shortcut, + * and its toolbar sits under the text: mention, bold, italic, list, code, + * send. + * - A long press (or the context menu) raises the comment's actions: the six + * reactions, Mark resolved on a thread's comment only, Edit and Delete only + * where the comment thread hands them (the viewer's own comment). The click + * that ends the hold opens nothing. The press tells the host, and the sheet + * follows the comment's actions while it is up. + * - The filter (resolved shown, only mine) is the desktop panel's. + */ + +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, act } from '@testing-library/react'; +import { DiscussionContextProvider, type DiscussionContextValue } from '@object-ui/react'; +import type { FeedItem } from '@object-ui/types'; +import { CommentsPage, type CommentsPageProps } from './CommentsPage'; +import { COMMENT_LONG_PRESS_MS } from './useCommentPress'; + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +const at = (minute: number) => new Date(Date.UTC(2026, 10, 21, 9, minute)).toISOString(); + +// c1: the viewer's, two replies, a 👍 of the viewer's. c2: Grace's. +const ITEMS: FeedItem[] = [ + { id: 'c2', type: 'comment', actor: 'Grace', body: 'second thread', createdAt: at(10), resolved: false }, + { + id: 'c1', + type: 'comment', + actor: 'Ada', + body: 'first thread', + createdAt: at(1), + authoredByViewer: true, + resolved: false, + reactions: [{ emoji: '👍', count: 1, reacted: true }], + }, + { id: 'r1', type: 'comment', actor: 'Grace', body: 'first reply', createdAt: at(5), parentId: 'c1' }, + { id: 'r2', type: 'comment', actor: 'Ada', body: 'second reply', createdAt: at(6), parentId: 'c1', authoredByViewer: true }, + { id: 'a1', type: 'field_change', actor: 'System', body: 'stage changed', createdAt: at(2) }, +]; + +function renderPage( + props: Partial = {}, + value: Partial = {}, +) { + const writes = { + onAddComment: vi.fn(), + onAddReply: vi.fn(), + onToggleReaction: vi.fn(), + onEditComment: vi.fn(), + onDeleteComment: vi.fn(), + onResolveComment: vi.fn(), + }; + const handlers = { onOpenThread: vi.fn(), onBack: vi.fn(), onEngage: vi.fn() }; + const view = (threadId: string | null) => ( + + + + ); + const utils = render(view(props.threadId ?? null)); + return { ...writes, ...handlers, rerenderAt: (threadId: string | null) => utils.rerender(view(threadId)) }; +} + +const page = () => screen.getByRole('dialog'); +const commentEl = (id: string) => document.querySelector(`[data-comment-id="${id}"]`) as HTMLElement; +const sheet = () => document.querySelector('[data-comment-action-sheet]') as HTMLElement | null; + +function hold(el: HTMLElement) { + fireEvent.pointerDown(el, { pointerType: 'touch', button: 0, clientX: 10, clientY: 10 }); + act(() => { + vi.advanceTimersByTime(COMMENT_LONG_PRESS_MS); + }); + fireEvent.pointerUp(el, { pointerType: 'touch' }); + fireEvent.click(el); +} + +describe('CommentsPage — the list', () => { + it('shows the top-level comments with their reply count, and no reply', () => { + renderPage(); + expect(page()).toHaveAttribute('data-comments-page', 'list'); + const roots = Array.from(document.querySelectorAll('[data-comments-list] [data-comment-thread] > [data-comment-item]')).map( + (el) => el.getAttribute('data-comment-id'), + ); + expect(roots).toEqual(['c1', 'c2']); + expect(screen.getByRole('button', { name: /2 replies/ })).toBeInTheDocument(); + expect(screen.queryByText('first reply')).toBeNull(); + expect(screen.queryByText('stage changed')).toBeNull(); + expect(within(page()).getByRole('heading', { name: 'Comments' })).toBeInTheDocument(); + }); + + it('a tap on a comment or its reply count opens the thread; a tap on a reaction is the reaction', () => { + const { onOpenThread, onToggleReaction } = renderPage(); + fireEvent.click(screen.getByText('second thread')); + expect(onOpenThread).toHaveBeenLastCalledWith('c2'); + fireEvent.click(screen.getByRole('button', { name: /2 replies/ })); + expect(onOpenThread).toHaveBeenLastCalledWith('c1'); + onOpenThread.mockClear(); + fireEvent.click(commentEl('c1').querySelector('[data-comment-reaction="👍"]')!); + expect(onToggleReaction).toHaveBeenCalledWith('c1', '👍'); + expect(onOpenThread).not.toHaveBeenCalled(); + }); + + it('a focused comment opens on Enter', () => { + const { onOpenThread } = renderPage(); + fireEvent.keyDown(commentEl('c2'), { key: 'Enter' }); + expect(onOpenThread).toHaveBeenCalledWith('c2'); + }); + + it('「‹」 names the record and goes back', () => { + const { onBack } = renderPage(); + const back = within(page()).getByRole('button', { name: /Acme Corp/ }); + fireEvent.click(back); + expect(onBack).toHaveBeenCalledTimes(1); + }); + + it('the docked box writes a new comment and names no keyboard shortcut', async () => { + const { onAddComment, onAddReply } = renderPage(); + const dock = document.querySelector('[data-comments-composer="comment"]') as HTMLElement; + const box = within(dock).getByRole('textbox'); + fireEvent.focus(box); + fireEvent.change(box, { target: { value: 'hello' } }); + const toolbar = dock.querySelector('[data-composer-toolbar="phone"]') as HTMLElement; + expect(within(toolbar).getAllByRole('button').map((b) => b.getAttribute('aria-label'))).toEqual([ + 'Mention someone', + 'Bold', + 'Italic', + 'List', + 'Inline code', + 'Send', + ]); + await act(async () => { + fireEvent.click(within(toolbar).getByRole('button', { name: 'Send' })); + }); + expect(onAddComment).toHaveBeenCalledWith('hello'); + expect(onAddReply).not.toHaveBeenCalled(); + expect(page().innerHTML).not.toMatch(/Ctrl/); + }); +}); + +describe('CommentsPage — a thread', () => { + it('shows the comment first and its replies after it, and replies to the thread', async () => { + const { onAddReply, onAddComment } = renderPage({ threadId: 'c1' }); + expect(page()).toHaveAttribute('data-comments-page', 'thread'); + const thread = document.querySelector('[data-comments-thread]') as HTMLElement; + const order = Array.from(thread.querySelectorAll('[data-comment-item]')).map((el) => el.getAttribute('data-comment-id')); + expect(order).toEqual(['c1', 'r1', 'r2']); + expect(within(page()).getByRole('button', { name: /Comments/ })).toHaveAttribute('data-comments-page-back'); + const dock = document.querySelector('[data-comments-composer="reply"]') as HTMLElement; + const box = within(dock).getByRole('textbox'); + fireEvent.focus(box); + fireEvent.change(box, { target: { value: 'me too' } }); + await act(async () => { + fireEvent.click(within(dock).getByRole('button', { name: 'Send' })); + }); + expect(onAddReply).toHaveBeenCalledWith('c1', 'me too'); + expect(onAddComment).not.toHaveBeenCalled(); + }); + + it('a thread that is not here shows the list', () => { + renderPage({ threadId: 'gone' }); + expect(page()).toHaveAttribute('data-comments-page', 'list'); + }); + + it('keeps the list draft while a thread is open', () => { + const { rerenderAt } = renderPage(); + const listBox = () => + within(document.querySelector('[data-comments-composer="comment"]') as HTMLElement).getByRole('textbox'); + fireEvent.focus(listBox()); + fireEvent.change(listBox(), { target: { value: 'half written' } }); + rerenderAt('c2'); + rerenderAt(null); + expect(listBox()).toHaveValue('half written'); + }); +}); + +describe('CommentsPage — the long press', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + it("raises the reactions, Mark resolved, Edit and Delete on the viewer's own comment, and the release opens nothing", () => { + const { onOpenThread, onEngage } = renderPage(); + hold(commentEl('c1')); + expect(sheet()).not.toBeNull(); + expect(onOpenThread).not.toHaveBeenCalled(); + expect(onEngage).toHaveBeenCalledTimes(1); + const emojis = Array.from(sheet()!.querySelectorAll('[data-comment-emoji]')).map((el) => el.getAttribute('data-comment-emoji')); + expect(emojis).toHaveLength(6); + expect(sheet()!.querySelector('[data-comment-emoji="👍"]')).toHaveAttribute('aria-pressed', 'true'); + const rows = Array.from(sheet()!.querySelectorAll('[data-comment-action]')).map((el) => el.getAttribute('data-comment-action')); + expect(rows).toEqual(['resolve', 'edit', 'delete']); + }); + + it("offers no Edit or Delete on another person's comment", () => { + renderPage(); + hold(commentEl('c2')); + const rows = Array.from(sheet()!.querySelectorAll('[data-comment-action]')).map((el) => el.getAttribute('data-comment-action')); + expect(rows).not.toContain('edit'); + expect(rows).not.toContain('delete'); + expect(sheet()!.querySelectorAll('[data-comment-emoji]')).toHaveLength(6); + }); + + it('offers Mark resolved on the thread’s comment only, never on a reply', () => { + renderPage({ threadId: 'c1' }); + hold(commentEl('r2')); + const rows = Array.from(sheet()!.querySelectorAll('[data-comment-action]')).map((el) => el.getAttribute('data-comment-action')); + expect(rows).toEqual(['edit', 'delete']); + }); + + it('a reaction in the sheet toggles it and closes the sheet; Delete goes to the host', () => { + const { onToggleReaction, onDeleteComment } = renderPage(); + hold(commentEl('c1')); + fireEvent.click(sheet()!.querySelector('[data-comment-emoji="🎉"]')!); + expect(onToggleReaction).toHaveBeenCalledWith('c1', '🎉'); + hold(commentEl('c1')); + fireEvent.click(sheet()!.querySelector('[data-comment-action="delete"]')!); + expect(onDeleteComment).toHaveBeenCalledWith('c1'); + }); + + it('a press that travels is a scroll, not a hold', () => { + renderPage(); + const el = commentEl('c2'); + fireEvent.pointerDown(el, { pointerType: 'touch', button: 0, clientX: 10, clientY: 10 }); + fireEvent.pointerMove(el, { pointerType: 'touch', clientX: 10, clientY: 40 }); + act(() => { + vi.advanceTimersByTime(COMMENT_LONG_PRESS_MS); + }); + expect(sheet()).toBeNull(); + }); + + it('the context menu raises the same sheet', () => { + renderPage(); + fireEvent.contextMenu(commentEl('c2')); + expect(sheet()).not.toBeNull(); + }); + + it('the press engages before the hold opens, and a verdict that lands while the sheet is up adds its rows', () => { + const writes = { + onToggleReaction: vi.fn(), + onEditComment: vi.fn(), + onDeleteComment: vi.fn(), + onResolveComment: vi.fn(), + }; + const onEngage = vi.fn(); + const view = (updatesOthers: boolean | undefined) => ( + + + + ); + const { rerender } = render(view(undefined)); + const el = commentEl('c2'); + fireEvent.pointerDown(el, { pointerType: 'touch', button: 0, clientX: 10, clientY: 10 }); + // The host is told at the press, not at the end of the hold. + expect(onEngage).toHaveBeenCalledTimes(1); + act(() => { + vi.advanceTimersByTime(COMMENT_LONG_PRESS_MS); + }); + fireEvent.pointerUp(el, { pointerType: 'touch' }); + fireEvent.click(el); + const rows = () => + Array.from(sheet()!.querySelectorAll('[data-comment-action]')).map((row) => row.getAttribute('data-comment-action')); + // Grace's comment, before the host has its answer: Mark resolved (any + // thread the viewer reads, objectstack#36186) and Delete (the viewer moderates). + expect(rows()).toEqual(['resolve', 'delete']); + // The answer lands with the sheet still up: Edit of another's comment joins. + rerender(view(true)); + expect(rows()).toEqual(['resolve', 'edit', 'delete']); + fireEvent.click(sheet()!.querySelector('[data-comment-action="resolve"]')!); + expect(writes.onResolveComment).toHaveBeenCalledWith('c2', true); + }); + + it("behind the own-comment delete door (objectstack#36191) Delete is offered on the viewer's own comment with no reply only", () => { + renderPage({ threadId: 'c1' }, { ownCommentDeletesOnly: true, moderatesComments: true }); + const rowsOf = (id: string) => { + hold(commentEl(id)); + return Array.from(sheet()!.querySelectorAll('[data-comment-action]')).map((el) => el.getAttribute('data-comment-action')); + }; + // The viewer's own reply: Delete. + expect(rowsOf('r2')).toContain('delete'); + // The viewer's own comment with replies under it: the door keeps it. + expect(rowsOf('c1')).not.toContain('delete'); + // Grace's reply: not the viewer's, so no Delete even though they moderate. + expect(rowsOf('r1')).not.toContain('delete'); + }); + + it('a read-only discussion raises no sheet and docks no box', () => { + render( + + + , + ); + expect(document.querySelector('[data-comments-composer]')).toBeNull(); + hold(commentEl('c2')); + expect(sheet()).toBeNull(); + }); +}); + +describe('CommentsPage — the filter', () => { + it('hides resolved threads by default and shows them from the filter', () => { + const items = ITEMS.map((i) => (i.id === 'c2' ? { ...i, resolved: true } : i)); + render( + + + , + ); + expect(screen.queryByText('second thread')).toBeNull(); + expect(document.querySelector('[data-comments-filter]')).not.toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/comments/CommentsPage.tsx b/ui/packages/plugin-detail/src/comments/CommentsPage.tsx new file mode 100644 index 00000000000..156b86d4c62 --- /dev/null +++ b/ui/packages/plugin-detail/src/comments/CommentsPage.tsx @@ -0,0 +1,339 @@ +/** + * 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, cn } from '@object-ui/components'; +import { ChevronLeft, Loader2, MessageSquare } from 'lucide-react'; +import { useDetailTranslation } from '../useDetailTranslation'; +import { CommentActionSheet } from './CommentActionSheet'; +import { CommentComposer } from './CommentComposer'; +import { CommentsFilterMenu } from './CommentsFilterMenu'; +import { CommentThread, type CommentItemActions } from './CommentThread'; +import { DEFAULT_COMMENT_THREAD_FILTER, filterCommentThreads, type CommentThreadFilter } from './commentThreads'; +import { useCommentPress } from './useCommentPress'; +import { useRecordComments } from './useRecordComments'; + +export interface CommentsPageProps { + /** The thread the page shows, by its top-level comment's id; `null`: the list. */ + threadId: string | null; + /** A thread in the list was opened: the host shows `threadId` (it pushes a history entry). */ + onOpenThread: (rootId: string) => void; + /** 「‹」: from a thread back to the list, from the list back to the record. */ + onBack: () => void; + /** The list's 「‹」 names where it returns: the record. */ + backLabel: string; + /** + * The reader began a press on a comment: the host may now ask what the + * comment's actions take (`updatesOthers`), and not before + * (objectstack#28470). The hold that opens them lasts long enough for the + * answer. + */ + onEngage?: () => void; + className?: string; +} + +/** + * The on-screen keyboard while the page is up: the visible area's top and + * height (`visualViewport`), so the page stands on the keyboard with its + * comment box in view. `null` with no keyboard (or no `visualViewport`): + * `100dvh` and the layout viewport do not shrink for it on iOS Safari, nor on + * Chrome for Android by default. + */ +function useVisibleViewport(): { top: number; height: number } | null { + const [box, setBox] = React.useState<{ top: number; height: number } | null>(null); + React.useEffect(() => { + const viewport = typeof window === 'undefined' ? null : window.visualViewport; + if (!viewport) return undefined; + const read = () => { + const covered = Math.round(window.innerHeight - viewport.height - viewport.offsetTop); + // Below this the gap is the browser's own chrome moving, not a keyboard. + setBox(covered < 80 ? null : { top: Math.round(viewport.offsetTop), height: Math.round(viewport.height) }); + }; + read(); + viewport.addEventListener('resize', read); + viewport.addEventListener('scroll', read); + return () => { + viewport.removeEventListener('resize', read); + viewport.removeEventListener('scroll', read); + }; + }, []); + return box; +} + +const HEADER_BUTTON = + 'inline-flex min-h-11 min-w-11 items-center justify-center rounded-md text-foreground transition-colors hover:bg-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-ring'; + +/** + * The record's comments on a phone (objectstack#36076): a page over the + * record, two levels deep. The list shows each thread's top-level comment and + * 「N 条回复」; a tap opens the thread, its comment first and the replies under + * it. The comment box stays docked at the foot of the screen, above the + * keyboard while it is up: in the list it writes a new comment, in a thread a + * reply. A long press on a comment raises its actions from the bottom. + * + * The discussion, the writes and every gate are the host's + * `DiscussionContext`, read through `useRecordComments`, the same as the + * desktop panel's; only how the threads are laid out and how a comment's + * actions are reached differ. + */ +export const CommentsPage: React.FC = ({ + threadId, + onOpenThread, + onBack, + backLabel, + onEngage, + className, +}) => { + const { t } = useDetailTranslation(); + const comments = useRecordComments(); + const { threads, loading, denied, failed, onRetry, onAddComment, onAddReply, resolvable } = comments; + const [filter, setFilter] = React.useState(DEFAULT_COMMENT_THREAD_FILTER); + const shown = React.useMemo( + () => (resolvable ? filterCommentThreads(threads, filter) : threads), + [resolvable, threads, filter], + ); + const thread = threadId == null ? undefined : threads.find((th) => String(th.root.id) === threadId); + // A thread that is not (or no longer) here — deleted, or a stale link — shows the list. + const inThread = !!thread; + + // The held comment's actions. The thread that holds it hands them again when + // what they offer changes (`onHeldActions`), so the sheet is never the + // snapshot of the press: a verdict that lands while it is up adds its rows. + const [sheet, setSheet] = React.useState(null); + const hold = React.useCallback((actions: CommentItemActions) => { + // A comment with nothing to do on it (a read-only discussion) raises nothing. + if (actions.onReact || actions.onResolve || actions.onEdit || actions.onDelete) setSheet(actions); + }, []); + const refreshHeld = React.useCallback((actions: CommentItemActions) => { + setSheet((current) => (current && String(current.item.id) === String(actions.item.id) ? actions : current)); + }, []); + const heldId = sheet ? String(sheet.item.id) : null; + // The press itself engages, not the hold it may become: the 500 ms hold + // covers the host's question about the comment's actions. + const listPress = useCommentPress({ + onPressStart: onEngage, + onLongPress: hold, + onTap: (actions) => onOpenThread(String(actions.item.id)), + }); + const threadPress = useCommentPress({ onPressStart: onEngage, onLongPress: hold }); + // Moving between the list and a thread closes a sheet left open (adjusted while rendering). + const [sheetThread, setSheetThread] = React.useState(threadId); + if (sheetThread !== threadId) { + setSheetThread(threadId); + setSheet(null); + } + + // 「回复」 inside the thread puts the caret in the docked box. + const [composerFocus, setComposerFocus] = React.useState(0); + + // The newest comment is at the foot of the list: it opens scrolled there and + // follows a thread that is added. A thread opens at its comment and follows + // a reply that is added. + const listRef = React.useRef(null); + const threadRef = React.useRef(null); + const threadCount = threads.length; + React.useLayoutEffect(() => { + const list = listRef.current; + if (list) list.scrollTop = list.scrollHeight; + }, [threadCount, loading]); + const replyCount = thread?.replies.length ?? 0; + const seenReplies = React.useRef<{ id: string | null; count: number }>({ id: null, count: 0 }); + React.useLayoutEffect(() => { + const el = threadRef.current; + const seen = seenReplies.current; + if (el && seen.id === threadId && replyCount > seen.count) el.scrollTop = el.scrollHeight; + else if (el && seen.id !== threadId) el.scrollTop = 0; + seenReplies.current = { id: threadId, count: replyCount }; + }, [threadId, replyCount]); + + const backRef = React.useRef(null); + React.useEffect(() => { + backRef.current?.focus({ preventScroll: true }); + }, [inThread]); + + const viewport = useVisibleViewport(); + + let listBody: React.ReactNode; + if (denied) { + listBody = ; + } else if (failed && threadCount === 0) { + listBody = ( + + {onRetry && ( + + )} + + ); + } else if (loading && threadCount === 0) { + listBody = ( +
+ +
+ ); + } else if (threadCount === 0) { + listBody = ( +
+
+ ); + } else if (shown.length === 0) { + listBody = ( +
+

+ {filter.onlyMine ? t('detail.noCommentsInvolvingMe') : t('detail.noUnresolvedComments')} +

+ +
+ ); + } else { + listBody = ( +
+ {shown.map((th) => ( + onOpenThread(String(th.root.id))} + itemInteraction={listPress.bind} + heldId={heldId} + onHeldActions={refreshHeld} + /> + ))} +
+ ); + } + + const title = inThread ? t('detail.commentThread') : t('detail.comments'); + return ( +
{ + if (e.key !== 'Escape' || e.defaultPrevented) return; + e.stopPropagation(); + onBack(); + }} + data-comments-page={inThread ? 'thread' : 'list'} + data-keyboard-up={viewport ? 'true' : undefined} + data-owns-escape="" + > +
+ +

{title}

+
+ {!inThread && resolvable && !denied && ( + + )} +
+
+
+ {listBody} +
+ {thread && ( +
+ setComposerFocus((n) => n + 1)} + itemInteraction={threadPress.bind} + heldId={heldId} + onHeldActions={refreshHeld} + /> +
+ )} + {/* The list's box and a thread's are two boxes: each keeps its own + draft, and a draft written in the list is never posted as a reply. */} + {!denied && onAddComment && ( + + )} + {!denied && onAddReply && thread && ( + + onAddReply(thread.root.id, text)} + /> + + )} + setSheet(null)} /> +
+ ); +}; + +/** The comment box's place at the foot of the page, over the safe area or on the keyboard. */ +const ComposerDock: React.FC<{ hidden?: boolean; keyboardUp: boolean; kind: 'comment' | 'reply'; children: React.ReactNode }> = ({ + hidden, + keyboardUp, + kind, + children, +}) => ( + +); + +const PageNote: React.FC<{ kind: 'denied' | 'failed'; text: string; children?: React.ReactNode }> = ({ kind, text, children }) => ( +
+

{text}

+ {children} +
+); diff --git a/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx b/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx index cf8c5f4d40c..3ed003ff961 100644 --- a/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx +++ b/ui/packages/plugin-detail/src/comments/CommentsPanel.tsx @@ -7,17 +7,11 @@ */ import * as React from 'react'; -import { - Button, - DropdownMenu, - DropdownMenuCheckboxItem, - DropdownMenuContent, - DropdownMenuTrigger, - cn, -} from '@object-ui/components'; -import { ListFilter, Loader2, MessageSquare, X } from 'lucide-react'; +import { Button, cn } from '@object-ui/components'; +import { Loader2, MessageSquare, X } from 'lucide-react'; import { useDetailTranslation } from '../useDetailTranslation'; import { CommentComposer } from './CommentComposer'; +import { CommentsFilterMenu } from './CommentsFilterMenu'; import { CommentHoverActions } from './CommentHoverActions'; import { CommentThread } from './CommentThread'; import { DEFAULT_COMMENT_THREAD_FILTER, filterCommentThreads, type CommentThreadFilter } from './commentThreads'; @@ -50,7 +44,6 @@ export const CommentsPanel: React.FC = ({ onClose, className () => (resolvable ? filterCommentThreads(threads, filter) : threads), [resolvable, threads, filter], ); - const filtering = resolvable && (filter.onlyMine || !filter.showResolved); // The newest comment is at the foot: the list opens scrolled to it, and // follows a thread the reader (or anyone) adds. @@ -155,41 +148,7 @@ export const CommentsPanel: React.FC = ({ onClose, className

{title}

- {resolvable && !denied && ( - - - - - - setFilter((f) => ({ ...f, showResolved: checked === true }))} - data-comments-filter-option="show-resolved" - > - {t('detail.showResolvedComments')} - - setFilter((f) => ({ ...f, onlyMine: checked === true }))} - data-comments-filter-option="only-mine" - > - {t('detail.commentsInvolvingMe')} - - - - )} + {resolvable && !denied && } {onClose && (