An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): add CommentThread (#7607)
Ernestfc12a1803dbf
diff --git a/.changeset/lab-comment-thread-catalog.md b/.changeset/lab-comment-thread-catalog.mdnew file mode 100644index 0000000000..2f947c0a42--- /dev/null+++ b/.changeset/lab-comment-thread-catalog.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] i18n catalog: add the English messages used by the Lab CommentThread for replies, reactions, edit history, resolution, errors, comment actions, and the unsaved-draft warning it announces when a dismissal would discard a reply or edit.++@ernesttdiff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.jsonindex feae13873b..6d00127e6d 100644--- a/apps/storybook/rtl-audit/verified-not-applicable.json+++ b/apps/storybook/rtl-audit/verified-not-applicable.json@@ -357,5 +357,9 @@{"component": "lab/CommentComposer","reason": "CommentComposer stacks an optional quoted passage, the core ChatComposer input, and a footer row of attach, emoji, product controls, and the core ChatSendButton. Every inset, gap, and corner is a logical property or a flex gap, its glyphs (attach, emoji, close) are non-directional, and its only positioned affordances are core Popover and typeahead menus, which the core audit covers. Nothing it owns has a horizontal semantic to mirror."+ },+ {+ "component": "lab/CommentThread",+ "reason": "CommentThread is one Card or Section holding comment rows: an avatar column and a content column in a flex row whose order follows CSS direction, a block-axis avatar rail, header metadata and actions in wrap-capable flex rows, and a reply composer. Insets and the actions' negative bleed use logical properties, its glyphs (reply, resolve, add reaction, copy link, more) are non-directional, and its menus and tooltips are core overlays. Keyboard navigation is Tab order plus the core DropdownMenu, with no component-owned arrow-key semantics."}]diff --git a/apps/storybook/stories/Comments.stories.tsx b/apps/storybook/stories/Comments.stories.tsxindex 15be2e5400..eb98a0232e 100644--- a/apps/storybook/stories/Comments.stories.tsx+++ b/apps/storybook/stories/Comments.stories.tsx@@ -1,12 +1,18 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import type {Meta, StoryObj} from '@storybook/react';-import {CommentComposer} from '@astryxdesign/lab';+import {VStack} from '@astryxdesign/core/Layout';+import {+ CommentThread,+ type CommentThreadData,+ type CommentUser,+} from '@astryxdesign/lab';import CommentComposerShowcase from '../../../packages/lab/blocks/CommentComposerShowcase';+import CommentThreadInPopover from '../../../packages/lab/blocks/CommentThreadInPopover';+import CommentThreadShowcase from '../../../packages/lab/blocks/CommentThreadShowcase';const meta: Meta = {title: 'Lab/Comments',- component: CommentComposer,tags: ['autodocs'],parameters: {layout: 'centered'},};@@ -14,7 +20,91 @@ const meta: Meta = {export default meta;type Story = StoryObj;+const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};+const MAYA: CommentUser = {id: 'maya', name: 'Maya Chen'};+const JORDAN: CommentUser = {id: 'jordan', name: 'Jordan Lee'};+const SAM: CommentUser = {id: 'sam', name: 'Sam Rivera'};++const THREAD: CommentThreadData = {+ id: 'root',+ author: MAYA,+ body: 'The rollout plan is ready for review.',+ createdAt: '2026-09-30T19:00:00Z',+ reactions: [+ {+ key: 'like',+ label: '👍',+ count: 2,+ reactedByViewer: true,+ actors: [VIEWER, MAYA],+ },+ ],+ replies: [+ {+ id: 'reply',+ author: VIEWER,+ body: 'Looks good to me.',+ createdAt: '2026-09-30T19:10:00Z',+ },+ ],+};+/** A controlled standalone composer that posts into a short list. */export const Composer: Story = {render: () => <CommentComposerShowcase />,};++/** One thread on its own: a margin comment beside a document. */+export const MarginComment: Story = {+ render: () => <CommentThreadShowcase />,+};++/**+ * A thread in a Popover that owns its dismissal: with an unsaved reply, the+ * first press outside or Escape shakes the thread and keeps the draft.+ */+export const InPopover: Story = {+ render: () => <CommentThreadInPopover />,+};++/** A host-opened thread reveals its body and replies without moving focus. */+export const OpenThread: Story = {+ render: () => (+ <VStack width={480}>+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ isSelected+ onSubmit={() => {}}+ onReact={() => {}}+ />+ </VStack>+ ),+};++/** Controlled typing plus hidden seen metadata, ready for a transport adapter. */+export const LiveState: Story = {+ render: () => (+ <VStack width={480}>+ <CommentThread+ comment={{+ ...THREAD,+ typingUsers: [JORDAN, SAM],+ seenBy: [JORDAN, SAM],+ replies: [+ {+ id: 'live-reply',+ author: VIEWER,+ body: 'The review notes are incorporated.',+ createdAt: '2026-09-30T19:10:00Z',+ seenBy: [MAYA, JORDAN, SAM],+ },+ ],+ }}+ currentUser={VIEWER}+ isSelected+ onSubmit={() => {}}+ />+ </VStack>+ ),+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 919670841f..d0e9e537e7 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -566,6 +566,11 @@"path": "components/lab/comment-pin","aliases": []},+ {+ "name": "component-lab-comment-thread",+ "path": "components/lab/comment-thread",+ "aliases": []+ },{"name": "component-lab-diff-viewer","path": "components/lab/diff-viewer",@@ -1900,6 +1905,11 @@"path": "examples/comment-pin/host-owned-placement","aliases": []},+ {+ "name": "example-comment-thread-in-a-popover",+ "path": "examples/comment-thread/in-a-popover",+ "aliases": []+ },{"name": "example-complex-selector-deadline-picker","path": "examples/complex-selector/deadline-picker",@@ -4265,6 +4275,11 @@"path": "showcases/comment-pin/avatar-first-annotations","aliases": []},+ {+ "name": "showcase-comment-thread-margin-comment",+ "path": "showcases/comment-thread/margin-comment",+ "aliases": []+ },{"name": "showcase-complex-selector-default","path": "showcases/complex-selector/default",diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 881ec86875..be46e30b33 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -1830,5 +1830,221 @@"@astryx.commentComposer.cancel": {"defaultMessage": "Cancel","description": "Text button beside the label of a lab CommentComposer that is editing an existing comment; it discards the edit."+ },+ "@astryx.comments.actionsLabel": {+ "defaultMessage": "Actions for {name}'s comment",+ "description": "Accessible name of a comment's actions menu button in a lab Comments panel. `name` is the comment author's name."+ },+ "@astryx.comments.addReaction": {+ "defaultMessage": "Add reaction",+ "description": "Button on a comment in a lab Comments panel that opens the set of reactions to choose from."+ },+ "@astryx.comments.agentBadge": {+ "defaultMessage": "Agent",+ "description": "Badge beside the name of a comment author in a lab Comments panel that is an AI agent rather than a person."+ },+ "@astryx.comments.agentLogo": {+ "defaultMessage": "{name} logo",+ "description": "Alt text of an AI agent's logo used as its avatar in a lab Comments panel. `name` is the agent's name."+ },+ "@astryx.comments.chooseReaction": {+ "defaultMessage": "Choose a reaction",+ "description": "Accessible name of the popover listing the reactions a comment can take in a lab Comments panel."+ },+ "@astryx.comments.copyLink": {+ "defaultMessage": "Copy comment link",+ "description": "Button on a comment in a lab Comments panel that copies a link to the comment."+ },+ "@astryx.comments.currentVersion": {+ "defaultMessage": "Current version",+ "description": "Marks the version shown now in the edit history dialog of a lab Comments panel."+ },+ "@astryx.comments.delete": {+ "defaultMessage": "Delete",+ "description": "Item in a comment's actions menu, and the confirming action of the delete dialog, in a lab Comments panel."+ },+ "@astryx.comments.deleteDescription": {+ "defaultMessage": "Delete {name}'s comment? This action cannot be undone.",+ "description": "Body of the dialog that confirms deleting a comment in a lab Comments panel. `name` is the comment's author."+ },+ "@astryx.comments.deleteFailed": {+ "defaultMessage": "This comment couldn't be deleted.",+ "description": "Error shown on a comment in a lab Comments panel when deleting it failed."+ },+ "@astryx.comments.deleteFailedRetry": {+ "defaultMessage": "This comment couldn't be deleted. Try again.",+ "description": "Text the delete confirmation dialog of a lab Comments panel shows, and announces, after deleting failed."+ },+ "@astryx.comments.deleteTitle": {+ "defaultMessage": "Delete comment?",+ "description": "Title of the dialog that confirms deleting a comment in a lab Comments panel."+ },+ "@astryx.comments.edit": {+ "defaultMessage": "Edit",+ "description": "Item in a comment's actions menu in a lab Comments panel that edits the viewer's own comment."+ },+ "@astryx.comments.editFailed": {+ "defaultMessage": "Your edit couldn't be saved.",+ "description": "Error shown on a comment in a lab Comments panel when saving an edit failed; a Retry action follows."+ },+ "@astryx.comments.editPlaceholder": {+ "defaultMessage": "Edit comment",+ "description": "Placeholder of the composer that edits an existing comment in a lab Comments panel."+ },+ "@astryx.comments.edited": {+ "defaultMessage": "Edited",+ "description": "Text beside a comment's time in a lab Comments panel marking that it was changed after posting; it opens the edit history when one exists."+ },+ "@astryx.comments.editingContext": {+ "defaultMessage": "Editing comment",+ "description": "Label above the composer that edits an existing comment in a lab Comments panel; a Cancel action follows it."+ },+ "@astryx.comments.hideReplies": {+ "defaultMessage": "Hide replies",+ "description": "Text button under an open comment thread in a lab Comments panel that collapses its replies."+ },+ "@astryx.comments.historyEmptyDescription": {+ "defaultMessage": "This comment has no earlier versions.",+ "description": "Empty-state description of the edit history dialog of a lab Comments panel."+ },+ "@astryx.comments.historyEmptyTitle": {+ "defaultMessage": "No edit history",+ "description": "Empty-state title of the edit history dialog of a lab Comments panel for a comment with no earlier versions."+ },+ "@astryx.comments.historyFailed": {+ "defaultMessage": "Edit history couldn't load",+ "description": "Error Banner title in the edit history dialog of a lab Comments panel."+ },+ "@astryx.comments.historyLoadFailed": {+ "defaultMessage": "The comment's edit history couldn't be loaded. Try again.",+ "description": "Error description in the edit history dialog of a lab Comments panel when loading the versions failed."+ },+ "@astryx.comments.historyLoading": {+ "defaultMessage": "Loading edit history",+ "description": "Accessible name of the spinner shown while a comment's earlier versions load in a lab Comments panel."+ },+ "@astryx.comments.historySubtitle": {+ "defaultMessage": "Comment by {name}",+ "description": "Subtitle of the edit history dialog in a lab Comments panel. `name` is the comment's author."+ },+ "@astryx.comments.historyTitle": {+ "defaultMessage": "Edit history",+ "description": "Title of the dialog listing a comment's earlier versions in a lab Comments panel."+ },+ "@astryx.comments.linkCopied": {+ "defaultMessage": "Comment link copied",+ "description": "Label the Copy comment link button takes for two seconds after copying, in a lab Comments panel."+ },+ "@astryx.comments.otherReactors": {+ "defaultMessage": "{count, plural, one {# other} other {# others}}",+ "description": "Last item of the list of people who reacted to a comment in a lab Comments panel, for those not named. `count` is how many."+ },+ "@astryx.comments.outdated": {+ "defaultMessage": "Outdated",+ "description": "Badge beside the quoted passage of an inline comment in a lab Comments panel when that passage was edited away."+ },+ "@astryx.comments.reactionCelebrate": {+ "defaultMessage": "Celebrate",+ "description": "Name of the party-popper reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reactionCount": {+ "defaultMessage": "{reaction}: {count, number}",+ "description": "Accessible name of a reaction toggle on a comment in a lab Comments panel. `reaction` is the reaction's name, e.g. \"Like\"; `count` is how many people reacted."+ },+ "@astryx.comments.reactionFailed": {+ "defaultMessage": "Your reaction couldn't be saved.",+ "description": "Error shown on a comment in a lab Comments panel when adding or removing a reaction failed."+ },+ "@astryx.comments.reactionLaugh": {+ "defaultMessage": "Haha",+ "description": "Name of the laughing reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reactionLike": {+ "defaultMessage": "Like",+ "description": "Name of the thumbs-up reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reactionLove": {+ "defaultMessage": "Love",+ "description": "Name of the red-heart reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reactionSad": {+ "defaultMessage": "Sad",+ "description": "Name of the crying reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reactionWow": {+ "defaultMessage": "Wow",+ "description": "Name of the surprised reaction offered by default on comments in a lab Comments panel."+ },+ "@astryx.comments.reopen": {+ "defaultMessage": "Reopen",+ "description": "Button on a resolved comment thread in a lab Comments panel that reopens it."+ },+ "@astryx.comments.reopenFailed": {+ "defaultMessage": "This thread couldn't be reopened.",+ "description": "Error shown on a comment thread in a lab Comments panel when reopening it failed."+ },+ "@astryx.comments.reply": {+ "defaultMessage": "Reply",+ "description": "Button on a comment in a lab Comments panel that opens a reply to it."+ },+ "@astryx.comments.replyFailed": {+ "defaultMessage": "Your reply couldn't be posted.",+ "description": "Error shown above a reply composer in a lab Comments panel when posting failed; the draft is kept."+ },+ "@astryx.comments.replyPlaceholder": {+ "defaultMessage": "Reply to {name}…",+ "description": "Placeholder of the reply composer in a lab Comments panel comment thread. `name` is the author of the comment being answered."+ },+ "@astryx.comments.replyingContext": {+ "defaultMessage": "Replying to {name}",+ "description": "Accessible context for the reply composer in a lab Comments panel comment thread. `name` is the author of the comment being answered."+ },+ "@astryx.comments.resolve": {+ "defaultMessage": "Mark as resolved",+ "description": "Button on a comment thread in a lab Comments panel that marks the thread resolved."+ },+ "@astryx.comments.resolveFailed": {+ "defaultMessage": "This thread couldn't be resolved.",+ "description": "Error shown on a comment thread in a lab Comments panel when marking it resolved failed."+ },+ "@astryx.comments.resolved": {+ "defaultMessage": "Resolved",+ "description": "Text beside a comment thread's time in a lab Comments panel marking the thread resolved."+ },+ "@astryx.comments.resolvedBy": {+ "defaultMessage": "Resolved by {name}",+ "description": "Tooltip of the Resolved text on a comment thread in a lab Comments panel. `name` is the person who resolved it."+ },+ "@astryx.comments.retryFailed": {+ "defaultMessage": "Retrying didn't work.",+ "description": "Error shown on a comment in a lab Comments panel that failed to post when retrying it failed too."+ },+ "@astryx.comments.sendFailed": {+ "defaultMessage": "Couldn't send this comment.",+ "description": "Error Banner title on a comment in a lab Comments panel that failed to post, when the host gave no message of its own."+ },+ "@astryx.comments.threadLabel": {+ "defaultMessage": "Thread by {name}",+ "description": "Accessible name of the toggle that opens or closes a comment thread in a lab Comments panel. `name` is the author of the thread's first comment."+ },+ "@astryx.comments.unread": {+ "defaultMessage": "New",+ "description": "Badge on a comment in a lab Comments panel the viewer hasn't read yet."+ },+ "@astryx.comments.unsavedDraft": {+ "defaultMessage": "Unsaved draft. Dismiss again to discard it.",+ "description": "Announced to screen readers when a lab CommentThread refuses its first dismissal because a reply or edit holds unsaved text; a second press outside the thread or a second Escape discards the draft."+ },+ "@astryx.comments.versionAuthor": {+ "defaultMessage": "by {name}",+ "description": "Byline beside the time of one version in the edit history dialog of a lab Comments panel. `name` is who saved that version."+ },+ "@astryx.comments.viewHistory": {+ "defaultMessage": "View edit history",+ "description": "Accessible name of the Edited text button on a comment in a lab Comments panel, which opens the comment's earlier versions."+ },+ "@astryx.comments.viewReplies": {+ "defaultMessage": "View {count, plural, one {# reply} other {# replies}}",+ "description": "Text button under a collapsed comment thread in a lab Comments panel that opens it. `count` is the number of replies."}}diff --git a/packages/lab/blocks/CommentThreadInPopover.doc.mjs b/packages/lab/blocks/CommentThreadInPopover.doc.mjsnew file mode 100644index 0000000000..27a9189b2a--- /dev/null+++ b/packages/lab/blocks/CommentThreadInPopover.doc.mjs@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export default {+ type: 'block',+ name: 'In a popover',+ displayName: 'In a popover',+ description:+ 'Open one thread from a passage in a Popover with no padding. The thread owns the Popover’s dismissal through `onDismiss`, so turn the Popover’s light and Escape dismissal off: a press outside or Escape closes the thread, but the first one over an unsaved reply shakes it and keeps the draft.',+ exampleFor: 'CommentThread',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: [+ 'CommentThread',+ 'Popover',+ 'Button',+ 'Card',+ 'Text',+ 'VStack',+ ],+};diff --git a/packages/lab/blocks/CommentThreadInPopover.tsx b/packages/lab/blocks/CommentThreadInPopover.tsxnew file mode 100644index 0000000000..389625e92e--- /dev/null+++ b/packages/lab/blocks/CommentThreadInPopover.tsx@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @input Controlled popover state, a controlled comment thread, and its reply+ * callback+ * @output A passage whose comment button opens one thread in a Popover; the+ * thread owns the Popover's dismissal and keeps an unsaved reply on the+ * first press outside or Escape+ * @position Copyable Lab CommentThread example+ */++import {useState} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {Card} from '@astryxdesign/core/Card';+import {VStack} from '@astryxdesign/core/Layout';+import {Popover} from '@astryxdesign/core/Popover';+import {Text} from '@astryxdesign/core/Text';+import {+ CommentThread,+ type CommentThreadData,+ type CommentUser,+} from '@astryxdesign/lab';++const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};++export default function CommentThreadInPopover() {+ const [isOpen, setIsOpen] = useState(false);+ const [thread, setThread] = useState<CommentThreadData>({+ id: 'passage',+ author: {id: 'maya', name: 'Maya Chen'},+ body: 'Should this say three days? The dry run adds one.',+ createdAt: '2026-09-30T19:00:00Z',+ anchor: {quote: 'The final cohort completes rollout in two days.'},+ });+ const replyCount = thread.replies?.length ?? 0;++ return (+ <Card padding={4} width={420}>+ <VStack gap={3} align="start">+ <Text>+ Every region moves to the new build in three cohorts. The final cohort+ completes rollout in two days.+ </Text>+ <Popover+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ // The thread owns dismissal: it keeps an unsaved reply on the first+ // press outside or Escape, which native light dismiss cannot.+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ label="Comment thread"+ padding={0}+ width={340}+ content={+ <CommentThread+ comment={thread}+ currentUser={VIEWER}+ container="card"+ onDismiss={() => setIsOpen(false)}+ onSubmit={body =>+ setThread(current => ({+ ...current,+ replies: [+ ...(current.replies ?? []),+ {+ id: `reply-${Date.now()}`,+ author: VIEWER,+ body,+ createdAt: new Date().toISOString(),+ },+ ],+ }))+ }+ />+ }>+ <Button+ label={+ replyCount === 0 ? '1 comment' : `${replyCount + 1} comments`+ }+ variant="secondary"+ size="sm"+ />+ </Popover>+ </VStack>+ </Card>+ );+}diff --git a/packages/lab/blocks/CommentThreadShowcase.doc.mjs b/packages/lab/blocks/CommentThreadShowcase.doc.mjsnew file mode 100644index 0000000000..b1a13c55fe--- /dev/null+++ b/packages/lab/blocks/CommentThreadShowcase.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export default {+ type: 'block',+ name: 'Margin comment',+ displayName: 'Margin comment',+ description:+ 'One comment thread in a Card beside a document: it quotes its passage, opens on a press into its replies and reply composer, and resolves.',+ exampleFor: 'CommentThread',+ isReady: true,+ isShowcase: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['CommentThread', 'Card'],+};diff --git a/packages/lab/blocks/CommentThreadShowcase.tsx b/packages/lab/blocks/CommentThreadShowcase.tsxnew file mode 100644index 0000000000..fa0ec2268b--- /dev/null+++ b/packages/lab/blocks/CommentThreadShowcase.tsx@@ -0,0 +1,67 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @input A controlled inline comment thread and its reply callback+ * @output A margin comment: one thread quoting its passage, inside a Card+ * @position Lab CommentThread's docsite showcase and copyable CLI block+ */++import {useState} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {+ CommentThread,+ type CommentThreadData,+ type CommentUser,+} from '@astryxdesign/lab';++const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};++export default function CommentThreadShowcase() {+ const [thread, setThread] = useState<CommentThreadData>({+ id: 'margin',+ author: {id: 'maya', name: 'Maya Chen'},+ body: 'Should this say three days? The dry run adds one.',+ createdAt: '2026-09-30T19:00:00Z',+ anchor: {quote: 'The final cohort completes rollout in two days.'},+ replies: [+ {+ id: 'margin-reply',+ author: VIEWER,+ body: 'Good catch, updating it.',+ createdAt: '2026-09-30T19:20:00Z',+ },+ ],+ });++ return (+ <Card padding={0} width={340}>+ <CommentThread+ comment={thread}+ currentUser={VIEWER}+ container="card"+ onSubmit={body =>+ setThread(current => ({+ ...current,+ replies: [+ ...(current.replies ?? []),+ {+ id: `reply-${Date.now()}`,+ author: VIEWER,+ body,+ createdAt: new Date().toISOString(),+ },+ ],+ }))+ }+ onResolveThread={() =>+ setThread(current => ({...current, isResolved: true}))+ }+ onReopenThread={() =>+ setThread(current => ({...current, isResolved: false}))+ }+ />+ </Card>+ );+}diff --git a/packages/lab/src/Chat/ChatTypingIndicator.tsx b/packages/lab/src/Chat/ChatTypingIndicator.tsxindex 437233d2cf..a0622c526b 100644--- a/packages/lab/src/Chat/ChatTypingIndicator.tsx+++ b/packages/lab/src/Chat/ChatTypingIndicator.tsx@@ -69,6 +69,9 @@ const styles = stylex.create({dots: {display: 'inline-flex',alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ width: 'var(--astryx-chat-typing-indicator-dots-column-width, auto)',gap: spacingVars['--spacing-0-5'],},dot: {diff --git a/packages/lab/src/Comments/CommentActions.tsx b/packages/lab/src/Comments/CommentActions.tsxnew file mode 100644index 0000000000..dcd53c118b--- /dev/null+++ b/packages/lab/src/Comments/CommentActions.tsx@@ -0,0 +1,542 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CommentActions.tsx+ * @input Uses React, React DOM flushSync, StyleX, IconButton, Button, Tooltip,+ * ToggleButton, OverflowList, DropdownMenu, Popover, Text+ * @output Exports CommentActions (a comment's header actions), ReactionSummary+ * (its reaction toggles), and the action-lookup helpers rows use for focus+ * hand-offs+ * @position Internal parts of a comment row in the Comments family+ */++import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';+import {flushSync} from 'react-dom';+import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';+import {+ DropdownMenu,+ type DropdownMenuOption,+} from '@astryxdesign/core/DropdownMenu';+import {Icon} from '@astryxdesign/core/Icon';+import {IconButton} from '@astryxdesign/core/IconButton';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {OverflowList, type OverflowItem} from '@astryxdesign/core/OverflowList';+import {Popover} from '@astryxdesign/core/Popover';+import {Text} from '@astryxdesign/core/Text';+import {ToggleButton} from '@astryxdesign/core/ToggleButton';+import {Tooltip} from '@astryxdesign/core/Tooltip';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';+import {useLocale, useTranslator} from '@astryxdesign/core/i18n';+import {reactionDescription} from './i18n';+import {CommentIcon} from './icons';+import {commentAnchorId, type AnyComment} from './utils';+import type {CommentReaction, CommentReactionOption} from './types';++const LINK_COPIED_RESET_MS = 2_000;+const MORE_MENU_MIN_WIDTH = `calc(${spacingVars['--spacing-8']} * 5)`;++const styles = stylex.create({+ actionsList: {+ flexGrow: 1,+ flexShrink: 1,+ flexBasis: 0,+ minWidth: 0,+ justifyContent: 'flex-end',+ },+ // Every reaction-row control carries one spacing step of inline padding.+ reactionToggle: {+ aspectRatio: 'auto',+ paddingInline: spacingVars['--spacing-2'],+ },+});++export type CommentActionId = 'resolve' | 'reopen' | 'react' | 'reply' | 'link';++/** Mark as resolved on an open thread, Reopen on a resolved one. */+export type ResolveAction = {kind: 'resolve' | 'reopen'; onClick: () => void};++/** One of a comment's action buttons, as it shows. OverflowList renders a+ * hidden copy of every item to measure it; only the copy in the visible list+ * can take focus. */+export function visibleCommentAction(+ root: HTMLElement | null,+ action: CommentActionId,+): HTMLElement | null {+ return (+ root?.querySelector<HTMLElement>(+ `[data-comment-actions-list] [data-comment-action="${action}"]`,+ ) ?? null+ );+}++export function commentMoreMenuTrigger(+ root: HTMLElement | null,+): HTMLElement | null {+ return (+ root?.querySelector<HTMLElement>('[data-comment-more-menu] button') ?? null+ );+}++/** Who reacted, under the emoji and count. */+function ReactionTooltipContent({reaction}: {reaction: CommentReaction}) {+ const t = useTranslator();+ const locale = useLocale();+ const names = (reaction.actors ?? []).map(actor => actor.name);+ const others = reaction.count - names.length;+ const people =+ names.length === 0+ ? reactionDescription(t, reaction)+ : new Intl.ListFormat(locale, {type: 'conjunction'}).format(+ others > 0+ ? [...names, t('@astryx.comments.otherReactors', {count: others})]+ : names,+ );+ return (+ <VStack gap={0.5} align="start">+ <HStack gap={1} align="center">+ <Text as="span" type="body" color="inherit">+ {reaction.label}+ </Text>+ <Text as="span" type="body" color="inherit">+ {reaction.count}+ </Text>+ </HStack>+ <Text type="supporting" color="inherit">+ {people}+ </Text>+ </VStack>+ );+}++/** A comment's reactions: a toggle for each, pressed where the viewer reacted. */+export function ReactionSummary({+ canReact,+ comment,+ isBusy,+ onReact,+}: {+ canReact: boolean;+ comment: AnyComment;+ isBusy: boolean;+ onReact: (comment: AnyComment, key: string) => void;+}) {+ const t = useTranslator();+ const reactions = comment.reactions ?? [];+ if (reactions.length === 0) {+ return null;+ }+ return (+ <HStack gap={1} align="center" data-comment-reactions="true">+ {reactions.map(reaction => (+ <Tooltip+ key={reaction.key}+ content={<ReactionTooltipContent reaction={reaction} />}>+ {/* A pending reaction stays enabled, so focus never drops to <body>+ mid-request; the press is refused instead. */}+ <ToggleButton+ label={t('@astryx.comments.reactionCount', {+ reaction: reactionDescription(t, reaction),+ count: reaction.count,+ })}+ size="sm"+ isPressed={reaction.reactedByViewer === true}+ isDisabled={!canReact}+ data-comment-reaction={reaction.key}+ xstyle={styles.reactionToggle}+ onPressedChange={() => {+ if (!isBusy) {+ onReact(comment, reaction.key);+ }+ }}>+ <HStack gap={1} align="center">+ <Text as="span" type="body" color="primary" weight="normal">+ {reaction.label}+ </Text>+ <Text as="span" type="body" color="primary" weight="normal">+ {reaction.count}+ </Text>+ </HStack>+ </ToggleButton>+ </Tooltip>+ ))}+ </HStack>+ );+}++function ReactionPicker({+ isBusy,+ options,+ onPick,+}: {+ isBusy: boolean;+ options: readonly CommentReactionOption[];+ onPick: (option: CommentReactionOption) => void;+}) {+ const t = useTranslator();+ return (+ <HStack gap={0.5} align="center" data-reaction-picker="true">+ {options.map(option => (+ <IconButton+ key={option.key}+ label={reactionDescription(t, option)}+ tooltip={reactionDescription(t, option)}+ variant="ghost"+ data-reaction-option={option.key}+ icon={+ <Text as="span" type="large">+ {option.label}+ </Text>+ }+ isDisabled={isBusy}+ onClick={() => onPick(option)}+ />+ ))}+ </HStack>+ );+}++const NO_COLLAPSED_ACTIONS: ReadonlySet<CommentActionId> = new Set();++// OverflowList counts each element in its measuring row as an item, but an+// IconButton with a tooltip renders more than one there, so the row read as+// fitting and never collapsed. One HStack per action keeps the count right.+// Its `data-comment-action` names the item for changeOverflow and stays off+// the DOM, where the button itself carries it.+function CommentActionSlot({+ children,+}: {+ readonly 'data-comment-action': CommentActionId;+ readonly children: ReactNode;+}) {+ return <HStack align="center">{children}</HStack>;+}++/**+ * A comment's actions, in its header's top-end corner: Mark as resolved or+ * Reopen, Add reaction, Reply, and Copy link as icon buttons, then the more+ * menu. When the header runs out of room the buttons collapse into the more+ * menu, Copy link first, beside Edit and Delete where the viewer may use them.+ */+export function CommentActions({+ additionalActions,+ canCopyLink,+ canReact,+ canReply,+ comment,+ isBusy,+ menuItems,+ menuLabel,+ onOpenChange,+ onReact,+ onReply,+ options,+ resolveAction,+}: {+ additionalActions?: ReactNode;+ canCopyLink: boolean;+ canReact: boolean;+ canReply: boolean;+ comment: AnyComment;+ isBusy: boolean;+ /** Edit and Delete, where the viewer may use them. */+ menuItems: readonly DropdownMenuOption[];+ menuLabel: string;+ /** Pins the revealed actions while the picker or the menu is open. */+ onOpenChange: (isOpen: boolean) => void;+ onReact: (+ comment: AnyComment,+ key: string,+ option?: CommentReactionOption,+ ) => void;+ onReply: () => void;+ options: readonly CommentReactionOption[];+ resolveAction?: ResolveAction;+}) {+ const t = useTranslator();+ const [isLinkCopied, setIsLinkCopied] = useState(false);+ const [isLinkTooltipOpen, setIsLinkTooltipOpen] = useState(false);+ const [isPickerOpen, setIsPickerOpen] = useState(false);+ const [collapsed, setCollapsed] = useState(NO_COLLAPSED_ACTIONS);+ const clusterRef = useRef<HTMLElement | null>(null);+ const href = `#${commentAnchorId(comment.id)}`;+ const linkLabel = isLinkCopied+ ? t('@astryx.comments.linkCopied')+ : t('@astryx.comments.copyLink');+ const resolveLabel = t('@astryx.comments.resolve');+ const reopenLabel = t('@astryx.comments.reopen');+ const replyLabel = t('@astryx.comments.reply');+ const addReactionLabel = t('@astryx.comments.addReaction');+ // A check mark says the copy worked until the label resets.+ const linkIcon = isLinkCopied ? (+ <Icon icon="check" color="secondary" />+ ) : (+ <CommentIcon name="copyLink" />+ );++ const copyCommentLink = async () => {+ if (navigator.clipboard == null) {+ return;+ }+ try {+ await navigator.clipboard.writeText(+ new URL(href, window.location.href).href,+ );+ setIsLinkCopied(true);+ } catch {+ setIsLinkCopied(false);+ }+ };++ useEffect(() => {+ if (!isLinkCopied) {+ return;+ }+ const timer = window.setTimeout(+ () => setIsLinkCopied(false),+ LINK_COPIED_RESET_MS,+ );+ return () => window.clearTimeout(timer);+ }, [isLinkCopied]);++ const changePicker = (isOpen: boolean) => {+ setIsPickerOpen(isOpen);+ onOpenChange(isOpen);+ };+ const pickReaction = (option: CommentReactionOption) => {+ onReact(comment, option.key, option);+ // Closing the picker remounts Add reaction because its tooltip becomes+ // available again. Commit that handler-owned state before restoring focus+ // to the replacement control (architecture:react-component-runtime/INV2).+ flushSync(() => changePicker(false));+ const root = clusterRef.current;+ (+ visibleCommentAction(root, 'react') ?? commentMoreMenuTrigger(root)+ )?.focus();+ };+ const changeOverflow = useCallback((items: OverflowItem[]) => {+ setCollapsed(+ new Set(+ items.flatMap(item => {+ const action = (+ item.child.props as {'data-comment-action'?: CommentActionId}+ )['data-comment-action'];+ return action == null ? [] : [action];+ }),+ ),+ );+ }, []);++ const collapsedItems: DropdownMenuOption[] = [];+ if (resolveAction != null && collapsed.has(resolveAction.kind)) {+ collapsedItems.push({+ id: resolveAction.kind,+ label: resolveAction.kind === 'resolve' ? resolveLabel : reopenLabel,+ icon:+ resolveAction.kind === 'resolve' ? (+ <CommentIcon name="resolve" />+ ) : undefined,+ isDisabled: isBusy,+ onClick: resolveAction.onClick,+ });+ }+ if (canReply && collapsed.has('reply')) {+ collapsedItems.push({+ id: 'reply',+ label: replyLabel,+ icon: <CommentIcon name="reply" />,+ isDisabled: isBusy,+ onClick: onReply,+ });+ }+ // A comment that already has a more menu keeps Copy link in it; elsewhere+ // Copy link is a header button until the header runs out of room.+ const isLinkInMenu = menuItems.length > 0;+ const copyLinkItem: DropdownMenuOption = {+ id: 'copy-link',+ label: linkLabel,+ icon: linkIcon,+ onClick: () => void copyCommentLink(),+ };+ if (canCopyLink && !isLinkInMenu && collapsed.has('link')) {+ collapsedItems.push(copyLinkItem);+ }+ if (canReact && collapsed.has('react')) {+ collapsedItems.push({+ type: 'section',+ id: 'react',+ title: addReactionLabel,+ items: options.map(option => ({+ id: `react-${option.key}`,+ label: reactionDescription(t, option),+ icon: (+ <Text as="span" type="body">+ {option.label}+ </Text>+ ),+ isDisabled: isBusy,+ onClick: () => onReact(comment, option.key, option),+ })),+ });+ }+ const ownItems: DropdownMenuOption[] = [+ ...(canCopyLink && isLinkInMenu ? [copyLinkItem] : []),+ ...menuItems,+ ];+ const items: DropdownMenuOption[] = [+ ...collapsedItems,+ ...(collapsedItems.length > 0 && ownItems.length > 0+ ? [{type: 'divider' as const}]+ : []),+ ...ownItems,+ ];++ const renderCluster = (anchorRef?: (element: HTMLElement | null) => void) => (+ <HStack+ ref={(element: HTMLElement | null) => {+ clusterRef.current = element;+ anchorRef?.(element);+ }}+ gap={0.5}+ align="center"+ width="100%"+ data-comment-actions="header">+ <OverflowList+ gap={0.5}+ collapseFrom="end"+ onOverflowChange={changeOverflow}+ xstyle={styles.actionsList}+ data-comment-actions-list="true">+ {/* First, so it is the last to collapse. */}+ {resolveAction?.kind === 'resolve' ? (+ <CommentActionSlot key="resolve" data-comment-action="resolve">+ <IconButton+ label={resolveLabel}+ tooltip={resolveLabel}+ variant="ghost"+ size="sm"+ data-comment-action="resolve"+ icon={<CommentIcon name="resolve" />}+ isDisabled={isBusy}+ onClick={resolveAction.onClick}+ />+ </CommentActionSlot>+ ) : resolveAction?.kind === 'reopen' ? (+ <CommentActionSlot key="reopen" data-comment-action="reopen">+ <Button+ label={reopenLabel}+ variant="ghost"+ size="sm"+ data-comment-action="reopen"+ isDisabled={isBusy}+ onClick={resolveAction.onClick}+ />+ </CommentActionSlot>+ ) : null}+ {canReact ? (+ <CommentActionSlot key="react" data-comment-action="react">+ <IconButton+ label={addReactionLabel}+ // The Popover returns focus to this button while it hides, and+ // a tooltip shown then collides with it, so the tooltip rests+ // while the picker is open.+ tooltip={isPickerOpen ? undefined : addReactionLabel}+ variant="ghost"+ size="sm"+ data-comment-action="react"+ aria-haspopup="dialog"+ aria-expanded={isPickerOpen}+ icon={<CommentIcon name="addReaction" />}+ isDisabled={isBusy}+ onClick={() => changePicker(!isPickerOpen)}+ />+ </CommentActionSlot>+ ) : null}+ {canReply ? (+ <CommentActionSlot key="reply" data-comment-action="reply">+ <IconButton+ label={replyLabel}+ tooltip={replyLabel}+ variant="ghost"+ size="sm"+ data-comment-action="reply"+ icon={<CommentIcon name="reply" />}+ isDisabled={isBusy}+ onClick={onReply}+ />+ </CommentActionSlot>+ ) : null}+ {canCopyLink && !isLinkInMenu ? (+ <CommentActionSlot key="link" data-comment-action="link">+ <Tooltip+ content={linkLabel}+ // A press hides a hover tooltip; this one stays open while the+ // link reads as copied, so the press visibly worked.+ isOpen={isLinkCopied || isLinkTooltipOpen}+ onOpenChange={setIsLinkTooltipOpen}>+ <IconButton+ label={linkLabel}+ variant="ghost"+ size="sm"+ data-comment-action="link"+ data-link-copied={isLinkCopied ? 'true' : undefined}+ icon={linkIcon}+ onClick={() => void copyCommentLink()}+ />+ </Tooltip>+ </CommentActionSlot>+ ) : null}+ </OverflowList>+ {additionalActions}+ {items.length > 0 && (+ <HStack data-comment-more-menu="true">+ <DropdownMenu+ items={items}+ menuWidth={MORE_MENU_MIN_WIDTH}+ alignment="end"+ presentation="adaptive"+ hasChevron={false}+ button={{+ label: menuLabel,+ variant: 'ghost',+ size: 'sm',+ isIconOnly: true,+ icon: <Icon icon="moreHorizontal" color="secondary" />,+ isDisabled: isBusy,+ tooltip: menuLabel,+ }}+ onOpenChange={onOpenChange}+ />+ </HStack>+ )}+ </HStack>+ );+ if (!canReact) {+ return renderCluster();+ }+ return (+ <Popover+ isOpen={isPickerOpen}+ onOpenChange={changePicker}+ placement="above"+ alignment="end"+ label={t('@astryx.comments.chooseReaction')}+ // Hugs its emoji: without a width the Popover is as wide as its trigger,+ // which here is the header's whole action cluster.+ width="fit-content"+ // Only while open: a closed picker leaves no buttons in the page.+ content={+ isPickerOpen ? (+ <ReactionPicker+ isBusy={isBusy}+ options={options}+ onPick={pickReaction}+ />+ ) : null+ }>+ {triggerProps => renderCluster(triggerProps.ref)}+ </Popover>+ );+}diff --git a/packages/lab/src/Comments/CommentParts.tsx b/packages/lab/src/Comments/CommentParts.tsxindex 0dd0c5ffc4..dc33c4032b 100644--- a/packages/lab/src/Comments/CommentParts.tsx+++ b/packages/lab/src/Comments/CommentParts.tsx@@ -4,28 +4,236 @@/*** @file CommentParts.tsx- * @input Uses React, StyleX, theme colors, Banner, Blockquote, Button, Link, Text- * @output Exports the small presentational parts owned by CommentComposer- * @position Internal building blocks for the Lab CommentComposer; later- * Comments-family components extend this module+ * @input Uses React, StyleX, theme tokens, and Astryx primitives (Avatar,+ * Badge, Banner, Blockquote, Button, Card, Dialog, EmptyState, Item, Link,+ * Section, Skeleton, Spinner, Text, Thumbnail, Timestamp, Tooltip)+ * @output Exports the presentational parts of a comment row: author name and+ * avatar, metadata, quoted passages, progress, clamped body, error banner,+ * reply rail, activity event row, edit history dialog, and loading skeletons+ * @position Internal building blocks of the Comments family*/-import type {Ref} from 'react';+import {useState, type CSSProperties, type ReactNode, type Ref} from 'react';import * as stylex from '@stylexjs/stylex';+import {Avatar} from '@astryxdesign/core/Avatar';+import {Badge} from '@astryxdesign/core/Badge';import {Banner} from '@astryxdesign/core/Banner';import {Blockquote} from '@astryxdesign/core/Blockquote';import {Button} from '@astryxdesign/core/Button';+import {Center} from '@astryxdesign/core/Center';+import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';+import {EmptyState} from '@astryxdesign/core/EmptyState';+import {+ HStack,+ Layout,+ LayoutContent,+ StackItem,+ VStack,+} from '@astryxdesign/core/Layout';import {Link} from '@astryxdesign/core/Link';+import {Section} from '@astryxdesign/core/Section';+import {Spinner} from '@astryxdesign/core/Spinner';import {Text} from '@astryxdesign/core/Text';-import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';-import type {CommentHighlightColor} from './types';+import {Thumbnail} from '@astryxdesign/core/Thumbnail';+import {Timestamp} from '@astryxdesign/core/Timestamp';+import {Tooltip} from '@astryxdesign/core/Tooltip';+import {useTranslator} from '@astryxdesign/core/i18n';+import {+ borderVars,+ colorVars,+ durationVars,+ easeVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import type {AnyComment} from './utils';+import type {+ CommentAnchor,+ CommentHighlightColor,+ CommentProgress,+ CommentUser,+ CommentVersion,+} from './types';++/** The 28px avatar column every comment row, reply, and event aligns to. */+export const AVATAR_SIZE = `calc(${spacingVars['--spacing-6']} + ${spacingVars['--spacing-1']})`;+// The gap between thread rows; a rail stretch reaches across it.+const THREAD_ROW_GAP = spacingVars['--spacing-2'];+// The rail stops this far short of every avatar it meets, so it reads as+// segments between the avatars rather than one line behind them.+const THREAD_RAIL_AVATAR_GAP = spacingVars['--spacing-1'];+const THREAD_RAIL_BELOW_AVATAR = `calc(${AVATAR_SIZE} + ${THREAD_RAIL_AVATAR_GAP})`;+const RAIL_INLINE_START = `calc(${spacingVars['--spacing-3']} + ${borderVars['--border-width']})`;++// Holds for five seconds, then fades over the slow motion token. The badge+// removes itself when the animation ends so header actions reclaim the trailing+// edge; `visibility: hidden` keeps it out of the accessibility tree meanwhile.+const unreadBadgeFade = stylex.keyframes({+ from: {opacity: 1, visibility: 'visible'},+ to: {opacity: 0, visibility: 'hidden'},+});++// Slides a gradient twice the label's width so its light band crosses the+// label left to right.+const progressShimmer = stylex.keyframes({+ from: {backgroundPosition: '100% 0'},+ to: {backgroundPosition: '0 0'},+});++/**+ * A resolved thread's words step down to the secondary text color by+ * remapping the primary text token on their own elements (never on the+ * actions, which stay usable). Secondary text keeps a readable contrast, which+ * the disabled color does not: a resolved comment is still content, not an+ * inactive control. Markdown takes no text color of its own, and `xstyle`+ * takes no custom properties, so the remap is an inline style.+ */+export const RESOLVED_TEXT_STYLE: CSSProperties &+ Record<`--${string}`, string> = {+ '--color-text-primary': colorVars['--color-text-secondary'],+};export const partStyles = stylex.create({- noWrap: {whiteSpace: 'nowrap'},- quoteText: {fontStyle: 'italic'},- fullWidth: {width: '100%'},+ avatarFrame: {+ position: 'relative',+ zIndex: 1,+ overflow: 'hidden',+ width: AVATAR_SIZE,+ minWidth: AVATAR_SIZE,+ height: AVATAR_SIZE,+ // Avatars sit on an opaque card-surface disc in every state, including a+ // selected thread's translucent fill, so nothing shows through them.+ backgroundColor: colorVars['--color-background-card'],+ },+ avatarFramePerson: {+ borderRadius: radiusVars['--radius-full'],+ },+ avatarFrameAgent: {+ borderRadius: radiusVars['--radius-element'],+ },+ avatarSpacer: {+ width: AVATAR_SIZE,+ minWidth: AVATAR_SIZE,+ },+ agentLogo: {+ width: AVATAR_SIZE,+ minWidth: AVATAR_SIZE,+ height: AVATAR_SIZE,+ },+ noWrap: {+ whiteSpace: 'nowrap',+ },+ bodyClamped: {+ display: '-webkit-box',+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 3,+ overflow: 'hidden',+ },+ unreadBadge: {+ animationName: unreadBadgeFade,+ animationDelay: '5s',+ animationDuration: {+ default: durationVars['--duration-slow-max'],+ '@media (prefers-reduced-motion: reduce)': '1ms',+ },+ animationTimingFunction: easeVars['--ease-standard'],+ animationFillMode: 'forwards',+ },+ quoteText: {+ fontStyle: 'italic',+ },+ // Doubles the comment column's gap around the quote so it reads as its own+ // block between the author line and the body.+ threadQuote: {+ paddingBlock: spacingVars['--spacing-1'],+ },+ // The text is painted by its background, clipped to the glyphs, so it never+ // drops below secondary-text contrast. Where the clip is unsupported, under+ // reduced motion, and in forced colors, the label is plain secondary text.+ progressLabel: {+ color: {+ default: colorVars['--color-text-secondary'],+ '@supports (background-clip: text)': 'transparent',+ '@media (prefers-reduced-motion: reduce)':+ colorVars['--color-text-secondary'],+ '@media (forced-colors: active)': 'CanvasText',+ },+ backgroundImage: {+ default: 'none',+ '@supports (background-clip: text)': `linear-gradient(90deg, ${colorVars['--color-text-secondary']} 40%, ${colorVars['--color-text-primary']} 50%, ${colorVars['--color-text-secondary']} 60%)`,+ '@media (prefers-reduced-motion: reduce)': 'none',+ '@media (forced-colors: active)': 'none',+ },+ backgroundSize: '250% 100%',+ backgroundClip: 'text',+ animationName: {+ default: 'none',+ '@supports (background-clip: text)': progressShimmer,+ '@media (prefers-reduced-motion: reduce)': 'none',+ '@media (forced-colors: active)': 'none',+ },+ animationDuration: `calc(${durationVars['--duration-slow-max']} * 2)`,+ animationTimingFunction: 'linear',+ animationIterationCount: 'infinite',+ },+ railRow: {+ position: 'relative',+ },+ rail: {+ position: 'absolute',+ insetInlineStart: RAIL_INLINE_START,+ width: spacingVars['--spacing-0-5'],+ backgroundColor: colorVars['--color-border-emphasized'],+ pointerEvents: 'none',+ },+ // Where a stretch starts: below its row's avatar, or at the top of a row+ // without one; and where it ends: short of the next row's avatar, or at the+ // top of a next row without one, which carries the rail on.+ railFromAvatar: {+ insetBlockStart: THREAD_RAIL_BELOW_AVATAR,+ },+ railFromRow: {+ insetBlockStart: 0,+ },+ railToAvatar: {+ insetBlockEnd: `calc(${THREAD_RAIL_AVATAR_GAP} - ${THREAD_ROW_GAP})`,+ },+ railToRow: {+ insetBlockEnd: `calc(-1 * ${THREAD_ROW_GAP})`,+ },+ // A collapsed thread's rail fades out over the whole comment, down to its+ // View replies link, so the hidden replies read as part of it.+ railCollapsed: {+ position: 'absolute',+ insetBlockStart: THREAD_RAIL_BELOW_AVATAR,+ insetBlockEnd: 0,+ insetInlineStart: RAIL_INLINE_START,+ width: spacingVars['--spacing-0-5'],+ backgroundImage: `linear-gradient(to bottom, ${colorVars['--color-border-emphasized']}, transparent)`,+ pointerEvents: 'none',+ zIndex: -1,+ },+ eventRow: {+ paddingInlineStart: spacingVars['--spacing-3'],+ },+ loadingComposer: {+ borderRadius: radiusVars['--radius-container'],+ },+ fullWidth: {+ width: '100%',+ },+ // Neighboring Sections each draw a top and a bottom divider. Overlapping+ // them by one border width leaves a single 1px line between threads.+ sectionDividerOverlap: {+ marginBlockStart: {+ default: `calc(-1 * ${borderVars['--border-width']})`,+ ':first-child': '0',+ },+ },});+/* A highlighted passage's quote rule, in the border token of the host's+ highlight color. */const highlightRules = stylex.create({blue: {borderInlineStartColor: colorVars['--color-border-blue']},cyan: {borderInlineStartColor: colorVars['--color-border-cyan']},@@ -48,7 +256,10 @@ export type ErrorBannerContent = {isActionDisabled?: boolean;};-/** An inline failure announced when its error Banner mounts. */+/**+ * An inline failure as an error Banner. It sets role="alert" itself (Banner+ * adds no live-region role from `status`), so mounting it announces it.+ */export function ErrorBanner({actionRef,content,@@ -57,6 +268,7 @@ export function ErrorBanner({}: {actionRef?: Ref<HTMLButtonElement>;content: ErrorBannerContent;+ /** Runs before the action, e.g. to move focus off a Banner about to unmount. */onBeforeAction?: () => void;[dataAttribute: `data-${string}`]: string | undefined;}) {@@ -89,6 +301,45 @@ export function ErrorBanner({);}+/**+ * One stretch of the 2px reply rail. Each row draws its own stretch down across+ * the row gap, from just below its avatar or through the whole row, to just+ * short of the next row's avatar or into a next row that carries it on. The+ * rail never runs behind an avatar, and ends at the last one.+ */+export function ThreadRailSegment({+ from,+ to,+}: {+ from: 'avatar' | 'row';+ to: 'avatar' | 'row';+}) {+ return (+ <VStack+ xstyle={[+ partStyles.rail,+ from === 'avatar' ? partStyles.railFromAvatar : partStyles.railFromRow,+ to === 'avatar' ? partStyles.railToAvatar : partStyles.railToRow,+ ]}+ data-thread-rail-segment={`${from}-${to}`}+ aria-hidden="true">+ {null}+ </VStack>+ );+}++/** The fading rail of a collapsed thread with hidden replies. */+export function CollapsedThreadRail() {+ return (+ <VStack+ xstyle={partStyles.railCollapsed}+ data-thread-rail-segment="collapsed"+ aria-hidden="true">+ {null}+ </VStack>+ );+}+export function MetadataSeparator({type = 'body',}: {@@ -101,7 +352,7 @@ export function MetadataSeparator({);}-/** A secondary text link that performs a compact composer action. */+/** A secondary text link that runs an action, such as Edited or Cancel. */export function MetadataActionLink({accessibleLabel,actionRole,@@ -111,6 +362,7 @@ export function MetadataActionLink({textType = 'supporting',}: {accessibleLabel?: string;+ /** Names the link for focus hand-off, e.g. back to Edited after history. */actionRole?: 'history';isDisabled?: boolean;label: string;@@ -137,12 +389,16 @@ export function MetadataActionLink({);}-/** A quoted passage in Markdown's blockquote style, clamped to two lines. */+/**+ * A quoted passage in Markdown's blockquote style: italic, two lines at most.+ * A passage the host highlights carries the highlight's color on its rule.+ */export function QuotedPassage({quote,highlightColor,}: {quote: string;+ /** The highlight's color, or nothing for a neutral rule. */highlightColor?: CommentHighlightColor;}) {return (@@ -162,3 +418,306 @@ export function QuotedPassage({</Blockquote>);}++/** The passage an inline comment discusses, quoted under its author's name. */+export function CommentAnchorQuote({+ anchor,+ highlightColor,+ isResolved,+}: {+ anchor: CommentAnchor;+ highlightColor: CommentHighlightColor;+ /** A resolved thread's passage leaves the host's highlights. */+ isResolved: boolean;+}) {+ const t = useTranslator();+ const isOrphaned = anchor.status === 'orphaned';+ return (+ <HStack+ gap={2}+ align="center"+ width="100%"+ xstyle={partStyles.threadQuote}+ style={isResolved ? RESOLVED_TEXT_STYLE : undefined}+ data-comment-anchor={isOrphaned ? 'orphaned' : 'anchored'}>+ <StackItem size={isOrphaned ? undefined : 'fill'}>+ <QuotedPassage+ quote={anchor.quote}+ highlightColor={+ !isOrphaned && !isResolved ? highlightColor : undefined+ }+ />+ </StackItem>+ {/* The passage was edited away; the quote is what the comment saw. */}+ {isOrphaned && (+ <StackItem size="static">+ <Badge variant="neutral" label={t('@astryx.comments.outdated')} />+ </StackItem>+ )}+ </HStack>+ );+}++/** A comment its author is still writing: what it is doing, and where to watch. */+export function CommentProgressStatus({progress}: {progress: CommentProgress}) {+ return (+ <HStack+ gap={1}+ align="center"+ wrap="wrap"+ width="100%"+ data-comment-progress="shimmer">+ <Text+ type="body"+ color="secondary"+ role="status"+ xstyle={partStyles.progressLabel}>+ {progress.label}+ </Text>+ {progress.link != null && (+ <Link href={progress.link.href} target="_blank" type="body">+ {progress.link.label}+ </Link>+ )}+ </HStack>+ );+}++/** A comment body, clamped to three lines until its thread opens. */+export function ClampedBody({+ children,+ isExpanded,+ isMuted,+}: {+ children: ReactNode;+ isExpanded: boolean;+ isMuted: boolean;+}) {+ return (+ <VStack+ width="100%"+ xstyle={isExpanded ? undefined : partStyles.bodyClamped}+ style={isMuted ? RESOLVED_TEXT_STYLE : undefined}+ data-comment-body-clamp={isExpanded ? 'expanded' : '3'}>+ {children}+ </VStack>+ );+}++export function UnreadBadge() {+ const t = useTranslator();+ const [hasFaded, setHasFaded] = useState(false);+ if (hasFaded) {+ return null;+ }+ return (+ <HStack+ align="center"+ xstyle={partStyles.unreadBadge}+ data-comment-unread-badge="true"+ onAnimationEnd={event => {+ if (event.target === event.currentTarget) {+ setHasFaded(true);+ }+ }}>+ <Badge variant="info" label={t('@astryx.comments.unread')} />+ </HStack>+ );+}++/** Resolved, beside the time; names who resolved it when the host knows. */+export function ResolvedLabel({resolvedBy}: {resolvedBy?: CommentUser}) {+ const t = useTranslator();+ const label = (+ <Text+ type="body"+ color="secondary"+ xstyle={partStyles.noWrap}+ data-comment-resolved-label="true">+ {t('@astryx.comments.resolved')}+ </Text>+ );+ return resolvedBy == null ? (+ label+ ) : (+ <Tooltip+ content={t('@astryx.comments.resolvedBy', {name: resolvedBy.name})}>+ {label}+ </Tooltip>+ );+}++export function AuthorName({+ author,+ id,+ xstyle,+}: {+ author: CommentUser;+ id?: string;+ xstyle?: stylex.StyleXStyles;+}) {+ return (+ <Text+ id={id}+ type="label"+ color="primary"+ weight="medium"+ maxLines={1}+ xstyle={xstyle}+ data-author-name={author.name}>+ {author.href != null ? (+ <Link href={author.href} type="inherit" color="inherit">+ {author.name}+ </Link>+ ) : (+ author.name+ )}+ </Text>+ );+}++function CommentAvatar({user}: {user: CommentUser}) {+ const t = useTranslator();+ const logo = user.avatarUrl?.trim();+ if (user.kind === 'agent' && logo != null && logo !== '') {+ return (+ <Thumbnail+ src={logo}+ alt={t('@astryx.comments.agentLogo', {name: user.name})}+ xstyle={partStyles.agentLogo}+ />+ );+ }+ return (+ <Avatar+ name={user.name}+ src={logo === '' ? undefined : logo}+ size={32}+ xstyle={partStyles.agentLogo}+ // An agent without a logo keeps the agent's square-cornered frame.+ shape={user.kind === 'agent' ? 'rounded' : 'circle'}+ tooltip={false}+ />+ );+}++/** A 28×28 avatar on an opaque disc: a circle for people, a rounded square+ * for agents. */+export function CommentAvatarFrame({user}: {user: CommentUser}) {+ const isAgent = user.kind === 'agent';+ return (+ <Center+ xstyle={[+ partStyles.avatarFrame,+ isAgent ? partStyles.avatarFrameAgent : partStyles.avatarFramePerson,+ ]}+ data-avatar-shape={isAgent ? 'agent' : 'person'}>+ <CommentAvatar user={user} />+ </Center>+ );+}++/** The empty 28px avatar column, for rows without an avatar. */+export function AvatarSpacer() {+ return (+ <Center xstyle={partStyles.avatarSpacer} aria-hidden="true">+ {null}+ </Center>+ );+}++export type HistoryState = {+ comment: AnyComment;+ versions: readonly CommentVersion[];+ isLoading: boolean;+ error?: string;+};++export function HistoryDialog({+ history,+ onClose,+ renderVersionBody,+}: {+ history: HistoryState | null;+ onClose: () => void;+ renderVersionBody: (version: CommentVersion) => ReactNode;+}) {+ const t = useTranslator();+ if (history == null) {+ return null;+ }+ return (+ <Dialog isOpen onOpenChange={open => !open && onClose()} purpose="info">+ <Layout+ height="auto"+ header={+ <DialogHeader+ title={t('@astryx.comments.historyTitle')}+ subtitle={t('@astryx.comments.historySubtitle', {+ name: history.comment.author.name,+ })}+ onOpenChange={open => !open && onClose()}+ hasDivider+ />+ }+ content={+ <LayoutContent>+ {history.isLoading ? (+ <Spinner+ size="lg"+ label={t('@astryx.comments.historyLoading')}+ />+ ) : history.error != null ? (+ <Banner+ status="error"+ role="alert"+ title={t('@astryx.comments.historyFailed')}+ description={history.error}+ container="section"+ />+ ) : history.versions.length === 0 ? (+ <EmptyState+ title={t('@astryx.comments.historyEmptyTitle')}+ description={t('@astryx.comments.historyEmptyDescription')}+ isCompact+ />+ ) : (+ <VStack gap={3}>+ {history.versions.map(version => (+ <Section+ key={version.id}+ variant={+ version.isCurrent === true ? 'muted' : 'transparent'+ }+ padding={2}>+ <VStack gap={1.5}>+ <HStack gap={1} align="center" wrap="wrap">+ <Timestamp+ value={version.editedAt}+ format="date_time"+ />+ {version.author != null && (+ <Text type="supporting" color="secondary">+ {t('@astryx.comments.versionAuthor', {+ name: version.author.name,+ })}+ </Text>+ )}+ {version.isCurrent === true && (+ <Text type="supporting" weight="semibold">+ {t('@astryx.comments.currentVersion')}+ </Text>+ )}+ </HStack>+ {renderVersionBody(version)}+ </VStack>+ </Section>+ ))}+ </VStack>+ )}+ </LayoutContent>+ }+ />+ </Dialog>+ );+}diff --git a/packages/lab/src/Comments/CommentRow.tsx b/packages/lab/src/Comments/CommentRow.tsxnew file mode 100644index 0000000000..648e7b0c4d--- /dev/null+++ b/packages/lab/src/Comments/CommentRow.tsx@@ -0,0 +1,918 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CommentRow.tsx+ * @input Uses React, StyleX, Astryx Card/Section/Link/Timestamp/Badge,+ * useContainerReveal, useClickableContainer, ChatMessageMetadata,+ * ChatTypingIndicator, and the Comments family's context and parts+ * @output Exports CommentRow: a thread (its first comment, render-derived open+ * replies, typing state, hidden seen metadata, and reply composer, on a+ * selectable Card or Section) at depth 0, or a reply at depth 1+ * @position Internal row renderer shared by Comments and CommentThread+ */++import {+ useCallback,+ useRef,+ useState,+ type CSSProperties,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Badge} from '@astryxdesign/core/Badge';+import {Card} from '@astryxdesign/core/Card';+import {ChatMessageMetadata} from '@astryxdesign/core/Chat';+import type {DropdownMenuOption} from '@astryxdesign/core/DropdownMenu';+import {+ useClickableContainer,+ useContainerReveal,+} from '@astryxdesign/core/hooks';+import {HStack, StackItem, VStack} from '@astryxdesign/core/Layout';+import {Link} from '@astryxdesign/core/Link';+import {Section} from '@astryxdesign/core/Section';+import {Text} from '@astryxdesign/core/Text';+import {Timestamp} from '@astryxdesign/core/Timestamp';+import {useTranslator} from '@astryxdesign/core/i18n';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';+import {+ borderVars,+ colorVars,+ focusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';+import {+ CommentActions,+ ReactionSummary,+ type ResolveAction,+} from './CommentActions';+import {CommentComposerBase} from './CommentComposer';+import {CommentMarkdown} from './CommentMarkdown';+import {ChatTypingIndicator} from '../Chat/ChatTypingIndicator';+import {+ AuthorName,+ AvatarSpacer,+ ClampedBody,+ CollapsedThreadRail,+ CommentAnchorQuote,+ CommentAvatarFrame,+ CommentProgressStatus,+ ErrorBanner,+ MetadataActionLink,+ MetadataSeparator,+ RESOLVED_TEXT_STYLE,+ ResolvedLabel,+ ThreadRailSegment,+ UnreadBadge,+ partStyles,+} from './CommentParts';+import {useCommentsContext} from './CommentsContext';+import {CommentIcon} from './icons';+import {+ activationSourceOf,+ commentAnchorId,+ replyComposerId,+ type ActivationSource,+ type AnyComment,+} from './utils';+import type {+ CommentComposerContext,+ CommentThreadData,+ CommentUser,+} from './types';++export type ThreadDivider = 'top' | 'bottom';++/** The 28px avatar column (StyleX resolves only same-file constants). */+const AVATAR_SIZE = `calc(${spacingVars['--spacing-6']} + ${spacingVars['--spacing-1']})`;+const TYPING_INDICATOR_STYLE: CSSProperties &+ Record<'--astryx-chat-typing-indicator-dots-column-width', string> = {+ '--astryx-chat-typing-indicator-dots-column-width': AVATAR_SIZE,+};+export const THREAD_DIVIDERS: readonly ThreadDivider[] = ['top', 'bottom'];++const styles = stylex.create({+ threadRows: {+ position: 'relative',+ isolation: 'isolate',+ },+ // The header row is exactly one avatar tall, so revealing its icon buttons+ // on hover never changes the comment's height.+ header: {+ height: AVATAR_SIZE,+ minHeight: AVATAR_SIZE,+ },+ // The header's actions take whatever room the name and time leave.+ metadata: {+ flexGrow: 0,+ flexShrink: 1,+ flexBasis: 'auto',+ minWidth: 0,+ },+ // Leaves the more menu its button however long the name.+ metadataBesideActions: {+ maxWidth: `calc(100% - ${spacingVars['--spacing-6']} - ${spacingVars['--spacing-1']})`,+ },+ // The name gives way when the header is short, so the time, an agent's+ // badge and the actions keep their room.+ authorName: {+ flexShrink: 1,+ minWidth: 0,+ },+ agentBadge: {+ flexShrink: 0,+ },+ actionsReveal: {+ flexGrow: 1,+ flexShrink: 1,+ flexBasis: 0,+ minWidth: 0,+ },+ typingIndicator: {+ width: '100%',+ },+ // Row controls carry one spacing step of inline padding. Pulling the row+ // back by that step puts their glyphs on the body text line, so only their+ // hover and pressed fills cross it.+ controlRowBleed: {+ marginInlineStart: `calc(-1 * ${spacingVars['--spacing-2']})`,+ },+ surface: {+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+ // The hidden toggle that names the thread has focus: the surface takes the+ // system focus ring.+ surfaceFocused: {+ outlineStyle: focusVars['--focus-outline-style'],+ outlineWidth: focusVars['--focus-outline-width'],+ outlineColor: focusVars['--focus-outline-color'],+ outlineOffset: focusVars['--focus-outline-offset'],+ },+ // Only Card's default variant draws a border, so a selected Card keeps that+ // variant and takes the muted fill rather than switching variants.+ selectedCardFill: {+ backgroundColor: colorVars['--color-background-muted'],+ },+ // Forced colors replace the muted fill with the system background, so a+ // selected thread keeps a visible outline there.+ selectedForcedColors: {+ outlineStyle: {default: null, '@media (forced-colors: active)': 'solid'},+ outlineWidth: {+ default: null,+ '@media (forced-colors: active)': `calc(${borderVars['--border-width']} * 2)`,+ },+ outlineColor: {+ default: null,+ '@media (forced-colors: active)': 'Highlight',+ },+ outlineOffset: {+ default: null,+ '@media (forced-colors: active)': `calc(${borderVars['--border-width']} * -2)`,+ },+ },+});++// The header actions reveal instantly, with no fade or dwell.+const INSTANT_REVEAL_STYLE = {transition: 'none'} as const;++/**+ * A thread surface (a basic Card or Section) made selectable with+ * `useClickableContainer`: surface clicks toggle selection while inner+ * controls keep their own clicks, and a visually hidden toggle button carries+ * the accessible name and pressed state. Selection paints the container's own+ * muted fill, so no selectable component is restyled.+ */+function ThreadSurface({+ children,+ dividers,+ isFilled,+ isSelectable,+ isSelected,+ label,+ onChange,+ revealProps,+ surface,+ threadId,+}: {+ children: ReactNode;+ dividers: readonly ThreadDivider[];+ /** Selected, or called out by the host. */+ isFilled: boolean;+ isSelectable: boolean;+ isSelected: boolean;+ label: string;+ onChange: (isSelected: boolean, source: ActivationSource) => void;+ revealProps: {className?: string; style?: React.CSSProperties};+ surface: 'card' | 'section';+ threadId: string;+}) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const controlRef = useRef<HTMLButtonElement | null>(null);+ const [isFocused, setIsFocused] = useState(false);+ const toggle = useCallback(+ (event?: {detail?: number}) =>+ onChange(!isSelected, activationSourceOf(event)),+ [isSelected, onChange],+ );+ const {onClick, onMouseUp} = useClickableContainer({+ containerRef,+ interactiveRef: controlRef,+ onClick: toggle,+ });+ const control = isSelectable ? (+ <VisuallyHidden>+ <button+ ref={controlRef}+ type="button"+ aria-label={label}+ aria-pressed={isSelected}+ onClick={toggle}+ onFocus={() => setIsFocused(true)}+ onBlur={() => setIsFocused(false)}+ />+ </VisuallyHidden>+ ) : null;+ const interactionProps = isSelectable ? {onClick, onMouseUp} : {};+ const sharedXstyle = [+ isSelectable && styles.surface,+ isSelectable && isFocused && styles.surfaceFocused,+ isFilled && styles.selectedForcedColors,+ ];++ if (surface === 'section') {+ return (+ <Section+ ref={containerRef}+ variant={isFilled ? 'muted' : 'transparent'}+ dividers={[...dividers]}+ padding={3}+ width="100%"+ xstyle={[partStyles.sectionDividerOverlap, ...sharedXstyle]}+ className={revealProps.className}+ style={revealProps.style}+ data-thread-id={threadId}+ data-thread-surface="section"+ data-selected={isSelected ? 'true' : 'false'}+ {...interactionProps}>+ {control}+ {children}+ </Section>+ );+ }++ return (+ <Card+ ref={containerRef}+ variant="default"+ elevation="none"+ padding={3}+ width="100%"+ xstyle={[isFilled && styles.selectedCardFill, ...sharedXstyle]}+ className={revealProps.className}+ style={revealProps.style}+ data-thread-id={threadId}+ data-thread-surface="card"+ data-selected={isSelected ? 'true' : 'false'}+ {...interactionProps}>+ {control}+ {children}+ </Card>+ );+}++function uniqueCommentUsers(users: readonly CommentUser[]): CommentUser[] {+ const ids = new Set<string>();+ return users.filter(user => {+ if (ids.has(user.id)) {+ return false;+ }+ ids.add(user.id);+ return true;+ });+}++/**+ * A comment row. At depth 0 it is the whole thread: its first comment,+ * replies behind View replies, and the reply composer, on a selectable+ * surface. At depth 1 it is one reply inside it.+ */+export function CommentRow({+ comment,+ depth,+ dividers = THREAD_DIVIDERS,+ isParentThreadActive = false,+ isParentThreadResolved = false,+ threadId,+}: {+ comment: AnyComment;+ depth: 0 | 1;+ /** A card-parent thread's rules; an embedded list drops its outer ones. */+ dividers?: readonly ThreadDivider[];+ isParentThreadActive?: boolean;+ /** A reply in a resolved thread takes the thread's muted text. */+ isParentThreadResolved?: boolean;+ /** The thread this row belongs to: its own id at depth 0. */+ threadId: string;+}) {+ const t = useTranslator();+ const scope = useCommentsContext();+ const {+ actionErrors,+ agentCommands,+ can,+ composerPlaceholder,+ composerTriggers,+ container,+ currentUser,+ editTarget,+ hasEmojiPicker,+ highlightColor,+ isComposerActionPending,+ isSubmitting,+ markdownInlinePlugins,+ markdownPlugins,+ mode,+ onUploadImages,+ pendingActionIds,+ reactionOptions,+ renderAdditionalActions,+ renderAnchor,+ renderBody,+ renderComposer,+ replyDraft,+ replyError,+ replyTarget,+ selectedThreadId,+ } = scope;+ const [isMetadataMenuOpen, setIsMetadataMenuOpen] = useState(false);+ const {getContainerProps, getContentRevealProps} = useContainerReveal();+ const articleRef = useRef<HTMLElement | null>(null);+ const thread: CommentThreadData | null =+ depth === 0 ? (comment as CommentThreadData) : null;+ const status = comment.status ?? 'sent';+ const isReady = status === 'sent';+ const isInProgress = comment.progress != null;+ const isOwn = currentUser?.id === comment.author.id;+ const canMutate = mode !== 'read-only' && isReady && !isInProgress;+ const canReply = canMutate && can.submit && (comment.canReply ?? true);+ const canReact = canMutate && can.react && (comment.canReact ?? true);+ const canEdit =+ canMutate &&+ can.saveEdit &&+ mode === 'interactive' &&+ (comment.canEdit ?? isOwn);+ const canDelete =+ status !== 'sending' &&+ !isInProgress &&+ can.delete &&+ mode === 'interactive' &&+ (comment.canDelete ?? isOwn);+ const isBusy = pendingActionIds.has(comment.id);+ const rowActionsBusy = isBusy || isSubmitting || isComposerActionPending;+ const isResolved = thread?.isResolved === true;+ const isMuted = isResolved || isParentThreadResolved;+ const resolveAction: ResolveAction | undefined =+ thread == null || thread.canResolve === false || !canMutate+ ? undefined+ : isResolved+ ? can.reopen+ ? {kind: 'reopen', onClick: () => scope.reopen(comment)}+ : undefined+ : can.resolve+ ? {kind: 'resolve', onClick: () => scope.resolve(comment)}+ : undefined;+ const hasHistory =+ comment.isEdited === true &&+ ((comment.previousVersions?.length ?? 0) > 0 || can.loadVersions);+ const actionFailure = actionErrors[comment.id];+ const actionError = actionFailure?.message;+ const editorIsOpen = editTarget?.comment.id === comment.id;+ const replies = thread?.replies ?? [];+ const typingUsers = uniqueCommentUsers(thread?.typingUsers ?? []).filter(+ user => user.id !== currentUser?.id,+ );+ const isThreadSelected = depth === 0 && selectedThreadId === comment.id;+ const hasUnreadReplies = replies.some(reply => reply.isUnread === true);+ const isUnreadReplyReveal = !isThreadSelected && hasUnreadReplies;+ // Selection is the open state. Derive reply visibility from it during render+ // instead of repairing a second expansion state in an Effect (runtime INV1).+ const areRepliesVisible = isUnreadReplyReveal || isThreadSelected;+ const visibleReplies = areRepliesVisible ? replies : [];+ const anchorId = commentAnchorId(comment.id);+ const repliesRegionId = `${anchorId}-replies`;+ const authorNameId = `${anchorId}-author`;+ // An unread reveal is content, not a selected disclosure: it neither opens a+ // composer nor presents a Hide control that cannot clear host-owned unread+ // state. Once the host clears `isUnread`, the ordinary disclosure returns.+ const showReplyDisclosure =+ replies.length > 0 && editTarget == null && !isUnreadReplyReveal;+ const isReplyDisclosureBusy = isComposerActionPending || isSubmitting;+ const replyDisclosureLabel = areRepliesVisible+ ? t('@astryx.comments.hideReplies')+ : t('@astryx.comments.viewReplies', {count: replies.length});++ const isRootReplyComposerOpen =+ replyTarget?.parentId === comment.id &&+ replyTarget.comment.id === comment.id;+ const canOpenRootReplyFromCard = canReply && !isRootReplyComposerOpen;+ const canSelectThread =+ depth === 0 &&+ editTarget == null &&+ !isComposerActionPending &&+ !isSubmitting;+ const isBodyExpanded = depth === 0 ? isThreadSelected : isParentThreadActive;+ // Opening a thread puts the viewer in its reply composer, every time; a+ // composer already open for a reply in it keeps its target and draft.+ const focusThreadReply = () => {+ if (!canReply) {+ return;+ }+ scope.startReply(+ comment.id,+ replyTarget?.parentId === comment.id ? replyTarget.comment : comment,+ {focus: true},+ );+ };+ const activateThread = (source: ActivationSource) => {+ scope.selectThread(comment.id);+ if (source === 'pointer') {+ focusThreadReply();+ } else if (canOpenRootReplyFromCard) {+ scope.startReply(comment.id, comment);+ }+ };+ const changeThreadSelection = (+ isSelected: boolean,+ source: ActivationSource = 'pointer',+ ) => {+ if (isSelected) {+ activateThread(source);+ return;+ }+ if (isThreadSelected) {+ scope.selectThread(null);+ }+ if (replyTarget?.parentId === comment.id) {+ scope.cancelReply();+ }+ };++ const menuItems: DropdownMenuOption[] = [];+ if (canEdit) {+ menuItems.push({+ id: 'edit',+ label: t('@astryx.comments.edit'),+ icon: <CommentIcon name="edit" />,+ onClick: () => scope.startEdit(comment),+ });+ }+ if (canDelete) {+ menuItems.push({+ id: 'delete',+ label: t('@astryx.comments.delete'),+ icon: <CommentIcon name="delete" />,+ onClick: () => scope.requestDelete(comment),+ });+ }++ const metadataStatus = status === 'sending' ? 'sending' : undefined;+ const hasReactions = (comment.reactions?.length ?? 0) > 0;+ const showHeaderActions =+ !editorIsOpen &&+ (isReady || menuItems.length > 0 || renderAdditionalActions != null);+ const hasControlRow = metadataStatus != null || hasReactions;++ const uploaderFor = (context: CommentComposerContext) =>+ onUploadImages == null+ ? undefined+ : (files: readonly File[]) => onUploadImages(files, context);++ // A failed comment's Banner keeps a retry failure as its description, so one+ // Banner carries the whole story.+ const footer =+ status === 'error' ? (+ <ErrorBanner+ content={{+ title: comment.errorMessage ?? t('@astryx.comments.sendFailed'),+ description: actionError,+ actionLabel: can.retry ? t('@astryx.comments.retry') : undefined,+ onAction: can.retry ? () => scope.retry(comment) : undefined,+ isActionDisabled: rowActionsBusy,+ }}+ // The Banner unmounts once the retry starts; keep focus on the comment.+ onBeforeAction={() => articleRef.current?.focus()}+ data-comment-delivery-error="banner"+ />+ ) : hasControlRow || (actionFailure != null && !editorIsOpen) ? (+ <VStack gap={1} align="start" width="100%">+ {hasControlRow && (+ <HStack+ gap={1}+ align="center"+ xstyle={isReady ? styles.controlRowBleed : undefined}>+ {metadataStatus != null && (+ <ChatMessageMetadata status={metadataStatus} />+ )}+ {hasReactions && (+ <ReactionSummary+ comment={comment}+ canReact={canReact}+ isBusy={rowActionsBusy}+ onReact={scope.react}+ />+ )}+ </HStack>+ )}+ {actionFailure != null && !editorIsOpen && (+ <ErrorBanner+ content={{+ title: actionFailure.message,+ actionLabel:+ actionFailure.retry != null+ ? t('@astryx.comments.retry')+ : undefined,+ onAction: actionFailure.retry,+ }}+ onBeforeAction={() => articleRef.current?.focus()}+ data-comment-action-error="banner"+ />+ )}+ </VStack>+ ) : null;++ const anchor = thread?.anchor;+ const defaultAnchor =+ anchor != null ? (+ <CommentAnchorQuote+ anchor={anchor}+ highlightColor={highlightColor}+ isResolved={isResolved}+ />+ ) : null;+ const rows = (+ <VStack gap={8} width="100%">+ <VStack+ gap={2}+ width="100%"+ xstyle={replies.length > 0 ? styles.threadRows : undefined}>+ {visibleReplies.length === 0 && replies.length > 0 && (+ <CollapsedThreadRail />+ )}+ <VStack+ as="article"+ ref={articleRef}+ id={anchorId}+ tabIndex={-1}+ aria-labelledby={authorNameId}+ width="100%"+ xstyle={visibleReplies.length > 0 ? partStyles.railRow : undefined}+ data-comment-id={comment.id}+ data-comment-depth={String(depth)}+ data-author-kind={comment.author.kind ?? 'person'}+ data-comment-resolved={isResolved ? 'true' : undefined}>+ {visibleReplies.length > 0 && (+ <ThreadRailSegment+ from="avatar"+ to={showReplyDisclosure ? 'row' : 'avatar'}+ />+ )}+ <HStack gap={2} align="start" width="100%">+ <CommentAvatarFrame user={comment.author} />+ <StackItem size="fill">+ <VStack gap={1} width="100%">+ <HStack+ gap={1}+ align="center"+ width="100%"+ xstyle={styles.header}>+ <HStack+ gap={1}+ align="center"+ xstyle={[+ styles.metadata,+ showHeaderActions && styles.metadataBesideActions,+ ]}+ style={isMuted ? RESOLVED_TEXT_STYLE : undefined}>+ <AuthorName+ author={comment.author}+ id={authorNameId}+ xstyle={styles.authorName}+ />+ {comment.author.kind === 'agent' && (+ <HStack align="center" xstyle={styles.agentBadge}>+ <Badge+ variant="neutral"+ label={t('@astryx.comments.agentBadge')}+ />+ </HStack>+ )}+ <MetadataSeparator />+ <Timestamp+ value={comment.createdAt}+ format="relative_short"+ type="body"+ color="secondary"+ isLive+ />+ {comment.isEdited === true && (+ <>+ <MetadataSeparator />+ {hasHistory ? (+ <MetadataActionLink+ label={t('@astryx.comments.edited')}+ accessibleLabel={t(+ '@astryx.comments.viewHistory',+ )}+ actionRole="history"+ textType="body"+ onClick={() => scope.openHistory(comment)}+ />+ ) : (+ <Text+ type="body"+ color="secondary"+ xstyle={partStyles.noWrap}>+ {t('@astryx.comments.edited')}+ </Text>+ )}+ </>+ )}+ {isResolved && (+ <>+ <MetadataSeparator />+ <ResolvedLabel resolvedBy={thread?.resolvedBy} />+ </>+ )}+ </HStack>+ {showHeaderActions ? (+ <RevealedActions+ revealProps={getContentRevealProps({+ isLayoutPreserved: true,+ forceVisibility: isMetadataMenuOpen+ ? 'shown'+ : undefined,+ })}>+ <CommentActions+ comment={comment}+ canReact={canReact}+ canReply={canReply}+ canCopyLink={isReady && !isInProgress}+ resolveAction={resolveAction}+ isBusy={rowActionsBusy}+ menuItems={menuItems}+ menuLabel={t('@astryx.comments.actionsLabel', {+ name: comment.author.name,+ })}+ options={reactionOptions}+ onReact={scope.react}+ onReply={() =>+ scope.startReply(threadId, comment, {+ focus: true,+ })+ }+ onOpenChange={setIsMetadataMenuOpen}+ additionalActions={renderAdditionalActions?.(comment)}+ />+ </RevealedActions>+ ) : (+ <StackItem size="fill">{null}</StackItem>+ )}+ {comment.isUnread === true && <UnreadBadge />}+ </HStack>+ {thread != null &&+ defaultAnchor != null &&+ (renderAnchor == null+ ? defaultAnchor+ : renderAnchor(thread, defaultAnchor))}+ {editorIsOpen && editTarget != null ? (+ <CommentComposerBase+ context={{kind: 'edit', commentId: comment.id}}+ value={editTarget.value}+ onChange={value => scope.changeEdit(comment, value)}+ onSubmit={value => scope.saveEdit(comment, value)}+ placeholder={t('@astryx.comments.editPlaceholder')}+ contextLabel={t('@astryx.comments.editingContext')}+ onCancel={() => scope.cancelEdit(true)}+ focusKey={`edit-${comment.id}`}+ isSubmitting={isBusy}+ error={actionError}+ onRetryError={actionFailure?.retry}+ highlightColor={highlightColor}+ triggers={composerTriggers ?? []}+ agentCommands={agentCommands}+ hasEmojiPicker={hasEmojiPicker}+ onActionPendingChange={+ scope.composerActionPendingChange+ }+ onUploadImages={uploaderFor({+ kind: 'edit',+ commentId: comment.id,+ })}+ renderComposer={renderComposer}+ />+ ) : (+ <ClampedBody isExpanded={isBodyExpanded} isMuted={isMuted}>+ {comment.progress != null ? (+ <CommentProgressStatus progress={comment.progress} />+ ) : renderBody != null ? (+ renderBody(comment)+ ) : (+ <CommentMarkdown+ body={comment.body}+ agentCommands={agentCommands}+ plugins={markdownPlugins}+ inlinePlugins={markdownInlinePlugins}+ />+ )}+ </ClampedBody>+ )}+ {footer}+ </VStack>+ </StackItem>+ </HStack>+ </VStack>++ {depth === 0 && replies.length > 0 && (+ <VStack+ id={repliesRegionId}+ gap={2}+ width="100%"+ data-unread-replies-revealed={+ isUnreadReplyReveal ? 'true' : undefined+ }>+ {showReplyDisclosure && (+ <HStack+ gap={2}+ align="center"+ width="100%"+ xstyle={+ visibleReplies.length > 0 ? partStyles.railRow : undefined+ }>+ {visibleReplies.length > 0 && (+ <ThreadRailSegment from="row" to="avatar" />+ )}+ <AvatarSpacer />+ <Link+ type="body"+ color="secondary"+ xstyle={partStyles.noWrap}+ aria-expanded={areRepliesVisible}+ aria-controls={repliesRegionId}+ aria-disabled={isReplyDisclosureBusy || undefined}+ data-reply-disclosure="true"+ onClick={event => {+ event.preventDefault();+ if (!isReplyDisclosureBusy) {+ changeThreadSelection(+ !areRepliesVisible,+ activationSourceOf(event),+ );+ }+ }}>+ {replyDisclosureLabel}+ </Link>+ </HStack>+ )}+ {visibleReplies.map((reply, index) => (+ <VStack+ key={reply.id}+ gap={2}+ width="100%"+ xstyle={+ index === visibleReplies.length - 1+ ? undefined+ : partStyles.railRow+ }>+ {index < visibleReplies.length - 1 && (+ <ThreadRailSegment from="avatar" to="avatar" />+ )}+ <CommentRow+ comment={reply}+ depth={1}+ threadId={comment.id}+ isParentThreadActive={isThreadSelected}+ isParentThreadResolved={isResolved}+ />+ </VStack>+ ))}+ </VStack>+ )}+ {depth === 0 && isThreadSelected && typingUsers.length > 0 && (+ <HStack width="100%" data-thread-typing-indicator="true">+ <ChatTypingIndicator+ names={typingUsers.map(user => user.name)}+ xstyle={styles.typingIndicator}+ style={TYPING_INDICATOR_STYLE}+ />+ </HStack>+ )}+ </VStack>++ {depth === 0 &&+ isThreadSelected &&+ replyTarget?.parentId === comment.id && (+ <HStack+ id={replyComposerId(comment.id)}+ gap={2}+ align="start"+ width="100%"+ data-reply-composer="true">+ {currentUser != null ? (+ <CommentAvatarFrame user={currentUser} />+ ) : (+ <AvatarSpacer />+ )}+ <StackItem size="fill">+ <CommentComposerBase+ context={{+ kind: 'reply',+ parentCommentId: comment.id,+ repliedToCommentId: replyTarget.comment.id,+ }}+ value={replyDraft}+ onChange={scope.changeReplyDraft}+ onSubmit={value => scope.submitReply(comment.id, value)}+ placeholder={+ composerPlaceholder ??+ t('@astryx.comments.replyPlaceholder', {+ name: replyTarget.comment.author.name,+ })+ }+ contextLabel={t('@astryx.comments.replyingContext', {+ name: replyTarget.comment.author.name,+ })}+ focusKey={+ replyTarget.focusRequestId == null+ ? undefined+ : `reply-${replyTarget.comment.id}-${replyTarget.focusRequestId}`+ }+ isSubmitting={isSubmitting}+ error={replyError}+ onRetryError={+ replyError != null+ ? () => scope.submitReply(comment.id, replyDraft)+ : undefined+ }+ highlightColor={highlightColor}+ triggers={composerTriggers ?? []}+ agentCommands={agentCommands}+ hasEmojiPicker={hasEmojiPicker}+ onActionPendingChange={scope.composerActionPendingChange}+ onUploadImages={uploaderFor({+ kind: 'reply',+ parentCommentId: comment.id,+ repliedToCommentId: replyTarget.comment.id,+ })}+ renderComposer={renderComposer}+ />+ </StackItem>+ </HStack>+ )}+ </VStack>+ );++ if (depth !== 0) {+ return rows;+ }++ return (+ <ThreadSurface+ surface={container === 'card' ? 'section' : 'card'}+ dividers={container === 'card' ? dividers : []}+ label={t('@astryx.comments.threadLabel', {name: comment.author.name})}+ isSelectable={canSelectThread}+ isSelected={isThreadSelected}+ isFilled={isThreadSelected || thread?.isHighlighted === true}+ onChange={changeThreadSelection}+ threadId={comment.id}+ // The whole surface drives the reveal, so actions stay visible while+ // the pointer is anywhere on the thread, its replies and composer too.+ revealProps={getContainerProps()}>+ {rows}+ </ThreadSurface>+ );+}++/** The header actions, revealed while the pointer or focus is on the thread. */+function RevealedActions({+ children,+ revealProps,+}: {+ children: ReactNode;+ revealProps: {className?: string; style?: React.CSSProperties};+}) {+ return (+ <HStack+ align="center"+ xstyle={styles.actionsReveal}+ className={revealProps.className}+ style={{...revealProps.style, ...INSTANT_REVEAL_STYLE}}+ data-comment-actions-reveal="hover-focus">+ {children}+ </HStack>+ );+}diff --git a/packages/lab/src/Comments/CommentThread.doc.mjs b/packages/lab/src/Comments/CommentThread.doc.mjsnew file mode 100644index 0000000000..cdf9c8520b--- /dev/null+++ b/packages/lab/src/Comments/CommentThread.doc.mjs@@ -0,0 +1,580 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// @ts-check++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */+export const docs = {+ name: 'CommentThread',+ displayName: 'Comment Thread',+ group: 'Comments',+ category: 'Chat',+ keywords: [+ 'comment',+ 'comment thread',+ 'thread',+ 'replies',+ 'margin comment',+ 'annotation',+ ],+ description:+ 'One comment thread on its own: its first comment, one level of replies, reactions, edit history, controlled typing and seen metadata, and a reply composer. For a margin comment beside a document, a popover under a highlight, or any surface that shows a single thread.',+ usage: {+ description:+ 'A comment thread shows one conversation: its first comment and the replies under it. Use it where a surface shows a single thread, such as a margin card beside a document or a popover opened from a highlight. To show many threads with a composer for new ones, use Comments.',+ anatomy: [+ {+ name: 'Surface',+ required: true,+ description:+ 'An outlined Card on a page, or a Section without outer rules inside a card or popover. A press anywhere on it opens the thread; a visually hidden toggle carries its name and focus.',+ },+ {+ name: 'Quoted passage',+ required: false,+ description:+ 'The passage an inline comment discusses, as an italic blockquote ruled in the highlight color, with an Outdated badge once the passage is edited away.',+ },+ {+ name: 'First comment',+ required: true,+ description:+ 'Avatar, header (name, time, Edited, Resolved, and the actions shown on hover or focus), Markdown body clamped to three lines until the thread opens, and reactions.',+ },+ {+ name: 'Replies',+ required: false,+ description:+ 'One level of replies behind View replies, joined to the first comment by an avatar rail while the thread is open. A host-marked unread reply reveals without selecting the thread, moving focus, or opening the reply composer.',+ },+ {+ name: 'Live state',+ required: false,+ description:+ 'Controlled typing state follows the conversation while the thread is open, with its pulsing dots in the avatar column and its label on the comment-text line. Controlled `seenBy` metadata remains available to comment render callbacks but has no default presentation.',+ },+ {+ name: 'Reply composer',+ required: false,+ description:+ 'A CommentComposer that opens with the thread, beside the viewer’s avatar.',+ },+ ],+ bestPractices: [+ {+ guidance: true,+ description:+ 'Inside a card or popover, set `container="card"` and give the card no padding: the thread supplies its own insets and draws no outer rules.',+ },+ {+ guidance: true,+ description:+ 'Control `isSelected` when the thread opens from elsewhere, such as its highlight in a document. Controlled selection reveals the body and replies without moving focus or opening the reply composer.',+ },+ {+ guidance: true,+ description:+ 'In a Popover over a document, pass `onDismiss` and pair it with `hasLightDismiss={false}` and `hasEscapeDismiss={false}` on the host Popover. A press outside the thread or Escape then closes it, except that the first one over an unsaved reply or edit shakes the thread and keeps the draft.',+ },+ {+ guidance: true,+ description:+ 'Map your collaboration state to `typingUsers` and `seenBy`, then publish local reply and edit activity with `onComposerDraftChange`. `seenBy` stays hidden unless a comment render callback presents it. The thread never opens a connection or expires participants.',+ },+ {+ guidance: false,+ description:+ 'Stack several CommentThreads with a composer to build a discussion. Use Comments, which keeps one thread open at a time and orders threads with activity.',+ },+ {+ guidance: false,+ description:+ 'Wrap the thread in your own button or link to open it. The thread is already one toggle; a second control nests interactive elements.',+ },+ {+ guidance: false,+ description:+ 'Leave the host Popover’s light dismiss on while passing `onDismiss`. The browser closes the Popover before the thread can keep a draft.',+ },+ ],+ accessibility: [+ {+ name: 'Escape',+ category: 'Keyboard',+ criterion: '2.1.1 Keyboard',+ description:+ 'With `onDismiss`, Escape dismisses the thread only when no layer inside it is open. An open emoji picker, menu, or dialog closes first, one Escape at a time.',+ },+ {+ name: 'Unsaved draft warning',+ category: 'Semantics',+ criterion: '4.1.3 Status Messages',+ description:+ 'When a dismissal would discard an unsaved reply or edit, the thread stays open, focus returns to the draft, and a polite live region says the draft is unsaved and that dismissing again discards it. The shake is never the only signal.',+ },+ {+ name: 'Reduced motion',+ criterion: '2.3.3 Animation from Interactions',+ description:+ 'Under `prefers-reduced-motion: reduce` the thread does not shake. Focus and the announcement still mark the kept draft.',+ },+ ],+ },+ props: [+ {+ name: 'comment',+ type: 'CommentThreadData',+ required: true,+ description:+ 'The thread: its first comment, carrying its replies, reactions, optional anchor, transient `typingUsers`, and per-comment `seenBy` metadata. `seenBy` is not rendered by default but remains available to comment render callbacks.',+ },+ {+ name: 'isSelected',+ type: 'boolean',+ description:+ 'Whether the thread is open, controlled: body unclamped and replies shown. Omit it to let the thread own selection. Host-controlled selection never moves focus or opens the reply composer; a viewer Reply action does.',+ },+ {+ name: 'onSelectedChange',+ type: '(isSelected: boolean) => void',+ description: 'Called when the viewer opens or closes the thread.',+ },+ {+ name: 'onDismiss',+ type: '() => void',+ description:+ 'Hands the thread its anchored host’s light dismissal. A press outside the thread, or an Escape no layer inside it handled, calls it. While a reply or edit holds unsaved text, the first request instead shakes the thread, returns focus to the draft, and announces; the next consecutive request dismisses, and typing or pressing inside the thread re-arms the warning. Pair it with `hasLightDismiss={false}` and `hasEscapeDismiss={false}` on the host Popover. Omit it and the thread never dismisses anything.',+ },+ {+ name: 'currentUser',+ type: 'CommentUser',+ description: 'The viewer, for own-comment actions and the reply avatar.',+ },+ {+ name: 'mode',+ type: "'interactive' | 'non-editable' | 'read-only'",+ default: "'interactive'",+ description: 'Which actions show, as on Comments.',+ },+ {+ name: 'container',+ type: "'section' | 'card'",+ default: "'section'",+ description:+ 'The parent surface: an outlined Card on a page, or a Section without outer rules inside a card or popover.',+ },+ {+ name: 'onSubmit',+ type: '(content: string, parentCommentId?: string) => void | Promise<void>',+ description:+ 'Posts a reply, always with the thread’s first comment as the parent. A rejected Promise restores the draft and shows an error with Retry.',+ },+ {+ name: 'onComposerDraftChange',+ type: '(value: string, context: CommentComposerContext) => void',+ description:+ 'Reports internally owned reply and edit drafts, including seeds and an empty value after submit, cancel, or a target switch. Route updates by `context` and own transport timing in your app.',+ },+ {+ name: 'onSaveEdit',+ type: '(commentId: string, content: string) => void | Promise<void>',+ description:+ 'Adds Edit to the viewer’s own comments and saves the new Markdown.',+ },+ {+ name: 'onDelete',+ type: '(commentId: string) => void | Promise<void>',+ description:+ 'Adds Delete to the viewer’s own comments, confirmed in a dialog first.',+ },+ {+ name: 'onReact',+ type: '(commentId: string, reactionKey: string, option?: CommentReactionOption) => void | Promise<void>',+ description: 'Toggles the viewer’s reaction by its stable key.',+ },+ {+ name: 'onRetryComment',+ type: '(commentId: string) => void | Promise<void>',+ description: 'Adds Retry to a comment whose `status` is `error`.',+ },+ {+ name: 'onResolveThread',+ type: '(commentId: string) => void | Promise<void>',+ description: 'Adds Mark as resolved to an open thread.',+ },+ {+ name: 'onReopenThread',+ type: '(commentId: string) => void | Promise<void>',+ description: 'Adds Reopen to a resolved thread.',+ },+ {+ name: 'loadVersions',+ type: '(commentId: string) => Promise<readonly CommentVersion[]>',+ description: 'Loads a comment’s edit history, newest first.',+ },+ {+ name: 'onUploadImages',+ type: '(files: readonly File[], context: CommentComposerContext) => CommentUploadedImage[] | Promise<CommentUploadedImage[]>',+ description:+ 'Uploads images attached, pasted, or dropped in the reply composer and appends them as Markdown images.',+ },+ {+ name: 'isSubmitting',+ type: 'boolean',+ default: 'false',+ description: 'Host-controlled pending state for the reply composer.',+ },+ {+ name: 'composerPlaceholder',+ type: 'string',+ description:+ 'Placeholder of the reply composer. Defaults to the localized "Reply to <name>…".',+ },+ {+ name: 'highlightColor',+ type: "'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'",+ default: "'yellow'",+ description:+ 'The palette color your app highlights the thread’s passage in.',+ },+ {+ name: 'reactionOptions',+ type: 'readonly CommentReactionOption[]',+ default: 'DEFAULT_COMMENT_REACTIONS',+ description: 'The reactions Add reaction offers.',+ },+ {+ name: 'agentCommands',+ type: 'readonly CommentAgentCommand[]',+ description: 'Agents a reply can address with a `/` command.',+ },+ {+ name: 'composerTriggers',+ type: 'readonly ChatComposerTrigger[]',+ description:+ 'Typeahead triggers for the reply composer, such as an `@` people search.',+ },+ {+ name: 'markdownPlugins',+ type: 'readonly MarkdownPluginEntry[]',+ description: 'Block Markdown plugins for comment bodies.',+ },+ {+ name: 'markdownInlinePlugins',+ type: 'readonly MarkdownInlinePlugin[]',+ description:+ 'Inline Markdown plugins for comment bodies, such as mentions.',+ },+ {+ name: 'getReplyMention',+ type: '(author: CommentUser) => string | undefined',+ description: 'Seeds a reply to a reply with a mention of its author.',+ },+ {+ name: 'hasEmojiPicker',+ type: 'boolean',+ default: 'true',+ description: 'Whether the reply composer offers the emoji picker.',+ },+ {+ name: 'renderAnchor',+ type: '(comment: CommentThreadData, defaultAnchor: ReactNode) => ReactNode',+ description: 'Replaces the thread’s quoted passage.',+ },+ {+ name: 'renderBody',+ type: '(comment: CommentData) => ReactNode',+ description: 'Replaces a comment’s Markdown body.',+ },+ {+ name: 'renderVersionBody',+ type: '(version: CommentVersion) => ReactNode',+ description: 'Replaces the body of a version in the edit history.',+ },+ {+ name: 'renderAdditionalActions',+ type: '(comment: CommentData) => ReactNode',+ description: 'Adds product actions to a comment’s header.',+ },+ {+ name: 'renderComposer',+ type: '(props: CommentComposerRenderProps) => ReactNode',+ description:+ 'Replaces the reply composer’s input while the thread keeps its draft and state.',+ },+ ],+ examples: [+ {+ label: 'Margin comment',+ code: `import {Card} from '@astryxdesign/core/Card';+import {CommentThread} from '@astryxdesign/lab';++<Card padding={0} width={320}>+ <CommentThread+ comment={{+ id: 'margin',+ author: {id: 'maya', name: 'Maya Chen'},+ body: 'Should this say three days? The dry run adds one.',+ createdAt: '2026-09-30T19:00:00Z',+ anchor: {quote: 'The final cohort completes rollout in two days.'},+ }}+ currentUser={{id: 'avery', name: 'Avery Kim'}}+ container="card"+ onSubmit={(body, parentId) => postReply(parentId, body)}+ />+</Card>`,+ },+ {+ label: 'In a popover that keeps unsaved drafts',+ code: `import {useState} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {Popover} from '@astryxdesign/core/Popover';+import {CommentThread} from '@astryxdesign/lab';++function CommentPopover({thread, viewer}) {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <Popover+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ label="Comment"+ padding={0}+ width={340}+ content={+ <CommentThread+ comment={thread}+ currentUser={viewer}+ container="card"+ isSelected+ onSubmit={(body, parentId) => postReply(parentId, body)}+ onDismiss={() => setIsOpen(false)}+ />+ }>+ <Button label="1 comment" variant="secondary" />+ </Popover>+ );+}`,+ },+ ],+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsZh = {+ description:+ '单独呈现的一个评论线程:首条评论、一级回复、表情回应、编辑历史、受控的输入中与已读元数据,以及回复输入框。适用于文档旁的边注、高亮下方的弹出层,或任何只显示单个线程的界面。',+ usage: {+ description:+ '评论线程展示一段对话:首条评论及其下的回复。用于只显示单个线程的界面,例如文档旁的边注卡片,或从高亮处打开的弹出层。要显示多个线程并提供新评论输入框,请使用 Comments。',+ bestPractices: [+ {+ guidance: true,+ description:+ '放在卡片或弹出层中时,设置 `container="card"` 并去掉卡片的内边距:线程自带内边距,且不绘制外框线。',+ },+ {+ guidance: true,+ description:+ '当线程从其他位置打开(例如文档中的高亮)时,控制 `isSelected`。受控选中会展开正文和回复,但不会移动焦点或打开回复输入框。',+ },+ {+ guidance: true,+ description:+ '在覆盖文档的 Popover 中,传入 `onDismiss`,并在宿主 Popover 上设置 `hasLightDismiss={false}` 和 `hasEscapeDismiss={false}`。这样在线程外按下或按 Escape 会关闭线程;但若回复或编辑中有未保存的文字,第一次只会抖动线程并保留草稿。',+ },+ {+ guidance: true,+ description:+ '将协作状态映射到 `typingUsers` 和 `seenBy`,再通过 `onComposerDraftChange` 发布本地的回复和编辑动态。`seenBy` 默认不显示,除非评论渲染回调展示它。线程从不建立连接,也不会让参与者过期。',+ },+ {+ guidance: false,+ description:+ '把多个 CommentThread 与输入框堆叠成讨论区。请使用 Comments,它一次只展开一个线程,并按动态排序线程。',+ },+ {+ guidance: false,+ description:+ '用自己的按钮或链接包裹线程来打开它。线程本身已是一个切换控件;再加一个控件会嵌套交互元素。',+ },+ {+ guidance: false,+ description:+ '传入 `onDismiss` 时仍保留宿主 Popover 的轻触关闭。浏览器会在线程保留草稿之前关闭 Popover。',+ },+ ],+ accessibility: [+ {+ name: 'Escape',+ category: 'Keyboard',+ criterion: '2.1.1 Keyboard',+ description:+ '传入 `onDismiss` 后,只有当线程内没有打开的图层时,Escape 才会关闭线程。打开的表情选择器、菜单或对话框会先关闭,每次 Escape 只关闭一层。',+ },+ {+ name: '未保存草稿提示',+ category: 'Semantics',+ criterion: '4.1.3 Status Messages',+ description:+ '当关闭会丢弃未保存的回复或编辑时,线程保持打开,焦点回到草稿,礼貌型实时区域会说明草稿尚未保存,再次关闭将丢弃它。抖动从来不是唯一的提示。',+ },+ {+ name: '减少动态效果',+ criterion: '2.3.3 Animation from Interactions',+ description:+ '在 `prefers-reduced-motion: reduce` 下线程不会抖动。焦点移动和播报仍会提示草稿已保留。',+ },+ ],+ },+ propDescriptions: {+ comment:+ '线程:首条评论,携带其回复、表情回应、可选锚点、临时的 `typingUsers`,以及每条评论的 `seenBy` 元数据。`seenBy` 默认不渲染,但评论渲染回调可以使用。',+ isSelected:+ '线程是否展开(受控):正文不截断并显示回复。省略时由线程自行管理选中。宿主控制的选中从不移动焦点或打开回复输入框;查看者点击“回复”才会。',+ onSelectedChange: '查看者展开或收起线程时调用。',+ onDismiss:+ '把锚定宿主的轻触关闭交给线程处理。在线程外按下,或线程内没有图层处理的 Escape,都会调用它。若回复或编辑中有未保存的文字,第一次请求改为抖动线程、把焦点移回草稿并播报;紧接着的下一次请求才会关闭,输入或在线程内按下会重新启用提示。请在宿主 Popover 上同时设置 `hasLightDismiss={false}` 和 `hasEscapeDismiss={false}`。省略时线程不会关闭任何东西。',+ currentUser: '查看者,用于本人评论的操作和回复头像。',+ mode: '显示哪些操作,与 Comments 相同。',+ container:+ '父级界面:页面上的描边 Card,或卡片、弹出层中不带外框线的 Section。',+ onSubmit:+ '发布回复,父级始终是线程的首条评论。被拒绝的 Promise 会恢复草稿,并显示带“重试”的错误。',+ onComposerDraftChange:+ '报告线程内部管理的回复和编辑草稿,包括预填内容,以及提交、取消或切换目标后的空值。请按 `context` 分发更新,并在应用中自行控制传输时机。',+ onSaveEdit: '为查看者自己的评论添加“编辑”,并保存新的 Markdown。',+ onDelete: '为查看者自己的评论添加“删除”,先在对话框中确认。',+ onReact: '按稳定的键切换查看者的表情回应。',+ onRetryComment: '为 `status` 为 `error` 的评论添加“重试”。',+ onResolveThread: '为未解决的线程添加“标记为已解决”。',+ onReopenThread: '为已解决的线程添加“重新打开”。',+ loadVersions: '加载评论的编辑历史,最新的在前。',+ onUploadImages:+ '上传在回复输入框中附加、粘贴或拖入的图片,并以 Markdown 图片追加。',+ isSubmitting: '宿主控制的回复输入框等待状态。',+ composerPlaceholder: '回复输入框的占位文字。默认为本地化的“回复 <name>…”。',+ highlightColor: '应用中高亮该线程所引用段落的调色板颜色。',+ reactionOptions: '“添加表情回应”提供的选项。',+ agentCommands: '回复可以通过 `/` 命令呼叫的智能体。',+ composerTriggers: '回复输入框的联想触发器,例如 `@` 人员搜索。',+ markdownPlugins: '评论正文的块级 Markdown 插件。',+ markdownInlinePlugins: '评论正文的行内 Markdown 插件,例如提及。',+ getReplyMention: '回复某条回复时,用提及其作者的内容预填。',+ hasEmojiPicker: '回复输入框是否提供表情选择器。',+ renderAnchor: '替换线程引用的段落。',+ renderBody: '替换评论的 Markdown 正文。',+ renderVersionBody: '替换编辑历史中某个版本的正文。',+ renderAdditionalActions: '向评论标题栏添加产品操作。',+ renderComposer: '替换回复输入框的输入区域,线程仍保留其草稿和状态。',+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description:+ 'One comment thread alone: first comment, one reply level, reactions, edit history, controlled typing/seen metadata, reply composer. For margin comments, highlight popovers, any single-thread surface.',+ usage: {+ description:+ 'One conversation: first comment plus replies. For margin cards or highlight popovers. Many threads with a new-comment composer: use Comments.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'In a card or popover: `container="card"`, card padding 0. Thread owns insets, draws no outer rules.',+ },+ {+ guidance: true,+ description:+ 'Control `isSelected` when opened from elsewhere (a document highlight). Reveals body and replies without moving focus or opening the composer.',+ },+ {+ guidance: true,+ description:+ 'In a Popover over a document: pass `onDismiss`, set `hasLightDismiss={false}` and `hasEscapeDismiss={false}` on the host. Outside press or Escape closes; the first over an unsaved reply/edit shakes and keeps the draft.',+ },+ {+ guidance: true,+ description:+ 'Map collaboration state to `typingUsers`/`seenBy`; publish local drafts via `onComposerDraftChange`. `seenBy` hidden unless a render callback shows it. No connections, no participant expiry.',+ },+ {+ guidance: false,+ description:+ 'Stack CommentThreads plus a composer as a discussion. Use Comments.',+ },+ {+ guidance: false,+ description:+ 'Wrap the thread in your own button/link. It is already one toggle.',+ },+ {+ guidance: false,+ description:+ 'Keep host Popover light dismiss on with `onDismiss`. The browser closes it before the thread can keep a draft.',+ },+ ],+ accessibility: [+ {+ name: 'Escape',+ category: 'Keyboard',+ criterion: '2.1.1 Keyboard',+ description:+ 'With `onDismiss`, Escape dismisses only when no inner layer is open. Picker, menu, or dialog closes first, one per Escape.',+ },+ {+ name: 'Unsaved draft warning',+ category: 'Semantics',+ criterion: '4.1.3 Status Messages',+ description:+ 'A dismissal over an unsaved reply/edit keeps the thread open, refocuses the draft, and announces politely. Shake is never the only signal.',+ },+ {+ name: 'Reduced motion',+ criterion: '2.3.3 Animation from Interactions',+ description:+ 'No shake under `prefers-reduced-motion: reduce`; focus and announcement remain.',+ },+ ],+ },+ propDescriptions: {+ comment:+ 'The thread: first comment with replies, reactions, optional anchor, transient `typingUsers`, per-comment `seenBy` (not rendered by default).',+ isSelected:+ 'Controlled open state. Omit for uncontrolled. Never moves focus or opens the composer.',+ onSelectedChange: 'Viewer opened or closed the thread.',+ onDismiss:+ 'Thread owns its anchored host’s light dismissal: outside press or unhandled Escape calls it. Over an unsaved reply/edit, the first request shakes, refocuses the draft, announces; the next consecutive one dismisses. Typing or pressing inside re-arms. Pair with host `hasLightDismiss={false}` and `hasEscapeDismiss={false}`.',+ currentUser: 'Viewer: own-comment actions, reply avatar.',+ mode: 'Which actions show, as on Comments.',+ container:+ 'Parent surface: outlined Card on a page, or rule-less Section in a card/popover.',+ onSubmit:+ 'Posts a reply; parent is always the first comment. Rejection restores the draft with Retry.',+ onComposerDraftChange:+ 'Reports reply/edit drafts, seeds, and empty values after submit, cancel, or target switch. Route by `context`.',+ onSaveEdit: 'Adds Edit to own comments; saves new Markdown.',+ onDelete: 'Adds Delete to own comments, confirmed in a dialog.',+ onReact: 'Toggles the viewer’s reaction by stable key.',+ onRetryComment: 'Adds Retry to `status: error` comments.',+ onResolveThread: 'Adds Mark as resolved to an open thread.',+ onReopenThread: 'Adds Reopen to a resolved thread.',+ loadVersions: 'Loads edit history, newest first.',+ onUploadImages: 'Uploads composer images; appends Markdown images.',+ isSubmitting: 'Host pending state for the reply composer.',+ composerPlaceholder:+ 'Reply placeholder. Default: localized "Reply to <name>…".',+ highlightColor: 'Palette color of the passage highlight.',+ reactionOptions: 'Reactions Add reaction offers.',+ agentCommands: 'Agents a reply can address with `/`.',+ composerTriggers: 'Reply typeahead triggers, e.g. `@` people search.',+ markdownPlugins: 'Block Markdown plugins for bodies.',+ markdownInlinePlugins: 'Inline Markdown plugins for bodies, e.g. mentions.',+ getReplyMention: 'Seeds a reply-to-reply with an author mention.',+ hasEmojiPicker: 'Whether the reply composer offers the emoji picker.',+ renderAnchor: 'Replaces the quoted passage.',+ renderBody: 'Replaces a comment’s Markdown body.',+ renderVersionBody: 'Replaces a history version’s body.',+ renderAdditionalActions: 'Adds product actions to a comment header.',+ renderComposer: 'Replaces the reply input; thread keeps draft and state.',+ },+};diff --git a/packages/lab/src/Comments/CommentThread.test.tsx b/packages/lab/src/Comments/CommentThread.test.tsxnew file mode 100644index 0000000000..d72b0a5feb--- /dev/null+++ b/packages/lab/src/Comments/CommentThread.test.tsx@@ -0,0 +1,634 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {act, fireEvent, render, screen, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {useState} from 'react';+import {createPortal} from 'react-dom';+import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';+// The full emoji set renders slowly in jsdom; the composer only needs a few.+vi.mock('../EmojiPicker/emojiData', () => ({+ EMOJI_GROUPS: [+ {+ name: 'Activities',+ emojis: [+ ['🎉', 'Party popper', 'celebration tada'],+ ['🎈', 'Balloon', 'celebration'],+ ],+ },+ ],+}));++import {Popover} from '@astryxdesign/core/Popover';+import {CommentThread, type CommentThreadProps} from './CommentThread';+import {unsavedDraftOf} from './useCommentThreadDismissal';+import type {+ CommentComposerRenderProps,+ CommentThreadData,+ CommentUser,+} from './types';++const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};+const OTHER: CommentUser = {id: 'maya', name: 'Maya Chen'};++const THREAD: CommentThreadData = {+ id: 'margin',+ author: OTHER,+ body: 'Should this say three days?',+ createdAt: '2026-09-30T19:00:00Z',+ anchor: {quote: 'The final cohort completes rollout in two days.'},+ replies: [+ {+ id: 'margin-reply',+ author: VIEWER,+ body: 'Good catch, updating it.',+ createdAt: '2026-09-30T19:20:00Z',+ },+ ],+};++const originalMatches = HTMLElement.prototype.matches;+const popoverOpenState = new WeakMap<HTMLElement, boolean>();++beforeAll(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, true);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ popoverOpenState.set(this, false);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ });+ Object.defineProperty(HTMLElement.prototype, 'matches', {+ configurable: true,+ writable: true,+ value(this: HTMLElement, selector: string): boolean {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ return originalMatches.call(this, selector);+ },+ });+});++afterAll(() => {+ Object.defineProperty(HTMLElement.prototype, 'matches', {+ configurable: true,+ writable: true,+ value: originalMatches,+ });+});++class ResizeObserverStub {+ observe() {}+ unobserve() {}+ disconnect() {}+}++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);+ Element.prototype.scrollIntoView = () => {};+});++afterEach(() => {+ vi.unstubAllGlobals();+});++async function settle() {+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 0)));+}++describe('CommentThread', () => {+ it('renders one thread with its quoted passage, collapsed replies, and no rules', () => {+ render(<CommentThread comment={THREAD} container="card" />);+ const surface = document.querySelector('[data-thread-id="margin"]');+ expect(surface?.getAttribute('data-thread-surface')).toBe('section');+ expect(screen.getByText(THREAD.anchor?.quote ?? '')).toBeTruthy();+ expect(screen.getByText('View 1 reply')).toBeTruthy();+ expect(screen.queryByText('Good catch, updating it.')).toBeNull();+ });++ it('opens on a press, showing its replies and reply composer', async () => {+ const onSelectedChange = vi.fn();+ render(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ onSubmit={vi.fn()}+ onSelectedChange={onSelectedChange}+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Thread by Maya Chen'}));+ await settle();+ expect(onSelectedChange).toHaveBeenCalledWith(true);+ expect(screen.getByText('Good catch, updating it.')).toBeTruthy();+ expect(+ screen.getByRole('textbox', {name: 'Reply to Maya Chen…'}),+ ).toBeTruthy();+ });++ it('opens when the host selects it', async () => {+ const {rerender} = render(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ onSubmit={vi.fn()}+ isSelected={false}+ />,+ );+ expect(screen.queryByText('Good catch, updating it.')).toBeNull();+ rerender(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ onSubmit={vi.fn()}+ isSelected+ />,+ );+ await settle();+ expect(screen.getByText('Good catch, updating it.')).toBeTruthy();+ });++ it('opens a thread selected at mount without opening its composer or taking focus', async () => {+ render(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ onSubmit={vi.fn()}+ isSelected+ />,+ );+ await settle();+ // Restored host state opens the body and replies. Only a viewer Reply action+ // opens the composer, so controlled selection never steals focus.+ expect(screen.getByText('Good catch, updating it.')).toBeTruthy();+ expect(+ screen.queryByRole('textbox', {name: 'Reply to Maya Chen…'}),+ ).toBeNull();+ expect(document.body).toHaveFocus();+ });++ it('opens from the keyboard and keeps focus on the thread', async () => {+ const user = userEvent.setup();+ const onSelectedChange = vi.fn();+ render(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ onSubmit={vi.fn()}+ onSelectedChange={onSelectedChange}+ />,+ );+ const toggle = screen.getByRole('button', {name: 'Thread by Maya Chen'});+ await user.tab();+ expect(toggle).toHaveFocus();+ await user.keyboard('{Enter}');+ await settle();+ expect(onSelectedChange).toHaveBeenLastCalledWith(true);+ expect(screen.getByText('Good catch, updating it.')).toBeTruthy();+ // A key press leaves focus on the thread rather than moving it.+ expect(toggle).toHaveFocus();+ await user.keyboard(' ');+ await settle();+ expect(onSelectedChange).toHaveBeenLastCalledWith(false);+ expect(toggle).toHaveFocus();+ });++ it('forwards the reply draft lifecycle through a standalone thread', async () => {+ const onComposerDraftChange = vi.fn();+ const onSubmit = vi.fn().mockResolvedValue(undefined);+ const renderComposer = (props: CommentComposerRenderProps) => (+ <section aria-label="Live reply">+ <button type="button" onClick={() => props.onChange('Live reply body')}>+ Set live draft+ </button>+ <button type="button" onClick={() => props.onSubmit(props.value)}>+ Submit live draft+ </button>+ </section>+ );+ render(+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ isSelected+ onSubmit={onSubmit}+ onComposerDraftChange={onComposerDraftChange}+ renderComposer={renderComposer}+ />,+ );+ await settle();++ const context = {+ kind: 'reply' as const,+ parentCommentId: 'margin',+ repliedToCommentId: 'margin',+ };+ fireEvent.click(+ within(screen.getByRole('article', {name: 'Maya Chen'})).getByRole(+ 'button',+ {name: 'Reply'},+ ),+ );+ await settle();+ fireEvent.click(screen.getByText('Set live draft'));+ expect(onComposerDraftChange).toHaveBeenLastCalledWith(+ 'Live reply body',+ context,+ );+ fireEvent.click(screen.getByText('Submit live draft'));+ await settle();+ expect(onSubmit).toHaveBeenCalledWith('Live reply body', 'margin');+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('', context);+ });++ it('forwards root props', () => {+ render(<CommentThread comment={THREAD} data-testid="margin-thread" />);+ expect(screen.getByTestId('margin-thread').className).toContain(+ 'astryx-comment-thread',+ );+ });+});++describe('CommentThread dismissal', () => {+ type FakeAnimation = {+ cancel: ReturnType<typeof vi.fn>;+ addEventListener: ReturnType<typeof vi.fn>;+ };+ let animate: ReturnType<typeof vi.fn>;+ let animations: FakeAnimation[];++ beforeEach(() => {+ animations = [];+ animate = vi.fn(() => {+ const animation: FakeAnimation = {+ cancel: vi.fn(),+ addEventListener: vi.fn(),+ };+ animations.push(animation);+ return animation;+ });+ Object.defineProperty(HTMLElement.prototype, 'animate', {+ configurable: true,+ writable: true,+ value: animate,+ });+ });++ afterEach(() => {+ delete (HTMLElement.prototype as Partial<HTMLElement>).animate;+ vi.restoreAllMocks();+ });++ const PRESS = {button: 0, isPrimary: true, pointerId: 1};++ /** A full primary press: whether its mousedown and click went unclaimed. */+ function press(target: Element) {+ fireEvent.pointerDown(target, PRESS);+ const mouseDown = fireEvent.mouseDown(target);+ fireEvent.pointerUp(target, PRESS);+ fireEvent.mouseUp(target);+ const click = fireEvent.click(target);+ return {mouseDown, click};+ }++ function renderThread(props: Partial<CommentThreadProps> = {}) {+ const onDismiss = vi.fn();+ const result = render(+ <>+ <button type="button">Elsewhere</button>+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ isSelected+ onSubmit={vi.fn()}+ onDismiss={onDismiss}+ {...props}+ />+ </>,+ );+ return {onDismiss, ...result};+ }++ // A closed-by-default host's top layer reads as hidden to jsdom's+ // accessibility tree, so queries inside a Popover include hidden elements.+ async function openReply({hidden = false} = {}) {+ fireEvent.click(+ within(+ screen.getByRole('article', {name: 'Maya Chen', hidden}),+ ).getByRole('button', {name: 'Reply', hidden}),+ );+ await settle();+ return screen.getByRole('textbox', {name: 'Reply to Maya Chen…', hidden});+ }++ function typeDraft(textbox: HTMLElement, text: string) {+ textbox.textContent = text;+ fireEvent.input(textbox);+ }++ async function politeAnnouncement() {+ await act(+ () =>+ new Promise<void>(resolve => requestAnimationFrame(() => resolve())),+ );+ return (+ document.querySelector('[data-astryx-live-region="polite"]')+ ?.textContent ?? ''+ );+ }++ const UNSAVED = 'Unsaved draft. Dismiss again to discard it.';++ it('dismisses on an outside press when nothing is unsaved', async () => {+ const {onDismiss} = renderThread();+ await settle();+ const {click} = press(screen.getByRole('button', {name: 'Elsewhere'}));+ expect(onDismiss).toHaveBeenCalledTimes(1);+ expect(animate).not.toHaveBeenCalled();+ // Only a guarded press is spent; this click reaches its target.+ expect(click).toBe(true);+ });++ it('dismisses with an open reply that holds only whitespace', async () => {+ const {onDismiss} = renderThread();+ await settle();+ typeDraft(await openReply(), ' ');+ press(screen.getByRole('button', {name: 'Elsewhere'}));+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('shakes, refocuses, and announces on the first outside press over a draft, then dismisses on the second', async () => {+ const {onDismiss, container} = renderThread();+ await settle();+ const textbox = await openReply();+ typeDraft(textbox, 'Half a thought');+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ elsewhere.focus();++ const first = press(elsewhere);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(animate).toHaveBeenCalledTimes(1);+ expect(animate.mock.contexts[0]).toBe(+ container.querySelector('.astryx-comment-thread'),+ );+ const [keyframes, options] = animate.mock.calls[0] as [+ Keyframe[],+ KeyframeAnimationOptions,+ ];+ expect(keyframes[0].transform).toBe(keyframes.at(-1)?.transform);+ expect(options.duration).toBeGreaterThanOrEqual(300);+ expect(options.duration).toBeLessThanOrEqual(450);+ expect(textbox).toHaveFocus();+ expect(await politeAnnouncement()).toBe(UNSAVED);+ // The guarded press keeps focus where it is and activates nothing.+ expect(first.mouseDown).toBe(false);+ expect(first.click).toBe(false);++ press(elsewhere);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ expect(animate).toHaveBeenCalledTimes(1);+ });++ it('re-arms after the draft changes or the viewer presses inside', async () => {+ const {onDismiss} = renderThread();+ await settle();+ const textbox = await openReply();+ typeDraft(textbox, 'First');+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});++ press(elsewhere);+ typeDraft(textbox, 'First, then more');+ press(elsewhere);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(animate).toHaveBeenCalledTimes(2);+ // The second shake replaced the first rather than stacking on it.+ expect(animations[0].cancel).toHaveBeenCalled();++ press(textbox);+ press(elsewhere);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(animate).toHaveBeenCalledTimes(3);++ press(elsewhere);+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('ignores secondary buttons and touches that turn into a scroll', async () => {+ const {onDismiss} = renderThread();+ await settle();+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ fireEvent.pointerDown(elsewhere, {...PRESS, button: 2});+ fireEvent.pointerUp(elsewhere, {...PRESS, button: 2});+ fireEvent.pointerDown(elsewhere, PRESS);+ fireEvent.pointerCancel(elsewhere, PRESS);+ fireEvent.pointerUp(elsewhere, PRESS);+ expect(onDismiss).not.toHaveBeenCalled();+ });++ it('counts a press in a layer the thread portals elsewhere as inside', async () => {+ const {onDismiss, container} = renderThread({+ renderAdditionalActions: () =>+ createPortal(+ <button type="button">Portaled action</button>,+ document.body,+ ),+ });+ await settle();+ const portaled = screen.getAllByRole('button', {+ name: 'Portaled action',+ })[0];+ // The DOM puts it outside the thread; React's tree puts it inside.+ expect(+ container.querySelector('.astryx-comment-thread')?.contains(portaled),+ ).toBe(false);+ press(portaled);+ expect(onDismiss).not.toHaveBeenCalled();+ });++ it('leaves an outside press to an open emoji picker above the thread', async () => {+ const {onDismiss} = renderThread();+ await settle();+ typeDraft(await openReply(), 'Draft');+ fireEvent.click(screen.getByRole('button', {name: 'Add emoji'}));+ await settle();+ press(screen.getByRole('button', {name: 'Elsewhere'}));+ expect(onDismiss).not.toHaveBeenCalled();+ expect(animate).not.toHaveBeenCalled();+ });++ it('requests dismissal on an Escape no nested layer handled', async () => {+ const {onDismiss} = renderThread();+ await settle();+ fireEvent.keyDown(document.body, {key: 'Escape'});+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('guards a draft on Escape and dismisses on the next one', async () => {+ const {onDismiss} = renderThread();+ await settle();+ const textbox = await openReply();+ typeDraft(textbox, 'Draft');+ expect(fireEvent.keyDown(textbox, {key: 'Escape'})).toBe(false);+ expect(onDismiss).not.toHaveBeenCalled();+ expect(animate).toHaveBeenCalledTimes(1);+ expect(textbox).toHaveFocus();+ expect(await politeAnnouncement()).toBe(UNSAVED);+ fireEvent.keyDown(textbox, {key: 'Escape'});+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('closes an open emoji picker on Escape before the thread', async () => {+ const {onDismiss} = renderThread();+ await settle();+ await openReply();+ const emoji = screen.getByRole('button', {name: 'Add emoji'});+ fireEvent.click(emoji);+ await settle();+ expect(emoji).toHaveAttribute('aria-expanded', 'true');+ fireEvent.keyDown(document.activeElement ?? document.body, {+ key: 'Escape',+ });+ await settle();+ expect(emoji).toHaveAttribute('aria-expanded', 'false');+ expect(onDismiss).not.toHaveBeenCalled();+ fireEvent.keyDown(document.activeElement ?? document.body, {+ key: 'Escape',+ });+ expect(onDismiss).toHaveBeenCalledTimes(1);+ });++ it('does not move under reduced motion but still refocuses and announces', async () => {+ vi.spyOn(window, 'matchMedia').mockImplementation(+ query =>+ ({+ matches: query === '(prefers-reduced-motion: reduce)',+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }) as MediaQueryList,+ );+ const {onDismiss} = renderThread();+ await settle();+ const textbox = await openReply();+ typeDraft(textbox, 'Draft');+ press(screen.getByRole('button', {name: 'Elsewhere'}));+ expect(animate).not.toHaveBeenCalled();+ expect(onDismiss).not.toHaveBeenCalled();+ expect(textbox).toHaveFocus();+ expect(await politeAnnouncement()).toBe(UNSAVED);+ });++ it('adds no listeners and dismisses nothing without onDismiss', async () => {+ const addListener = vi.spyOn(document, 'addEventListener');+ renderThread({onDismiss: undefined});+ await settle();+ const textbox = await openReply();+ typeDraft(textbox, 'Draft');+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});+ const {mouseDown, click} = press(elsewhere);+ fireEvent.keyDown(textbox, {key: 'Escape'});+ expect(animate).not.toHaveBeenCalled();+ expect(mouseDown).toBe(true);+ expect(click).toBe(true);+ expect(+ addListener.mock.calls.some(([type]) => type === 'pointercancel'),+ ).toBe(false);+ });++ it('keeps a Popover host open on its trigger over a draft and closes without reopening otherwise', async () => {+ function Host() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <Popover+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ hasLightDismiss={false}+ hasEscapeDismiss={false}+ hasAutoFocus={false}+ label="Comment"+ padding={0}+ content={+ <CommentThread+ comment={THREAD}+ currentUser={VIEWER}+ isSelected+ container="card"+ onSubmit={vi.fn()}+ onDismiss={() => setIsOpen(false)}+ />+ }>+ <button type="button">Open comment</button>+ </Popover>+ );+ }+ render(<Host />);+ const trigger = screen.getByRole('button', {name: 'Open comment'});+ fireEvent.click(trigger);+ await settle();+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ const textbox = await openReply({hidden: true});+ typeDraft(textbox, 'Draft');+ press(trigger);+ await settle();+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(animate).toHaveBeenCalledTimes(1);++ press(trigger);+ await settle();+ // Closed, and the same press's click did not toggle it back open.+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it('derives an unsaved draft from typed replies and changed edits only', () => {+ const reply = {parentId: 'margin', comment: THREAD};+ expect(+ unsavedDraftOf({replyTarget: null, replyDraft: '', editTarget: null}),+ ).toBeNull();+ expect(+ unsavedDraftOf({+ replyTarget: {...reply, seed: '@Maya '},+ replyDraft: '@Maya ',+ editTarget: null,+ }),+ ).toBeNull();+ expect(+ unsavedDraftOf({+ replyTarget: {...reply, seed: '@Maya '},+ replyDraft: '@Maya agreed',+ editTarget: null,+ })?.kind,+ ).toBe('reply');+ expect(+ unsavedDraftOf({+ replyTarget: null,+ replyDraft: '',+ editTarget: {comment: THREAD, value: `${THREAD.body} `},+ }),+ ).toBeNull();+ expect(+ unsavedDraftOf({+ replyTarget: null,+ replyDraft: '',+ editTarget: {comment: THREAD, value: 'Should this say four days?'},+ })?.kind,+ ).toBe('edit');+ });+});diff --git a/packages/lab/src/Comments/CommentThread.tsx b/packages/lab/src/Comments/CommentThread.tsxnew file mode 100644index 0000000000..493c46a61c--- /dev/null+++ b/packages/lab/src/Comments/CommentThread.tsx@@ -0,0 +1,226 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CommentThread.tsx+ * @input Uses React, StyleX, the Comments family's controller, CommentRow,+ * LayerDepthProvider, and useCommentThreadDismissal+ * @output Exports CommentThread and CommentThreadProps+ * @position One comment thread on its own: its first comment, one level of+ * replies, reactions, actions, and the reply composer. For a margin comment+ * beside a document, a popover under a highlight, or any surface that shows+ * a single thread; Comments renders many with a composer for new ones.+ * With `onDismiss`, it owns its anchored host's light dismissal and guards+ * an unsaved draft against it.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/Comments/index.ts (exports)+ * - /packages/lab/src/Comments/CommentThread.doc.mjs+ * - /packages/lab/src/Comments/useCommentThreadDismissal.ts+ */++import {useCallback, useMemo, useRef, type Ref} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {LayerDepthProvider} from '@astryxdesign/core/Layer';+import {VStack} from '@astryxdesign/core/Layout';+import {mergeProps, themeProps} from '@astryxdesign/core/utils';+import {CommentRow} from './CommentRow';+import {+ CommentsContextProvider,+ useCommentsController,+} from './CommentsContext';+import type {CommentThreadData, CommentThreadSharedProps} from './types';+import {+ unsavedDraftOf,+ useCommentThreadDismissal,+} from './useCommentThreadDismissal';++export interface CommentThreadProps+ extends+ CommentThreadSharedProps,+ Omit<+ BaseProps<HTMLElement>,+ keyof CommentThreadSharedProps | 'onChange' | 'onSubmit'+ > {+ /** Ref forwarded to the root element. */+ ref?: Ref<HTMLElement>;+ /** The thread: its first comment, which carries its replies. */+ comment: CommentThreadData;+ /**+ * Whether the thread is open: its body unclamped and its replies shown. Omit+ * it to let the thread own selection; set it to open a thread from elsewhere,+ * such as its highlight in a document. Host selection does not move focus or+ * open the reply composer; a viewer Reply action does.+ */+ isSelected?: boolean;+ /** Called when the viewer opens or closes the thread. */+ onSelectedChange?: (isSelected: boolean) => void;+ /**+ * Hands the thread its anchored host's light dismissal, such as a Popover+ * opened from a highlight. A press outside the thread, or an Escape no layer+ * inside it handled, calls this, except that while a reply or edit holds+ * unsaved text the first request shakes the thread and returns focus to the+ * draft instead; the next consecutive request dismisses. Pair it with+ * `hasLightDismiss={false}` and `hasEscapeDismiss={false}` on the host+ * Popover. Omit it and the thread never dismisses anything.+ */+ onDismiss?: () => void;+}++/**+ * One comment thread: its first comment, one level of replies, reactions,+ * edit history, and a reply composer. Controlled: the host owns the data and+ * every mutation; the thread owns presentation, selection, and focus.+ *+ * @example+ * ```+ * <CommentThread+ * comment={thread}+ * currentUser={viewer}+ * container="card"+ * onSubmit={(body, parentId) => postReply(parentId, body)}+ * onReact={toggleReaction}+ * />+ * ```+ */+export function CommentThread({+ comment,+ isSelected,+ onSelectedChange,+ onDismiss,+ currentUser,+ mode,+ container,+ composerPlaceholder,+ highlightColor,+ reactionOptions,+ agentCommands,+ composerTriggers,+ markdownPlugins,+ markdownInlinePlugins,+ getReplyMention,+ hasEmojiPicker,+ isSubmitting,+ onComposerDraftChange,+ onSubmit,+ onSaveEdit,+ onDelete,+ onReact,+ onRetryComment,+ onResolveThread,+ onReopenThread,+ loadVersions,+ onUploadImages,+ renderAnchor,+ renderBody,+ renderVersionBody,+ renderAdditionalActions,+ renderComposer,+ ref,+ xstyle,+ className,+ style,+ onPointerDownCapture,+ ...rest+}: CommentThreadProps) {+ const rootRef = useRef<HTMLElement | null>(null);+ const setRootRef = useCallback(+ (element: HTMLElement | null) => {+ rootRef.current = element;+ if (typeof ref === 'function') {+ ref(element);+ } else if (ref != null) {+ ref.current = element;+ }+ },+ [ref],+ );+ const roots = useMemo(() => [comment], [comment]);+ const {value, dialogs, announce} = useCommentsController({+ currentUser,+ mode,+ container,+ composerPlaceholder,+ highlightColor,+ reactionOptions,+ agentCommands,+ composerTriggers,+ markdownPlugins,+ markdownInlinePlugins,+ getReplyMention,+ hasEmojiPicker,+ isSubmitting,+ onComposerDraftChange,+ onSubmit,+ onSaveEdit,+ onDelete,+ onReact,+ onRetryComment,+ onResolveThread,+ onReopenThread,+ loadVersions,+ onUploadImages,+ renderAnchor,+ renderBody,+ renderVersionBody,+ renderAdditionalActions,+ renderComposer,+ selectedThreadId:+ isSelected === undefined ? undefined : isSelected ? comment.id : null,+ onSelectedThreadChange: threadId =>+ onSelectedChange?.(threadId === comment.id),+ roots,+ rootRef,+ });+ const dismissal = useCommentThreadDismissal({+ onDismiss,+ rootRef,+ draft: unsavedDraftOf(value),+ announce,+ });++ const content = (+ <>+ {/* A lone thread on a card parent sits inside the host's border, so+ it draws no rules of its own. */}+ <CommentRow+ comment={comment}+ depth={0}+ threadId={comment.id}+ dividers={[]}+ />+ {dialogs}+ </>+ );++ return (+ <CommentsContextProvider value={value}>+ <VStack+ ref={setRootRef}+ tabIndex={-1}+ width="100%"+ {...rest}+ onPointerDownCapture={event => {+ dismissal.onRootPointerDownCapture(event);+ onPointerDownCapture?.(event);+ }}+ {...mergeProps(+ themeProps('comment-thread', {container: container ?? 'section'}),+ stylex.props(xstyle),+ className,+ style,+ )}>+ {/* Layers the thread opens sit above it on the dismissal stack. */}+ {dismissal.isEnabled ? (+ <LayerDepthProvider>{content}</LayerDepthProvider>+ ) : (+ content+ )}+ </VStack>+ </CommentsContextProvider>+ );+}++CommentThread.displayName = 'CommentThread';diff --git a/packages/lab/src/Comments/CommentsContext.tsx b/packages/lab/src/Comments/CommentsContext.tsxnew file mode 100644index 0000000000..24acb8a081--- /dev/null+++ b/packages/lab/src/Comments/CommentsContext.tsx@@ -0,0 +1,755 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CommentsContext.tsx+ * @input Uses React state, React DOM flushSync, AlertDialog, Dialog, Markdown+ * body, and useAnnounce+ * @output Exports the Comments family's shared context, the controller hook+ * that owns its interaction state (selection, reply and edit targets, draft+ * lifecycle reporting, pending actions, failures, focus hand-offs, delete+ * confirmation, and edit history), the dialogs it opens, and its announcer+ * @position Internal state layer shared by Comments and a standalone+ * CommentThread; comment rows read it instead of taking dozens of props+ */++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useRef,+ useState,+ type ReactNode,+ type RefObject,+} from 'react';+import {flushSync} from 'react-dom';+import type {ChatComposerTrigger} from '@astryxdesign/core/Chat';+import type {MarkdownInlinePlugin} from '@astryxdesign/core/Markdown';+import type {MarkdownPluginEntry} from '@astryxdesign/core/Markdown/plugins';+import {AlertDialog} from '@astryxdesign/core/AlertDialog';+import {useAnnounce} from '@astryxdesign/core/hooks';+import {useTranslator} from '@astryxdesign/core/i18n';+import {CommentMarkdown} from './CommentMarkdown';+import {commentMoreMenuTrigger, visibleCommentAction} from './CommentActions';+import {HistoryDialog, type HistoryState} from './CommentParts';+import {+ commentAnchorId,+ replyComposerId,+ shouldRestoreFocusFrom,+ type AnyComment,+} from './utils';+import {+ DEFAULT_COMMENT_REACTIONS,+ type CommentAgentCommand,+ type CommentComposerContext,+ type CommentHighlightColor,+ type CommentImageUploader,+ type CommentMode,+ type CommentReactionOption,+ type CommentThreadData,+ type CommentThreadSharedProps,+ type CommentUser,+} from './types';++/** The thread a reply composer is open in, and the comment it answers. */+export type ReplyTarget = {+ parentId: string;+ comment: AnyComment;+ /** Set when the composer should take focus; each request has its own. */+ focusRequestId?: number;+ /** The mention the draft was seeded with, which the viewer did not type. */+ seed?: string;+};++export type EditTarget = {comment: AnyComment; value: string};++function replyComposerContext(target: ReplyTarget): CommentComposerContext {+ return {+ kind: 'reply',+ parentCommentId: target.parentId,+ repliedToCommentId: target.comment.id,+ };+}++function editComposerContext(comment: AnyComment): CommentComposerContext {+ return {kind: 'edit', commentId: comment.id};+}++/** A failed comment action and how to run it again. */+export type ActionFailure = {message: string; retry?: () => void};++type FocusTarget = 'reply' | 'actions' | 'history' | 'article' | 'thread';++/** Focus the control that replaces an interaction target after its state commits. */+function focusCommentTarget(+ commentId: string | null,+ target: FocusTarget,+ rootRef: RefObject<HTMLElement | null>,+): void {+ if (target === 'thread' || commentId == null) {+ rootRef.current?.focus();+ return;+ }+ const article = document.getElementById(commentAnchorId(commentId));+ const next =+ target === 'reply'+ ? (visibleCommentAction(article, 'reply') ??+ commentMoreMenuTrigger(article))+ : target === 'actions'+ ? commentMoreMenuTrigger(article)+ : target === 'history'+ ? article?.querySelector<HTMLElement>(+ '[data-metadata-action="history"]',+ )+ : article;+ (next ?? article ?? rootRef.current)?.focus();+}++/** Keep post-action focus in its originating handler (runtime INV2). */+function commitAndFocus(+ update: () => void,+ commentId: string | null,+ target: FocusTarget,+ rootRef: RefObject<HTMLElement | null>,+): void {+ flushSync(update);+ focusCommentTarget(commentId, target, rootRef);+}++type MaybePromise = void | Promise<void>;++const NO_AGENT_COMMANDS: readonly CommentAgentCommand[] = [];++export interface CommentsContextValue {+ currentUser?: CommentUser;+ mode: CommentMode;+ container: 'section' | 'card';+ /** The host's placeholder, or nothing for the localized defaults. */+ composerPlaceholder: string | undefined;+ reactionOptions: readonly CommentReactionOption[];+ highlightColor: CommentHighlightColor;+ agentCommands: readonly CommentAgentCommand[];+ composerTriggers?: readonly ChatComposerTrigger[];+ markdownPlugins?: readonly MarkdownPluginEntry[];+ markdownInlinePlugins?: readonly MarkdownInlinePlugin[];+ hasEmojiPicker: boolean;+ onUploadImages?: CommentImageUploader;+ renderAnchor?: CommentThreadSharedProps['renderAnchor'];+ renderBody?: CommentThreadSharedProps['renderBody'];+ renderAdditionalActions?: CommentThreadSharedProps['renderAdditionalActions'];+ renderComposer?: CommentThreadSharedProps['renderComposer'];+ /** Which actions the host handles. */+ can: {+ submit: boolean;+ saveEdit: boolean;+ delete: boolean;+ react: boolean;+ retry: boolean;+ loadVersions: boolean;+ resolve: boolean;+ reopen: boolean;+ };+ selectedThreadId: string | null;+ replyTarget: ReplyTarget | null;+ replyDraft: string;+ replyError?: string;+ editTarget: EditTarget | null;+ pendingActionIds: ReadonlySet<string>;+ actionErrors: Readonly<Record<string, ActionFailure>>;+ isSubmitting: boolean;+ isComposerActionPending: boolean;+ selectThread: (threadId: string | null) => void;+ startReply: (+ parentId: string,+ target: AnyComment,+ options?: {focus?: boolean},+ ) => void;+ changeReplyDraft: (value: string) => void;+ submitReply: (parentId: string, value: string) => void;+ cancelReply: (restoreFocus?: boolean) => void;+ startEdit: (comment: AnyComment) => void;+ changeEdit: (comment: AnyComment, value: string) => void;+ saveEdit: (comment: AnyComment, value: string) => void;+ cancelEdit: (restoreFocus?: boolean) => void;+ react: (+ comment: AnyComment,+ key: string,+ option?: CommentReactionOption,+ ) => void;+ resolve: (comment: AnyComment) => void;+ reopen: (comment: AnyComment) => void;+ retry: (comment: AnyComment) => void;+ requestDelete: (comment: AnyComment) => void;+ openHistory: (comment: AnyComment) => void;+ composerActionPendingChange: (isPending: boolean) => void;+}++const CommentsContext = createContext<CommentsContextValue | null>(null);++export const CommentsContextProvider = CommentsContext.Provider;++/** The nearest Comments or standalone CommentThread scope. */+export function useCommentsContext(): CommentsContextValue {+ const context = useContext(CommentsContext);+ if (context == null) {+ throw new Error(+ 'Comment rows render inside a Comments panel or a CommentThread.',+ );+ }+ return context;+}++export interface CommentsControllerOptions extends CommentThreadSharedProps {+ /** Controlled selection by thread id; `undefined` lets the scope own it. */+ selectedThreadId?: string | null;+ onSelectedThreadChange?: (threadId: string | null) => void;+ /** Threads in display order, to find who takes focus after a deletion. */+ roots: readonly CommentThreadData[];+ /** Takes focus when nothing nearer can, such as after the last deletion. */+ rootRef: RefObject<HTMLElement | null>;+}++export type SubmitResult = 'posted' | 'failed' | 'skipped';++/**+ * The interaction state behind a Comments panel or a standalone CommentThread.+ * The host owns the data and every mutation; this owns what the viewer is+ * doing with it.+ */+export function useCommentsController({+ currentUser,+ mode = 'interactive',+ container = 'section',+ composerPlaceholder,+ highlightColor = 'yellow',+ reactionOptions = DEFAULT_COMMENT_REACTIONS,+ agentCommands = NO_AGENT_COMMANDS,+ composerTriggers,+ markdownPlugins,+ markdownInlinePlugins,+ getReplyMention,+ hasEmojiPicker = true,+ isSubmitting = false,+ onComposerDraftChange,+ onSubmit,+ onSaveEdit,+ onDelete,+ onReact,+ onRetryComment,+ onResolveThread,+ onReopenThread,+ loadVersions,+ onUploadImages,+ renderAnchor,+ renderBody,+ renderVersionBody,+ renderAdditionalActions,+ renderComposer,+ selectedThreadId: selectedThreadIdProp,+ onSelectedThreadChange,+ roots,+ rootRef,+}: CommentsControllerOptions) {+ const [uncontrolledSelectedThreadId, setUncontrolledSelectedThreadId] =+ useState<string | null>(null);+ const isSelectionControlled = selectedThreadIdProp !== undefined;+ const selectedThreadId = isSelectionControlled+ ? selectedThreadIdProp+ : uncontrolledSelectedThreadId;+ // The last selection made by this surface. A different controlled value came+ // from the host and may need to synchronize the browser scroll position.+ const viewerSelectionRef = useRef<string | null>(selectedThreadId ?? null);+ const [replyTarget, setReplyTarget] = useState<ReplyTarget | null>(null);+ const [replyDraft, setReplyDraft] = useState('');+ const [replyError, setReplyError] = useState<string>();+ const [editTarget, setEditTarget] = useState<EditTarget | null>(null);+ const [pendingActionIds, setPendingActionIds] = useState<ReadonlySet<string>>(+ () => new Set(),+ );+ const [localSubmitPending, setLocalSubmitPending] = useState(false);+ const [pendingComposerActionCount, setPendingComposerActionCount] =+ useState(0);+ const [actionErrors, setActionErrors] = useState<+ Record<string, ActionFailure>+ >({});+ const [deleteTarget, setDeleteTarget] = useState<AnyComment | null>(null);+ const [deleteError, setDeleteError] = useState<string>();+ const [history, setHistory] = useState<HistoryState | null>(null);+ const replyFocusRequestRef = useRef(0);+ const announce = useAnnounce();+ const t = useTranslator();++ const reportDraftChange = (+ value: string,+ context: CommentComposerContext,+ ) => {+ onComposerDraftChange?.(value, context);+ };+ const clearReplyDraft = (target: ReplyTarget | null = replyTarget) => {+ if (target != null) {+ reportDraftChange('', replyComposerContext(target));+ }+ setReplyTarget(null);+ setReplyDraft('');+ setReplyError(undefined);+ };+ const clearEditDraft = (target: EditTarget | null = editTarget) => {+ if (target != null) {+ reportDraftChange('', editComposerContext(target.comment));+ }+ setEditTarget(null);+ };++ const setSelectedThreadId = (threadId: string | null) => {+ viewerSelectionRef.current = threadId;+ if (!isSelectionControlled) {+ setUncontrolledSelectedThreadId(threadId);+ }+ if (threadId !== selectedThreadId) {+ onSelectedThreadChange?.(threadId);+ }+ };++ // Synchronize a host-driven selection with the browser's scroll position.+ // Selection/open rendering is derived directly from selectedThreadId; this+ // Effect performs only the idempotent external DOM operation (runtime INV3).+ useEffect(() => {+ if (viewerSelectionRef.current === selectedThreadId) {+ return;+ }+ viewerSelectionRef.current = selectedThreadId;+ if (selectedThreadId != null) {+ document+ .getElementById(commentAnchorId(selectedThreadId))+ ?.scrollIntoView?.({block: 'nearest'});+ }+ }, [selectedThreadId]);++ const composerActionPendingChange = useCallback((isPending: boolean) => {+ setPendingComposerActionCount(count =>+ Math.max(0, count + (isPending ? 1 : -1)),+ );+ }, []);++ const clearActionError = (commentId: string) =>+ setActionErrors(previous => {+ if (!(commentId in previous)) {+ return previous;+ }+ const next = {...previous};+ delete next[commentId];+ return next;+ });++ const runCommentAction = async (+ commentId: string,+ action: () => MaybePromise,+ failureMessage: string,+ retry?: () => void,+ ): Promise<boolean> => {+ setPendingActionIds(previous => new Set(previous).add(commentId));+ clearActionError(commentId);+ try {+ await action();+ return true;+ } catch {+ setActionErrors(previous => ({+ ...previous,+ [commentId]: {+ message: failureMessage,+ retry:+ retry ??+ (() => void runCommentAction(commentId, action, failureMessage)),+ },+ }));+ return false;+ } finally {+ setPendingActionIds(previous => {+ const next = new Set(previous);+ next.delete(commentId);+ return next;+ });+ }+ };++ /** Posts a comment, or a reply when `parentId` names its thread. */+ const submit = async (+ content: string,+ parentId?: string,+ ): Promise<SubmitResult> => {+ if (onSubmit == null || content.trim() === '') {+ return 'skipped';+ }+ const submitted = content.trim();+ const submittedReplyTarget = parentId != null ? replyTarget : null;+ setLocalSubmitPending(true);+ if (parentId != null) {+ setReplyError(undefined);+ }+ try {+ await onSubmit(submitted, parentId);+ if (parentId != null) {+ const restoreFocus = shouldRestoreFocusFrom(+ document.getElementById(replyComposerId(parentId)),+ );+ if (restoreFocus) {+ commitAndFocus(+ () => clearReplyDraft(submittedReplyTarget),+ parentId,+ 'reply',+ rootRef,+ );+ } else {+ clearReplyDraft(submittedReplyTarget);+ }+ }+ return 'posted';+ } catch {+ if (parentId != null) {+ setReplyDraft(submitted);+ if (submittedReplyTarget != null) {+ reportDraftChange(+ submitted,+ replyComposerContext(submittedReplyTarget),+ );+ }+ setReplyError(t('@astryx.comments.replyFailed'));+ }+ return 'failed';+ } finally {+ setLocalSubmitPending(false);+ }+ };++ const saveEdit = async (comment: AnyComment, content: string) => {+ if (onSaveEdit == null || content.trim() === '') {+ return;+ }+ const saved = content.trim();+ const succeeded = await runCommentAction(+ comment.id,+ () => onSaveEdit(comment.id, saved),+ t('@astryx.comments.editFailed'),+ () => void saveEdit(comment, saved),+ );+ if (succeeded) {+ const restoreFocus = shouldRestoreFocusFrom(+ document.getElementById(commentAnchorId(comment.id)),+ );+ if (restoreFocus) {+ commitAndFocus(+ () => clearEditDraft({comment, value: saved}),+ comment.id,+ 'actions',+ rootRef,+ );+ } else {+ clearEditDraft({comment, value: saved});+ }+ } else {+ setEditTarget({comment, value: saved});+ reportDraftChange(saved, editComposerContext(comment));+ }+ };++ /** The neighbor that takes focus once `target` is deleted: a reply's+ * thread, else the next thread, else the previous one. */+ const focusTargetAfterDelete = (target: AnyComment): string | null => {+ const index = roots.findIndex(root => root.id === target.id);+ if (index === -1) {+ return (+ roots.find(root => root.replies?.some(reply => reply.id === target.id))+ ?.id ?? null+ );+ }+ return roots[index + 1]?.id ?? roots[index - 1]?.id ?? null;+ };++ const confirmDelete = async () => {+ if (deleteTarget == null || onDelete == null) {+ return;+ }+ const target = deleteTarget;+ const neighborId = focusTargetAfterDelete(target);+ setDeleteError(undefined);+ const succeeded = await runCommentAction(+ target.id,+ () => onDelete(target.id),+ t('@astryx.comments.deleteFailed'),+ // Retrying a delete asks for confirmation again.+ () => setDeleteTarget(target),+ );+ if (succeeded) {+ commitAndFocus(+ () => setDeleteTarget(null),+ neighborId,+ neighborId == null ? 'thread' : 'article',+ rootRef,+ );+ } else {+ // Announced from the failure itself, once, as the dialog's text changes.+ const message = t('@astryx.comments.deleteFailedRetry');+ setDeleteError(message);+ announce(message, 'assertive');+ }+ };++ const openHistory = async (comment: AnyComment) => {+ setHistory({+ comment,+ versions: comment.previousVersions ?? [],+ isLoading: loadVersions != null,+ });+ if (loadVersions == null) {+ return;+ }+ try {+ const versions = await loadVersions(comment.id);+ setHistory(current =>+ current?.comment.id === comment.id+ ? {...current, versions, isLoading: false}+ : current,+ );+ } catch {+ setHistory(current =>+ current?.comment.id === comment.id+ ? {+ ...current,+ isLoading: false,+ error: t('@astryx.comments.historyLoadFailed'),+ }+ : current,+ );+ }+ };++ const selectThread = (threadId: string | null) => {+ setSelectedThreadId(threadId);+ if (replyTarget != null && replyTarget.parentId !== threadId) {+ clearReplyDraft();+ }+ };++ const value: CommentsContextValue = {+ currentUser,+ mode,+ container,+ composerPlaceholder,+ reactionOptions,+ highlightColor,+ agentCommands,+ composerTriggers,+ markdownPlugins,+ markdownInlinePlugins,+ hasEmojiPicker,+ onUploadImages,+ renderAnchor,+ renderBody,+ renderAdditionalActions,+ renderComposer,+ can: {+ submit: onSubmit != null,+ saveEdit: onSaveEdit != null,+ delete: onDelete != null,+ react: onReact != null,+ retry: onRetryComment != null,+ loadVersions: loadVersions != null,+ resolve: onResolveThread != null,+ reopen: onReopenThread != null,+ },+ selectedThreadId,+ replyTarget,+ replyDraft,+ replyError,+ editTarget,+ pendingActionIds,+ actionErrors,+ isSubmitting: isSubmitting || localSubmitPending,+ isComposerActionPending: pendingComposerActionCount > 0,+ selectThread,+ startReply: (parentId, target, options) => {+ setSelectedThreadId(parentId);+ if (editTarget != null) {+ clearEditDraft();+ }+ const isNewTarget =+ replyTarget?.parentId !== parentId ||+ replyTarget.comment.id !== target.id;+ const seededMention =+ parentId === target.id || target.author.kind === 'agent'+ ? ''+ : (getReplyMention?.(target.author) ?? '');+ const nextTarget: ReplyTarget = {+ parentId,+ comment: target,+ focusRequestId:+ options?.focus === true ? ++replyFocusRequestRef.current : undefined,+ seed: isNewTarget ? seededMention : replyTarget?.seed,+ };+ if (isNewTarget) {+ if (replyTarget != null) {+ clearReplyDraft();+ }+ setReplyDraft(seededMention);+ if (seededMention !== '') {+ reportDraftChange(seededMention, replyComposerContext(nextTarget));+ }+ }+ setReplyError(undefined);+ setReplyTarget(nextTarget);+ },+ changeReplyDraft: value => {+ setReplyDraft(value);+ setReplyError(undefined);+ if (replyTarget != null) {+ reportDraftChange(value, replyComposerContext(replyTarget));+ }+ },+ submitReply: (parentId, value) => void submit(value, parentId),+ cancelReply: restoreFocus => {+ const parentId = replyTarget?.parentId;+ if (restoreFocus === true && parentId != null) {+ commitAndFocus(clearReplyDraft, parentId, 'reply', rootRef);+ } else {+ clearReplyDraft();+ }+ },+ startEdit: comment => {+ if (replyTarget != null) {+ clearReplyDraft();+ }+ if (editTarget != null && editTarget.comment.id !== comment.id) {+ clearEditDraft();+ }+ clearActionError(comment.id);+ setEditTarget({comment, value: comment.body});+ if (editTarget?.comment.id !== comment.id) {+ reportDraftChange(comment.body, editComposerContext(comment));+ }+ },+ changeEdit: (comment, value) => {+ setEditTarget({comment, value});+ clearActionError(comment.id);+ reportDraftChange(value, editComposerContext(comment));+ },+ saveEdit: (comment, value) => void saveEdit(comment, value),+ cancelEdit: restoreFocus => {+ const editedId = editTarget?.comment.id;+ if (restoreFocus === true && editedId != null) {+ commitAndFocus(clearEditDraft, editedId, 'actions', rootRef);+ } else {+ clearEditDraft();+ }+ },+ react: (comment, key, option) => {+ if (onReact == null) {+ return;+ }+ void runCommentAction(+ comment.id,+ () => onReact(comment.id, key, option),+ t('@astryx.comments.reactionFailed'),+ );+ },+ resolve: comment => {+ if (onResolveThread == null) {+ return;+ }+ void runCommentAction(+ comment.id,+ () => onResolveThread(comment.id),+ t('@astryx.comments.resolveFailed'),+ );+ },+ reopen: comment => {+ if (onReopenThread == null) {+ return;+ }+ void runCommentAction(+ comment.id,+ () => onReopenThread(comment.id),+ t('@astryx.comments.reopenFailed'),+ );+ },+ retry: comment => {+ if (onRetryComment == null) {+ return;+ }+ void runCommentAction(+ comment.id,+ () => onRetryComment(comment.id),+ t('@astryx.comments.retryFailed'),+ );+ },+ requestDelete: setDeleteTarget,+ openHistory: comment => void openHistory(comment),+ composerActionPendingChange,+ };++ const dialogs: ReactNode = (+ <>+ {deleteTarget != null && (+ <AlertDialog+ isOpen+ onOpenChange={open => {+ if (!open && !pendingActionIds.has(deleteTarget.id)) {+ const commentId = deleteTarget.id;+ // The dialog unmounts rather than closing, so commit that state+ // and restore focus from this originating handler (runtime INV2).+ commitAndFocus(+ () => {+ setDeleteTarget(null);+ setDeleteError(undefined);+ },+ commentId,+ 'actions',+ rootRef,+ );+ }+ }}+ title={t('@astryx.comments.deleteTitle')}+ description={+ deleteError ??+ t('@astryx.comments.deleteDescription', {+ name: deleteTarget.author.name,+ })+ }+ actionLabel={t('@astryx.comments.delete')}+ isActionLoading={pendingActionIds.has(deleteTarget.id)}+ onAction={() => void confirmDelete()}+ />+ )}+ <HistoryDialog+ history={history}+ onClose={() => {+ const commentId = history?.comment.id;+ if (commentId != null) {+ commitAndFocus(+ () => setHistory(null),+ commentId,+ 'history',+ rootRef,+ );+ } else {+ setHistory(null);+ }+ }}+ renderVersionBody={+ renderVersionBody ??+ (version => (+ <CommentMarkdown+ body={version.body}+ agentCommands={agentCommands}+ plugins={markdownPlugins}+ inlinePlugins={markdownInlinePlugins}+ />+ ))+ }+ />+ </>+ );++ return {value, dialogs, submit, announce};+}diff --git a/packages/lab/src/Comments/i18n.ts b/packages/lab/src/Comments/i18n.tsnew file mode 100644index 0000000000..00490849fc--- /dev/null+++ b/packages/lab/src/Comments/i18n.ts@@ -0,0 +1,40 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file i18n.ts+ * @input Uses the TranslatorFn type+ * @output Exports reactionDescription+ * @position Localized names for the Comments family's default reactions+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/Comments/types.ts (DEFAULT_COMMENT_REACTIONS)+ * - /packages/core/locales/en.json (@astryx.comments.reaction*)+ */++import type {TranslatorFn} from '@astryxdesign/core/i18n';+import type {CommentReactionOption} from './types';++/* Catalog keys for the names of DEFAULT_COMMENT_REACTIONS, by reaction key. */+const DEFAULT_REACTION_NAME_KEYS: Readonly<Record<string, string>> = {+ like: '@astryx.comments.reactionLike',+ love: '@astryx.comments.reactionLove',+ laugh: '@astryx.comments.reactionLaugh',+ wow: '@astryx.comments.reactionWow',+ sad: '@astryx.comments.reactionSad',+ celebrate: '@astryx.comments.reactionCelebrate',+};++/**+ * A reaction's human-readable name: the host's `description`, else the+ * localized name of a default reaction, else its glyph.+ */+export function reactionDescription(+ t: TranslatorFn,+ reaction: Pick<CommentReactionOption, 'key' | 'label' | 'description'>,+): string {+ if (reaction.description != null && reaction.description !== '') {+ return reaction.description;+ }+ const key = DEFAULT_REACTION_NAME_KEYS[reaction.key];+ return key != null ? t(key) : reaction.label;+}diff --git a/packages/lab/src/Comments/icons.tsx b/packages/lab/src/Comments/icons.tsxindex 668233de9c..48f30b65b0 100644--- a/packages/lab/src/Comments/icons.tsx+++ b/packages/lab/src/Comments/icons.tsx@@ -5,25 +5,36 @@/*** @file icons.tsx* @input Uses React, Icon, getExtendedIcon, and useThemeName- * @output Exports CommentComposer's owned icon keys and renderer- * @position Internal glyphs for the Lab CommentComposer+ * @output Exports COMMENT_ICON_KEYS and the CommentIcon renderer+ * @position Glyphs the Comments family owns: themeable by namespaced key,+ * with bundled inline defaults and no icon-library dependency+ *+ * A theme replaces any glyph by key:+ * defineTheme({icons: {'comment:reply': <MyReplyIcon />}})*/import type {SVGProps} from 'react';import {getExtendedIcon, Icon, type IconColor} from '@astryxdesign/core/Icon';import {useThemeName} from '@astryxdesign/core/theme';-/** Theme registry keys owned by CommentComposer. */+/** Stable icon-registry keys for the Comments family's glyphs. */export const COMMENT_ICON_KEYS = {+ addReaction: 'comment:addReaction',+ reply: 'comment:reply',+ copyLink: 'comment:copyLink',+ resolve: 'comment:resolve',+ edit: 'comment:edit',+ delete: 'comment:delete',attach: 'comment:attach',emoji: 'comment:emoji',} as const;-type CommentIconName = keyof typeof COMMENT_ICON_KEYS;+export type CommentIconName = keyof typeof COMMENT_ICON_KEYS;+type Glyph = (props: SVGProps<SVGSVGElement>) => React.JSX.Element;function glyph(paths: readonly string[]): Glyph {- function CommentComposerGlyph(props: SVGProps<SVGSVGElement>) {+ function CommentGlyph(props: SVGProps<SVGSVGElement>) {return (<svgxmlns="http://www.w3.org/2000/svg"@@ -40,13 +51,47 @@ function glyph(paths: readonly string[]): Glyph {</svg>);}- return CommentComposerGlyph;+ return CommentGlyph;}-const FALLBACK_GLYPHS: Record<CommentIconName, Glyph> = {+/** Glyphs the system registry already has: their keys fall back to it. */+const REGISTRY_FALLBACKS = {resolve: 'check'} as const;++/** Bundled defaults, drawn on a 24px grid with 1.5px strokes. */+const FALLBACK_GLYPHS: Record<+ Exclude<CommentIconName, keyof typeof REGISTRY_FALLBACKS>,+ Glyph+> = {+ // A smiling face with a plus at its upper end.+ addReaction: glyph([+ 'M20.5 12.5A8.5 8.5 0 1 1 11.5 3.5',+ 'M8.5 14.5a4 4 0 0 0 7 0',+ 'M9 10h.01M15 10h.01',+ 'M19 2.5v5M16.5 5h5',+ ]),+ // A speech bubble.+ reply: glyph([+ 'M4.5 5.5h15a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H10l-4.5 3.5v-3.5h-1a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z',+ ]),+ // Two chain links.+ copyLink: glyph([+ 'M10 14a4.5 4.5 0 0 0 6.36 0l3-3a4.5 4.5 0 0 0-6.36-6.36l-1.25 1.25',+ 'M14 10a4.5 4.5 0 0 0-6.36 0l-3 3a4.5 4.5 0 0 0 6.36 6.36l1.25-1.25',+ ]),+ // A pencil.+ edit: glyph(['M15.5 4.5l4 4L8 20H4v-4L15.5 4.5z', 'M13.5 6.5l4 4']),+ // A bin with a lid.+ delete: glyph([+ 'M4.5 6.5h15',+ 'M9.5 6.5v-2a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v2',+ 'M6.5 6.5l1 13a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1l1-13',+ 'M10.5 10.5v6M13.5 10.5v6',+ ]),+ // A paper clip.attach: glyph(['M19.5 11.5l-7.6 7.6a4.5 4.5 0 0 1-6.36-6.36l7.95-7.95a3 3 0 0 1 4.24 4.24l-7.6 7.6a1.5 1.5 0 0 1-2.12-2.12l7.07-7.07',]),+ // A smiling face.emoji: glyph(['M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z','M8.5 14.5a4 4 0 0 0 7 0',@@ -54,7 +99,10 @@ const FALLBACK_GLYPHS: Record<CommentIconName, Glyph> = {]),};-/** A composer glyph resolved through the active theme, with a bundled fallback. */+/**+ * A comment glyph at the icon slot's size: the active theme's icon for its+ * `comment:*` key when one is registered, else the bundled default.+ */export function CommentIcon({name,color = 'secondary',@@ -67,11 +115,9 @@ export function CommentIcon({const themeName = useThemeName();const key = COMMENT_ICON_KEYS[name];const hasOverride = getExtendedIcon(key, undefined, themeName) != null;- return (- <Icon- icon={hasOverride ? key : FALLBACK_GLYPHS[name]}- color={color}- size={size}- />- );+ const fallback =+ name in REGISTRY_FALLBACKS+ ? REGISTRY_FALLBACKS[name as keyof typeof REGISTRY_FALLBACKS]+ : FALLBACK_GLYPHS[name as keyof typeof FALLBACK_GLYPHS];+ return <Icon icon={hasOverride ? key : fallback} color={color} size={size} />;}diff --git a/packages/lab/src/Comments/index.ts b/packages/lab/src/Comments/index.tsindex 9ea20374b4..ddca9bcbd5 100644--- a/packages/lab/src/Comments/index.ts+++ b/packages/lab/src/Comments/index.ts@@ -3,20 +3,34 @@'use client';/**- * @file index.ts- * @input CommentComposer implementation and its public data types- * @output Exports the Lab CommentComposer surface- * @position CommentComposer entry point; re-exported by packages/lab/src/index.ts+ * @file Comments barrel export+ * @input Imports CommentThread, CommentComposer, and their public types+ * @output Exports the standalone Lab comment thread and composer surfaces+ * @position Comments-family entry point; re-exported by packages/lab/src/index.ts*/+export {CommentThread} from './CommentThread';+export type {CommentThreadProps} from './CommentThread';export {CommentComposer} from './CommentComposer';export type {CommentComposerProps} from './CommentComposer';+export {COMMENT_ICON_KEYS} from './icons';+export {DEFAULT_COMMENT_REACTIONS} from './types';export type {CommentAgentCommand,CommentAnchor,CommentComposerContext,CommentComposerRenderProps,+ CommentData,+ CommentStatus,CommentHighlightColor,CommentImageUploader,+ CommentMode,+ CommentProgress,+ CommentReaction,+ CommentReactionOption,+ CommentThreadData,+ CommentThreadSharedProps,CommentUploadedImage,+ CommentUser,+ CommentVersion,} from './types';diff --git a/packages/lab/src/Comments/types.ts b/packages/lab/src/Comments/types.tsindex 239e6558c9..d1af4a7d36 100644--- a/packages/lab/src/Comments/types.ts+++ b/packages/lab/src/Comments/types.ts@@ -2,32 +2,105 @@/*** @file types.ts- * @input No runtime dependencies- * @output Exports the data and callback types owned by CommentComposer- * @position Type contract for the Lab CommentComposer; later Comments-family- * components extend this shared vocabulary+ * @input Uses React types, ChatComposerTrigger, and Markdown plugin types+ * @output Exports the data, callback, and prop types shared by Comments,+ * CommentThread, and CommentComposer, and DEFAULT_COMMENT_REACTIONS+ * @position Type contract for the lab Comments family** SYNC: When modified, update these files to stay in sync:* - /packages/lab/src/Comments/index.ts (exports)- * - /packages/lab/src/Comments/CommentComposer.doc.mjs+ * - /packages/lab/src/Comments/Comments.doc.mjs+ * - /packages/lab/src/Comments/CommentThread.doc.mjs*/+import type {ReactNode} from 'react';+import type {+ ChatComposerTrigger,+ ChatMessageStatus,+} from '@astryxdesign/core/Chat';+import type {MarkdownInlinePlugin} from '@astryxdesign/core/Markdown';+import type {MarkdownPluginEntry} from '@astryxdesign/core/Markdown/plugins';++/**+ * `interactive` enables every permitted action; `non-editable` keeps create,+ * reply and react but removes edit and delete; `read-only` removes every+ * control that changes data.+ */+export type CommentMode = 'interactive' | 'non-editable' | 'read-only';++/** Whether a comment the viewer posted has reached the host. */+/**+ * Where a comment is in being posted, in Chat's message-status vocabulary:+ * `sending` while the post is in flight, `sent` once it has posted, and+ * `error` when it couldn't be posted.+ */+export type CommentStatus = Extract<+ ChatMessageStatus,+ 'sending' | 'sent' | 'error'+>;++/** A person or agent who writes comments, reacts, or acts on the item. */+export interface CommentUser {+ /** Stable host-owned id, used for equality ("is this my comment?"). */+ id: string;+ /** Full display name. Never a viewer-relative label such as "You". */+ name: string;+ /**+ * An agent shows its logo (`avatarUrl`), or square-cornered initials+ * without one, and an Agent badge beside its name.+ * @default 'person'+ */+ kind?: 'person' | 'agent';+ /** Where the author's name links, such as their profile. */+ href?: string;+ /** Profile picture, or an agent's square logo. Initials without one. */+ avatarUrl?: string;+}++/** A selectable reaction. */+export interface CommentReactionOption {+ /** Stable key the host stores, such as `like`. */+ key: string;+ /** Emoji or compact glyph shown in the picker and on the reaction. */+ label: string;+ /**+ * Human-readable name, such as "Like", for the reaction's accessible label+ * and tooltip. Optional for the keys in DEFAULT_COMMENT_REACTIONS, which+ * take their localized names.+ */+ description?: string;+}++/** A reaction summary on a comment. */+export interface CommentReaction extends CommentReactionOption {+ count: number;+ /** Whether the viewer is one of the people who reacted. */+ reactedByViewer?: boolean;+ /** Who reacted, named in the reaction's tooltip. */+ actors?: readonly Pick<CommentUser, 'id' | 'name'>[];+}+/*** The passage an inline comment discusses. The host owns anchoring (the text- * selection, offsets, and re-resolving them after edits); the composer quotes- * the passage without owning its coordinates.+ * selection, offsets, and re-resolving them after edits); the thread shows+ * the quote and its state.*/export interface CommentAnchor {- /** The selected text, quoted above the composer. */+ /** The selected text, quoted above the comment. */quote: string;/**- * `orphaned` when edits removed the passage.+ * `orphaned` when edits removed the passage: the thread stays, and its+ * quote shows with an Outdated badge.* @default 'anchored'*/status?: 'anchored' | 'orphaned';}-/** A palette color the host uses to connect a quoted passage to its highlight. */+/**+ * A color of the Astryx palette, as a host highlights inline comments'+ * passages in it. Quotes draw their rule in its `--color-border-<color>`+ * token so a quote and its passage read as one.+ */export type CommentHighlightColor =| 'blue'| 'cyan'@@ -48,7 +121,99 @@ export interface CommentUploadedImage {alt: string;}-/** Which comment workflow a composer callback belongs to. */+/** One version of a comment in its edit history. */+export interface CommentVersion {+ id: string;+ body: string;+ editedAt: string | number;+ author?: CommentUser;+ isCurrent?: boolean;+}++/**+ * What a comment's author, typically an agent, is doing while it still writes+ * the comment, and where to watch the work.+ */+export interface CommentProgress {+ /** What the author is doing, as a reader would say it: "Reading the file…". */+ label: string;+ /** Where to watch the work, such as the agent's session. */+ link?: {label: string; href: string};+}++/** A comment: a thread's first comment or one of its replies. */+export interface CommentData {+ id: string;+ author: CommentUser;+ /** Markdown. */+ body: string;+ createdAt: string | number;+ updatedAt?: string | number;+ /** Shows Edited beside the time; opens the edit history when there is one. */+ isEdited?: boolean;+ /** Host-owned unread state. Shows a New badge that fades after five seconds. */+ isUnread?: boolean;+ /** Earlier versions, newest first, when the host already has them. */+ previousVersions?: readonly CommentVersion[];+ /**+ * Host-controlled metadata for people who have seen this comment. Comments+ * does not render it by default; render callbacks receive it with the comment.+ * To associate each person once, attach them only to their newest seen comment.+ */+ seenBy?: readonly CommentUser[];+ reactions?: readonly CommentReaction[];+ /** @default 'sent' */+ status?: CommentStatus;+ /** Shown when `status` is `error`. */+ errorMessage?: string;+ /**+ * Marks a comment its author is still writing. The label shows in place of+ * the body, shimmering while motion is allowed, and is announced as a+ * polite status. The comment takes no reactions, replies, edits or+ * deletions, and has no link to copy, until it is written.+ */+ progress?: CommentProgress;+ /** Per-comment permission; the host stays authoritative. @default true */+ canReply?: boolean;+ /** @default true */+ canReact?: boolean;+ /** @default the viewer wrote it */+ canEdit?: boolean;+ /** @default the viewer wrote it */+ canDelete?: boolean;+}++/** A thread: its first comment, which carries the thread's replies. */+export interface CommentThreadData extends CommentData {+ /**+ * Other people currently composing in this thread. Controlled, transient+ * state: update it from your collaboration layer and expire stale entries+ * there. While this thread is open, the current viewer is not shown.+ */+ typingUsers?: readonly CommentUser[];+ /** One level of replies, oldest first. */+ replies?: readonly CommentData[];+ /** Makes this an inline comment: the passage its thread discusses. */+ anchor?: CommentAnchor;+ /** A resolved thread: Resolved beside the time, muted text, and Reopen. */+ isResolved?: boolean;+ /** Who resolved the thread, named in the Resolved label's tooltip. */+ resolvedBy?: CommentUser;+ /**+ * Calls the thread out without selecting it, such as the comment a playing+ * video has reached: it takes the selected thread's muted fill, and nothing+ * expands, scrolls, or takes focus.+ */+ isHighlighted?: boolean;+ /**+ * Whether the viewer may resolve or reopen this thread when the host+ * handles it. Its Resolved label shows either way.+ * @default true+ */+ canResolve?: boolean;+}++/** Which composer a callback came from. */export type CommentComposerContext =| {kind: 'comment';@@ -71,20 +236,145 @@ export interface CommentComposerRenderProps {onCancel?: () => void;}-/** An agent a comment can address with a slash command. */+/**+ * An agent a comment can address with a slash command: typing `/` in a+ * composer offers it, and a posted comment shows the command as its chip.+ */export interface CommentAgentCommand {- /** The command after the slash: `ask` for `/ask`. */+ /** The command after the slash: `ask` for `/ask`. Letters, digits, `-` and `_`. */command: string;- /** The agent's display name. */+ /** The agent's name, on its chip. */name: string;- /** What asking it does, shown in the slash-command menu. */+ /** What asking it does, in the `/` menu. */description: string;- /** Optional square logo; initials render without one. */+ /** Square agent logo; initials without one. */logoUrl?: string;}-/** Uploads images and returns their stored URLs and alt text. */+/** Uploads images for a composer and returns where they were stored. */export type CommentImageUploader = (files: readonly File[],context: CommentComposerContext,) => readonly CommentUploadedImage[] | Promise<readonly CommentUploadedImage[]>;++type MaybePromise = void | Promise<void>;++/**+ * Behavior and rendering shared by Comments and a standalone CommentThread.+ * Inside a Comments panel, its threads take these from the Comments.+ */+export interface CommentThreadSharedProps {+ /**+ * The viewer: their own comments get Edit and Delete, and their avatar sits+ * beside the reply composer. Authorization stays with the host.+ */+ currentUser?: CommentUser;+ /** @default 'interactive' */+ mode?: CommentMode;+ /**+ * The parent surface. `section` renders each thread as an outlined Card;+ * `card` renders divider-bounded Sections so cards never nest.+ * @default 'section'+ */+ container?: 'section' | 'card';+ /**+ * Placeholder of the new-comment composer. Defaults to the localized+ * "Write a comment…", with replies saying "Reply to <name>…"; a custom value+ * replaces both.+ */+ composerPlaceholder?: string;+ /**+ * The palette color the host highlights passages in.+ * @default 'yellow'+ */+ highlightColor?: CommentHighlightColor;+ /** @default DEFAULT_COMMENT_REACTIONS */+ reactionOptions?: readonly CommentReactionOption[];+ /** Agents a comment can address with a slash command. */+ agentCommands?: readonly CommentAgentCommand[];+ /** Typeahead triggers for every composer, such as an `@` people search. */+ composerTriggers?: readonly ChatComposerTrigger[];+ /** Markdown plugins for comment bodies, such as links for your own entities. */+ markdownPlugins?: readonly MarkdownPluginEntry[];+ /** Text-match renderers for comment bodies, such as the mentions your triggers insert. */+ markdownInlinePlugins?: readonly MarkdownInlinePlugin[];+ /**+ * Seeds a reply to a reply with a mention of its author, in whatever form+ * your mentions take. Return nothing to start the reply empty.+ */+ getReplyMention?: (author: CommentUser) => string | undefined;+ /**+ * Whether composers offer the emoji picker.+ * @default true+ */+ hasEmojiPicker?: boolean;+ /** Host-controlled pending state for a post or reply. */+ isSubmitting?: boolean;+ /**+ * Reports every draft owned by Comments or CommentThread: new comments,+ * replies, and edits. Programmatic seeds report their initial value; submit,+ * cancel, and target changes report an empty value for the closing context.+ * Use the context to route the update. A standalone CommentComposer already+ * exposes its controlled `value` and `onChange`.+ */+ onComposerDraftChange?: (+ value: string,+ context: CommentComposerContext,+ ) => void;+ /**+ * Posts a comment or a reply. Replies always receive their thread's first+ * comment as the parent, even when the viewer replied to a reply. A+ * rejected Promise restores the draft and shows an error with Retry.+ */+ onSubmit?: (content: string, parentCommentId?: string) => MaybePromise;+ onSaveEdit?: (commentId: string, content: string) => MaybePromise;+ /** Runs after the viewer confirms the deletion. */+ onDelete?: (commentId: string) => MaybePromise;+ /** Toggles the viewer's reaction. */+ onReact?: (+ commentId: string,+ reactionKey: string,+ option?: CommentReactionOption,+ ) => MaybePromise;+ /** Retries a comment whose `status` is `error`. */+ onRetryComment?: (commentId: string) => MaybePromise;+ /** Adds Mark as resolved to open threads. Update `isResolved` when it succeeds. */+ onResolveThread?: (commentId: string) => MaybePromise;+ /** Adds Reopen to resolved threads. */+ onReopenThread?: (commentId: string) => MaybePromise;+ /** Loads a comment's full edit history, newest first, current version included. */+ loadVersions?: (commentId: string) => Promise<readonly CommentVersion[]>;+ /**+ * Uploads images attached, pasted, or dropped in a composer and appends+ * them to the draft as Markdown images. Your upload endpoint must+ * authorize the viewer and validate the files.+ */+ onUploadImages?: CommentImageUploader;+ /** Replaces a thread's quoted anchor; return `defaultAnchor` to keep it. */+ renderAnchor?: (+ comment: CommentThreadData,+ defaultAnchor: ReactNode,+ ) => ReactNode;+ /** Replaces the Markdown body for product-owned content. */+ renderBody?: (comment: CommentData) => ReactNode;+ /** Replaces the Markdown body of an edit-history version. */+ renderVersionBody?: (version: CommentVersion) => ReactNode;+ /** Adds product-owned controls to a comment's header actions. */+ renderAdditionalActions?: (comment: CommentData) => ReactNode;+ /** Replaces the default composer while keeping its state and context. */+ renderComposer?: (props: CommentComposerRenderProps) => ReactNode;+}++/**+ * The reactions a thread offers when the host passes none: Like, Love, Haha,+ * Wow, Sad, and Celebrate, named in the viewer's language.+ */+export const DEFAULT_COMMENT_REACTIONS: readonly CommentReactionOption[] =+ Object.freeze([+ {key: 'like', label: '👍'},+ {key: 'love', label: '❤️'},+ {key: 'laugh', label: '😂'},+ {key: 'wow', label: '😮'},+ {key: 'sad', label: '😢'},+ {key: 'celebrate', label: '🎉'},+ ]);diff --git a/packages/lab/src/Comments/useCommentThreadDismissal.ts b/packages/lab/src/Comments/useCommentThreadDismissal.tsnew file mode 100644index 0000000000..9754df77c4--- /dev/null+++ b/packages/lab/src/Comments/useCommentThreadDismissal.ts@@ -0,0 +1,426 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useCommentThreadDismissal.ts+ * @input Uses React, the shared layer dismissal stack (useLayerDismissal), the+ * theme's motion and spacing tokens, the translator, and the Comments+ * controller's reply and edit drafts+ * @output Exports useCommentThreadDismissal, unsavedDraftOf, and their types+ * @position Light dismissal for a CommentThread whose host passes `onDismiss`.+ * A press outside the thread and an Escape no nested layer claimed both+ * request dismissal; while the thread holds an unsaved draft, the first+ * request shakes the thread, returns focus to the draft, and announces+ * instead, and the next consecutive one dismisses.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/Comments/CommentThread.tsx+ * - /packages/lab/src/Comments/CommentThread.doc.mjs+ * - /packages/lab/src/Comments/CommentThread.test.tsx+ * - /packages/core/locales/en.json (@astryx.comments.unsavedDraft)+ *+ * ## Why the thread owns the outside press+ *+ * A host surface with native light dismiss (`popover="auto"`) closes before+ * script can veto it, so nothing can keep it open for a draft. The host turns+ * its own light and Escape dismissal off and hands the decision to the thread+ * through `onDismiss`.+ *+ * ## Inside versus outside+ *+ * React synthetic events bubble through portals, so the thread root's+ * pointer-down capture handler sees every press inside the thread, including+ * presses in layers it opened (the emoji picker, typeahead and action menus,+ * the delete and history dialogs) wherever they render. It marks that event;+ * the document listener, which runs after React's root listener, judges any+ * unmarked press as outside. Presses on the host surface around the thread+ * (its padding, its fallback close control) are inside too.+ *+ * The press acts on its pointer-up, as native light dismiss does, so a touch+ * that becomes a scroll (`pointercancel`) never dismisses.+ *+ * ## One layer at a time+ *+ * The thread registers on the shared layer stack, deeper than its host, and+ * wraps its content so layers it opens register deeper still. An Escape goes+ * to the top-most layer only, and an outside press counts only while the+ * thread is that layer: with the emoji picker open, the picker's own light+ * dismiss takes the press and the thread ignores it.+ */++import {+ useEffect,+ useRef,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+} from 'react';+import type {AnnouncePoliteness} from '@astryxdesign/core/hooks';+import {useTranslator} from '@astryxdesign/core/i18n';+import {useLayerDismissal} from '@astryxdesign/core/Layer';+import {useTheme} from '@astryxdesign/core/theme';+import type {CommentsContextValue} from './CommentsContext';+import {commentAnchorId, replyComposerId} from './utils';++/** A reply or edit holding text the viewer would lose on dismissal. */+export type UnsavedDraft =+ | {kind: 'reply'; parentId: string; signature: string}+ | {kind: 'edit'; commentId: string; signature: string};++/**+ * The thread's unsaved draft, derived from the controller's state: a reply+ * holding more than its seeded mention, or an edit whose text differs from+ * the saved body. Whitespace alone is never a draft.+ */+export function unsavedDraftOf({+ replyTarget,+ replyDraft,+ editTarget,+}: Pick<+ CommentsContextValue,+ 'replyTarget' | 'replyDraft' | 'editTarget'+>): UnsavedDraft | null {+ if (+ editTarget != null &&+ editTarget.value.trim() !== editTarget.comment.body.trim()+ ) {+ return {+ kind: 'edit',+ commentId: editTarget.comment.id,+ signature: `edit:${editTarget.comment.id}:${editTarget.value}`,+ };+ }+ if (replyTarget != null) {+ const typed = replyDraft.trim();+ if (typed !== '' && typed !== (replyTarget.seed ?? '').trim()) {+ return {+ kind: 'reply',+ parentId: replyTarget.parentId,+ signature: `reply:${replyTarget.parentId}:${replyDraft}`,+ };+ }+ }+ return null;+}++type RequestOutcome = 'dismissed' | 'guarded';++export interface CommentThreadDismissalOptions {+ /** The host's dismissal; `undefined` turns the whole behavior off. */+ onDismiss: (() => void) | undefined;+ /** The thread root: the boundary, the shake target, and the stack container. */+ rootRef: RefObject<HTMLElement | null>;+ /** The draft a dismissal would discard, derived during render. */+ draft: UnsavedDraft | null;+ /** The controller's announcer. */+ announce: (message: string, politeness?: AnnouncePoliteness) => void;+}++export interface CommentThreadDismissalReturn {+ /** Whether the thread owns its dismissal, so its content nests a layer. */+ isEnabled: boolean;+ /** The root's pointer-down capture handler: marks the press as inside. */+ onRootPointerDownCapture: (event: ReactPointerEvent<HTMLElement>) => void;+}++const DRAFT_INPUT_SELECTOR = [+ '[contenteditable="true"]',+ '[role="textbox"]',+ 'textarea',+ 'input:not([type="hidden"]):not([type="file"])',+].join(', ');++const DEFAULT_SHAKE_DURATION_MS = 410;+const DEFAULT_SHAKE_DISTANCE = '4px';++function parseDuration(value: string | undefined): number | null {+ const normalized = value?.trim() ?? '';+ const amount = Number.parseFloat(normalized);+ if (!Number.isFinite(amount)) {+ return null;+ }+ if (normalized.endsWith('ms')) {+ return amount;+ }+ return normalized.endsWith('s') ? amount * 1000 : null;+}++/** The top-layer host surface the thread renders in, such as a Popover. */+function hostSurfaceOf(root: HTMLElement): HTMLElement | null {+ return root.parentElement?.closest<HTMLElement>('[popover]') ?? null;+}++/** The control that toggles `host`, found through its `aria-controls`. */+function hostTriggerOf(doc: Document, host: HTMLElement): Element | null {+ if (host.id === '') {+ return null;+ }+ for (const element of doc.querySelectorAll('[aria-controls]')) {+ if (+ element.getAttribute('aria-controls')?.split(/\s+/).includes(host.id) ===+ true+ ) {+ return element;+ }+ }+ return null;+}++/**+ * Swallow the next `type` event of this gesture when `owns` its target. Lets+ * go at the next press or key so it can never reach a later gesture.+ */+function claimNext(+ doc: Document,+ type: 'mousedown' | 'click',+ owns: (target: EventTarget | null) => boolean,+): void {+ const release = () => {+ doc.removeEventListener(type, claim, true);+ doc.removeEventListener('pointerdown', release, true);+ doc.removeEventListener('keydown', release, true);+ };+ const claim = (event: Event) => {+ release();+ if (owns(event.target)) {+ event.preventDefault();+ event.stopPropagation();+ }+ };+ doc.addEventListener(type, claim, true);+ doc.addEventListener('pointerdown', release, true);+ doc.addEventListener('keydown', release, true);+}++/** Focus the draft's input, keeping the viewer's caret or landing after the text. */+function focusDraftInput(root: HTMLElement, draft: UnsavedDraft): void {+ const doc = root.ownerDocument;+ const region = doc.getElementById(+ draft.kind === 'reply'+ ? replyComposerId(draft.parentId)+ : commentAnchorId(draft.commentId),+ );+ let input: HTMLElement | null = null;+ for (const candidate of region?.querySelectorAll<HTMLElement>(+ DRAFT_INPUT_SELECTOR,+ ) ?? []) {+ // A layer the composer opened (the picker's search field) is not the draft.+ const layer = candidate.closest('[popover], [role="dialog"]');+ if (layer == null || !region?.contains(layer)) {+ input = candidate;+ break;+ }+ }+ if (input == null) {+ root.focus();+ return;+ }+ const selection = doc.getSelection();+ const existing =+ selection != null &&+ selection.rangeCount > 0 &&+ input.contains(selection.getRangeAt(0).commonAncestorContainer)+ ? selection.getRangeAt(0).cloneRange()+ : null;+ input.focus();+ if (selection == null || input.getAttribute('contenteditable') !== 'true') {+ return;+ }+ // A bare focus() collapses an editable's caret to its start; restore the+ // viewer's caret, or land after the draft.+ let range = existing;+ if (range == null) {+ range = doc.createRange();+ range.selectNodeContents(input);+ range.collapse(false);+ }+ selection.removeAllRanges();+ selection.addRange(range);+}++function prefersReducedMotion(element: HTMLElement): boolean {+ return (+ element.ownerDocument.defaultView?.matchMedia?.(+ '(prefers-reduced-motion: reduce)',+ ).matches === true+ );+}++/**+ * Own light dismissal for a CommentThread: outside presses and unclaimed+ * Escape presses request it, and an unsaved draft turns the first request+ * into a shake, a focus move, and a polite announcement.+ */+export function useCommentThreadDismissal({+ onDismiss,+ rootRef,+ draft,+ announce,+}: CommentThreadDismissalOptions): CommentThreadDismissalReturn {+ const t = useTranslator();+ const {tokens} = useTheme();+ const isEnabled = onDismiss != null;+ // The draft the last request guarded. The next request dismisses only while+ // the draft still matches it; an edit or a press inside clears it.+ const guardedSignatureRef = useRef<string | null>(null);+ // The pointer-down the root last saw, compared by identity so a press whose+ // native propagation stopped short of the document cannot leak forward.+ const insidePressRef = useRef<Event | null>(null);+ const shakeRef = useRef<Animation | null>(null);++ const shake = (root: HTMLElement) => {+ shakeRef.current?.cancel();+ shakeRef.current = null;+ const duration =+ parseDuration(tokens['--duration-medium']) ?? DEFAULT_SHAKE_DURATION_MS;+ if (+ duration <= 0 ||+ typeof root.animate !== 'function' ||+ prefersReducedMotion(root)+ ) {+ return;+ }+ // Symmetric about the resting position, so it reads the same in RTL.+ const distance = tokens['--spacing-1'] ?? DEFAULT_SHAKE_DISTANCE;+ const at = (factor: number) => ({+ transform: `translateX(calc(${distance} * ${factor}))`,+ });+ try {+ const animation = root.animate(+ [at(0), at(-1), at(1), at(-0.5), at(0.5), at(0)],+ {duration, easing: 'ease-in-out', composite: 'add'},+ );+ shakeRef.current = animation;+ const forget = () => {+ if (shakeRef.current === animation) {+ shakeRef.current = null;+ }+ };+ animation.addEventListener('finish', forget);+ animation.addEventListener('cancel', forget);+ } catch {+ // Motion is progressive enhancement; focus and the announcement remain.+ }+ };++ const request = (): RequestOutcome => {+ if (draft == null || guardedSignatureRef.current === draft.signature) {+ guardedSignatureRef.current = null;+ onDismiss?.();+ return 'dismissed';+ }+ guardedSignatureRef.current = draft.signature;+ const root = rootRef.current;+ if (root != null) {+ shake(root);+ focusDraftInput(root, draft);+ }+ announce(t('@astryx.comments.unsavedDraft'), 'polite');+ return 'guarded';+ };++ // The document listeners run outside render and reach the latest draft+ // through this ref, as the composer's own listeners do.+ const latestRef = useRef<{+ request: () => RequestOutcome;+ wouldGuard: () => boolean;+ } | null>(null);+ latestRef.current = {+ request,+ wouldGuard: () =>+ draft != null && guardedSignatureRef.current !== draft.signature,+ };++ const {shouldDismissOnCloseRequest} = useLayerDismissal({+ isActive: isEnabled,+ onDismiss: () => void latestRef.current?.request(),+ getContainer: () => rootRef.current,+ });++ // External subscription: outside presses on the thread's document.+ useEffect(() => {+ if (!isEnabled) {+ return;+ }+ const doc = rootRef.current?.ownerDocument ?? document;+ let pending: {pointerId: number; trigger: Element | null} | null = null;++ const handlePointerDown = (event: PointerEvent) => {+ pending = null;+ const insidePress = insidePressRef.current;+ insidePressRef.current = null;+ if (insidePress === event || !event.isPrimary || event.button !== 0) {+ return;+ }+ const root = rootRef.current;+ const target = event.target;+ if (root == null || !(target instanceof Node) || root.contains(target)) {+ return;+ }+ const host = hostSurfaceOf(root);+ if (host?.contains(target) === true) {+ return;+ }+ // A layer above the thread (an open picker or menu) takes this press+ // through its own light dismiss.+ if (!shouldDismissOnCloseRequest()) {+ return;+ }+ const trigger = host == null ? null : hostTriggerOf(doc, host);+ pending = {+ pointerId: event.pointerId,+ trigger: trigger?.contains(target) === true ? trigger : null,+ };+ // A guarded press keeps focus and selection where they are.+ if (latestRef.current?.wouldGuard() === true) {+ claimNext(doc, 'mousedown', () => true);+ }+ };++ const handlePointerUp = (event: PointerEvent) => {+ if (pending == null || event.pointerId !== pending.pointerId) {+ return;+ }+ const {trigger} = pending;+ pending = null;+ if (latestRef.current?.request() === 'guarded') {+ // The press was spent on the warning; it activates nothing.+ claimNext(doc, 'click', () => true);+ } else if (trigger != null) {+ // The host's trigger would reopen the surface this press just closed.+ claimNext(+ doc,+ 'click',+ target => target instanceof Node && trigger.contains(target),+ );+ }+ };++ const handlePointerCancel = (event: PointerEvent) => {+ if (pending?.pointerId === event.pointerId) {+ pending = null;+ }+ };++ doc.addEventListener('pointerdown', handlePointerDown);+ doc.addEventListener('pointerup', handlePointerUp, true);+ doc.addEventListener('pointercancel', handlePointerCancel, true);+ return () => {+ doc.removeEventListener('pointerdown', handlePointerDown);+ doc.removeEventListener('pointerup', handlePointerUp, true);+ doc.removeEventListener('pointercancel', handlePointerCancel, true);+ };+ }, [isEnabled, rootRef, shouldDismissOnCloseRequest]);++ return {+ isEnabled,+ onRootPointerDownCapture: event => {+ if (!isEnabled) {+ return;+ }+ insidePressRef.current = event.nativeEvent;+ // A press inside re-arms the guard.+ guardedSignatureRef.current = null;+ },+ };+}diff --git a/packages/lab/src/Comments/utils.ts b/packages/lab/src/Comments/utils.tsindex 9eeea4dd47..ed141d7341 100644--- a/packages/lab/src/Comments/utils.ts+++ b/packages/lab/src/Comments/utils.ts@@ -2,14 +2,44 @@/*** @file utils.ts- * @input Uploaded-image records and controlled draft strings- * @output Exports CommentComposer's Markdown serialization and draft helpers- * @position Internal pure helpers for the Lab CommentComposer+ * @input Comment data types+ * @output Exports the comment family's pure helpers: element ids, Markdown+ * serialization of images, draft appends, and focus bookkeeping+ * @position Internal helpers shared by CommentThread and CommentComposer; not+ * exported from the package*/-import type {CommentUploadedImage} from './types';+import type {+ CommentData,+ CommentThreadData,+ CommentUploadedImage,+} from './types';-/** Alt text that cannot break out of Markdown's image brackets. */+/** A thread's first comment or one of its replies. */+export type AnyComment = CommentData | CommentThreadData;++/** The element id a comment's permalink points at. */+export function commentAnchorId(commentId: string): string {+ return `comment-${encodeURIComponent(commentId)}`;+}++/** The element id of a thread's reply composer. */+export function replyComposerId(parentId: string): string {+ return `${commentAnchorId(parentId)}-reply-composer`;+}++/** Whether focus is inside `region`, or already lost to <body>. */+export function shouldRestoreFocusFrom(region: Element | null): boolean {+ const active = document.activeElement;+ return (+ active == null ||+ active === document.body ||+ (region != null && region.contains(active))+ );+}++/** Alt text that cannot break out of Markdown's image brackets; `fallback`+ * (already localized) stands in for an image with none. */export function safeImageAlt(alt: string, fallback: string): string {return alt.replace(/[[\]\r\n]+/g, ' ').trim() || fallback;}@@ -27,7 +57,8 @@ export function safeMarkdownImageUrl(url: string): string {);}-/** Uploaded images as Markdown, one paragraph each. */+/** Uploaded images as Markdown, one paragraph each. `fallbackAlt` (already+ * localized) names an image uploaded without alt text. */export function imagesToMarkdown(images: readonly CommentUploadedImage[],fallbackAlt: string,@@ -53,3 +84,16 @@ export function appendDraftInline(value: string, content: string): string {}return `${value} ${content}`;}++/**+ * A pointer press opens a thread into its reply composer; a key press keeps+ * focus where it is, so the same key can close the thread again.+ */+export type ActivationSource = 'pointer' | 'keyboard';++/** Keyboard and assistive-technology clicks carry no click count. */+export function activationSourceOf(event?: {+ detail?: number;+}): ActivationSource {+ return (event?.detail ?? 1) > 0 ? 'pointer' : 'keyboard';+}diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 3d543e1750..71539fe1a3 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -40,17 +40,31 @@ export {type CommentPinProps,} from './CommentPin';-// CommentComposer — controlled composer for new comments, replies, and edits+// CommentThread and CommentComposer — standalone comment conversation surfacesexport {+ CommentThread,+ type CommentThreadProps,CommentComposer,type CommentComposerProps,+ DEFAULT_COMMENT_REACTIONS,+ COMMENT_ICON_KEYS,type CommentAgentCommand,type CommentAnchor,type CommentComposerContext,type CommentComposerRenderProps,+ type CommentData,+ type CommentStatus,type CommentHighlightColor,type CommentImageUploader,+ type CommentMode,+ type CommentProgress,+ type CommentReaction,+ type CommentReactionOption,+ type CommentThreadData,+ type CommentThreadSharedProps,type CommentUploadedImage,+ type CommentUser,+ type CommentVersion,} from './Comments';// TransferList — controlled dual-panel collection input