From c1894060d581b08ea713ec17bc6d9d156d2ecd4b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 13:32:26 +0000 Subject: [PATCH 1/7] wip(comments): desktop comment panel (#36075) Claude-Session: https://claude.ai/code/session_01L6bhgXXdtDHm8mLZYX8Bsb Co-authored-by: Claude --- .../app-shell/src/views/RecordDetailView.tsx | 78 ++++++-- .../src/views/recordCommentsPanel.tsx | 129 +++++++++++++ .../src/views/recordDrawerContext.ts | 5 + .../app-shell/src/views/recordDrawerStack.tsx | 12 +- .../src/custom/navigation-overlay.tsx | 7 + .../components/src/custom/record-top-bar.tsx | 10 +- ui/packages/i18n/src/locales/ar.ts | 5 + ui/packages/i18n/src/locales/de.ts | 5 + ui/packages/i18n/src/locales/en.ts | 5 + ui/packages/i18n/src/locales/es.ts | 5 + ui/packages/i18n/src/locales/fr.ts | 5 + ui/packages/i18n/src/locales/ja.ts | 5 + ui/packages/i18n/src/locales/ko.ts | 5 + ui/packages/i18n/src/locales/pt-BR.ts | 5 + ui/packages/i18n/src/locales/ru.ts | 5 + ui/packages/i18n/src/locales/zh-Hans.ts | 5 + ui/packages/i18n/src/locales/zh-Hant.ts | 5 + .../plugin-detail/src/ReactionPicker.tsx | 2 +- .../src/RecordActivityTimeline.tsx | 2 +- .../src/comments/CommentAvatar.tsx | 57 ++++++ .../src/comments/CommentComposer.tsx | 76 ++++++++ .../src/comments/CommentHoverActions.tsx | 161 +++++++++++++++++ .../src/comments/CommentItem.tsx | 170 ++++++++++++++++++ .../src/comments/CommentThread.tsx | 169 +++++++++++++++++ .../src/comments/CommentsButton.tsx | 51 ++++++ .../src/comments/CommentsPanel.tsx | 143 +++++++++++++++ .../src/comments/commentThreads.ts | 72 ++++++++ .../plugin-detail/src/comments/commentTime.ts | 29 +++ .../plugin-detail/src/comments/index.ts | 19 ++ .../src/comments/useRecordComments.ts | 74 ++++++++ ui/packages/plugin-detail/src/index.tsx | 28 +++ .../plugin-detail/src/recordTimelineStream.ts | 10 ++ .../src/renderers/record-activity.tsx | 23 ++- .../plugin-detail/src/useDetailTranslation.ts | 5 + .../plugin-detail/src/useRecordPageTier.ts | 12 +- 35 files changed, 1374 insertions(+), 25 deletions(-) create mode 100644 ui/packages/app-shell/src/views/recordCommentsPanel.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentAvatar.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentComposer.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentHoverActions.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentItem.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentThread.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentsButton.tsx create mode 100644 ui/packages/plugin-detail/src/comments/CommentsPanel.tsx create mode 100644 ui/packages/plugin-detail/src/comments/commentThreads.ts create mode 100644 ui/packages/plugin-detail/src/comments/commentTime.ts create mode 100644 ui/packages/plugin-detail/src/comments/index.ts create mode 100644 ui/packages/plugin-detail/src/comments/useRecordComments.ts diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 4c724436ec6..e41438c3924 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, @@ -1256,7 +1257,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) ── @@ -2657,7 +2682,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 } : {}), @@ -2938,7 +2963,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 @@ -3296,8 +3325,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; @@ -3590,7 +3625,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 @@ -3663,7 +3698,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 @@ -3725,9 +3760,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 @@ -5435,6 +5480,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri stepper={pageStepper} actionSlotRef={setBarActionSlot} toggles={approvalQueueSwitch || panelToggles ? <>{approvalQueueSwitch}{panelToggles} : undefined} + comments={commentsButton} frame={pageFrame} record={pageRecordRow} /> @@ -5589,6 +5635,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. */} @@ -5733,6 +5780,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): @@ -5772,7 +5820,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 @@ -5879,7 +5927,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.tsx b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx new file mode 100644 index 00000000000..73734ae0537 --- /dev/null +++ b/ui/packages/app-shell/src/views/recordCommentsPanel.tsx @@ -0,0 +1,129 @@ +/** + * 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, 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; +}) { + 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/custom/navigation-overlay.tsx b/ui/packages/components/src/custom/navigation-overlay.tsx index 7d307c70560..28d2eb74c3b 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. @@ -480,6 +485,7 @@ export const NavigationOverlay: React.FC = ({ trail, stepper, toggles, + comments, actionSlotRef, stepperHidden = false, recordRow, @@ -593,6 +599,7 @@ export const NavigationOverlay: React.FC = ({ actionSlotRef={actionSlotRef} record={recordRow} toggles={toggles} + comments={comments} frame={ <> {onExpand && ( 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 && ( <> = ({ )}
- {isStream && ( + {isStream && streamFilters.length > 0 && (
= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + const token = parts[0]; + if (/\p{Script=Han}/u.test(token)) return token[0]; + return token.slice(0, 2).toUpperCase(); +} + +export interface CommentAvatarProps { + item: Pick; + /** 20 px in a thread, 16 px beside 「N 条回复」. */ + size?: 'md' | 'sm'; + className?: string; +} + +/** A comment author's face: their photo, else their initials on a round tile. */ +export const CommentAvatar: React.FC = ({ item, size = 'md', className }) => { + const box = size === 'sm' ? 'h-4 w-4 text-[8px]' : 'h-5 w-5 text-[10px]'; + if (item.actorAvatarUrl) { + return ( + + ); + } + return ( + + ); +}; 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..a4084a85e89 --- /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 { CommentAvatar } from './CommentAvatar'; +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 ( +
+