Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): add Comments (#7551)

Ernest5c75a7550717
diff --git a/.changeset/lab-comments-catalog.md b/.changeset/lab-comments-catalog.md
new file mode 100644
index 0000000000..e2a16553c6
--- /dev/null
+++ b/.changeset/lab-comments-catalog.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] i18n catalog: add the English messages used by the Lab Comments panel for its region, empty/loading states, pagination, and posting errors.
+
+@ernestt
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 6d00127e6d..dc2cdcd95f 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -361,5 +361,9 @@
{
"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."
+ },
+ {
+ "component": "lab/Comments",
+ "reason": "Comments is a block-axis timeline of CommentThread rows and activity events inside the core ChatLayout and ChatMessageList, with the composer docked on the block axis. It adds no horizontal positioning, directional glyphs, or arrow-key behavior of its own: rows, rails, and dividers use logical properties, and the load-earlier control and error Banners are centered or full width."
}
]
diff --git a/apps/storybook/stories/Comments.stories.tsx b/apps/storybook/stories/Comments.stories.tsx
index eb98a0232e..bf51838f1b 100644
--- a/apps/storybook/stories/Comments.stories.tsx
+++ b/apps/storybook/stories/Comments.stories.tsx
@@ -1,23 +1,31 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import type {Meta, StoryObj} from '@storybook/react';
+import {Card} from '@astryxdesign/core/Card';
import {VStack} from '@astryxdesign/core/Layout';
+import {Popover} from '@astryxdesign/core/Popover';
+import {Button} from '@astryxdesign/core/Button';
import {
CommentThread,
+ Comments,
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';
+import CommentsShowcase from '../../../packages/lab/blocks/CommentsShowcase';
const meta: Meta = {
title: 'Lab/Comments',
tags: ['autodocs'],
- parameters: {layout: 'centered'},
+ parameters: {
+ layout: 'centered',
+ },
};
export default meta;
+
type Story = StoryObj;
const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};
@@ -25,33 +33,91 @@ 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 />,
+const COMMENTS: readonly 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',
+ },
+ ],
+ },
+ {
+ id: 'second',
+ author: VIEWER,
+ body: 'I added the guardrail dashboard to the summary.',
+ createdAt: '2026-09-30T19:20:00Z',
+ },
+];
+
+/** Every feature, with working callbacks. */
+export const Panel: Story = {
+ render: () => (
+ <VStack width={920} height={640}>
+ <CommentsShowcase />
+ </VStack>
+ ),
+};
+
+/** Inside a card, threads are divider-bounded Sections so cards never nest. */
+export const InsideACard: Story = {
+ render: () => (
+ <Card padding={0} width={380} height={440}>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ container="card"
+ density="compact"
+ onSubmit={() => {}}
+ />
+ </Card>
+ ),
+};
+
+/** Readers see reactions and replies, and no control that changes data. */
+export const ReadOnly: Story = {
+ render: () => (
+ <VStack width={560} height={320}>
+ <Comments comments={COMMENTS} mode="read-only" density="compact" />
+ </VStack>
+ ),
+};
+
+export const Loading: Story = {
+ render: () => (
+ <VStack width={560} height={420}>
+ <Comments
+ comments={[]}
+ isLoading
+ currentUser={VIEWER}
+ density="compact"
+ onSubmit={() => {}}
+ />
+ </VStack>
+ ),
+};
+
+export const Empty: Story = {
+ render: () => (
+ <VStack width={560} height={320}>
+ <Comments comments={[]} currentUser={VIEWER} onSubmit={() => {}} />
+ </VStack>
+ ),
};
/** One thread on its own: a margin comment beside a document. */
@@ -67,12 +133,12 @@ export const InPopover: Story = {
render: () => <CommentThreadInPopover />,
};
-/** A host-opened thread reveals its body and replies without moving focus. */
+/** A lone thread a reader opened, with its replies showing. */
export const OpenThread: Story = {
render: () => (
<VStack width={480}>
<CommentThread
- comment={THREAD}
+ comment={COMMENTS[0]}
currentUser={VIEWER}
isSelected
onSubmit={() => {}}
@@ -88,7 +154,7 @@ export const LiveState: Story = {
<VStack width={480}>
<CommentThread
comment={{
- ...THREAD,
+ ...COMMENTS[0],
typingUsers: [JORDAN, SAM],
seenBy: [JORDAN, SAM],
replies: [
@@ -108,3 +174,106 @@ export const LiveState: Story = {
</VStack>
),
};
+
+export const Composer: Story = {
+ render: () => <CommentComposerShowcase />,
+};
+
+/** Loading failed: an error Banner with Retry above the threads. */
+export const LoadError: Story = {
+ render: () => (
+ <VStack width={560} height={360}>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ loadError="Check your connection and try again."
+ onRetryLoad={() => new Promise(resolve => setTimeout(resolve, 800))}
+ hasOlderComments
+ onLoadOlder={() => Promise.reject(new Error('offline'))}
+ density="compact"
+ onSubmit={() => {}}
+ />
+ </VStack>
+ ),
+};
+
+const LONG_NAME: CommentUser = {
+ id: 'long',
+ name: 'Maximiliana Alejandra Rodríguez-Vanderberg',
+};
+
+/** Long names, unbroken words, and long bodies wrap rather than overflow. */
+export const LongContent: Story = {
+ render: () => (
+ <VStack width={420} height={560}>
+ <Comments
+ comments={[
+ {
+ id: 'long-root',
+ author: LONG_NAME,
+ body: 'Supercalifragilisticexpialidocious-configuration-flag-name-that-never-breaks is still on in the canary. The rollout notes say the final cohort completes in two days, but the dashboard shows three, and the guardrail metrics have not settled for the last two regions, so I would hold the next step until the on-call confirms the numbers and the review queue is clear.',
+ createdAt: '2026-09-30T19:00:00Z',
+ isEdited: true,
+ anchor: {
+ quote:
+ 'The final cohort completes rollout in two days, after the guardrail metrics settle in every region and the review queue is clear.',
+ },
+ replies: [
+ {
+ id: 'long-reply',
+ author: VIEWER,
+ body: 'https://example.com/a/very/long/link/that/keeps/going/and/going/without/any/spaces/at/all',
+ createdAt: '2026-09-30T19:10:00Z',
+ },
+ ],
+ },
+ ]}
+ currentUser={VIEWER}
+ density="compact"
+ selectedThreadId="long-root"
+ onSelectedThreadChange={() => {}}
+ onSubmit={() => {}}
+ />
+ </VStack>
+ ),
+};
+
+/** At 320 CSS pixels the header actions collapse into the more menu. */
+export const Narrow: Story = {
+ render: () => (
+ <VStack width={320} height={520}>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ density="compact"
+ onSubmit={() => {}}
+ onReact={() => {}}
+ onResolveThread={() => {}}
+ onSaveEdit={() => {}}
+ onDelete={() => {}}
+ />
+ </VStack>
+ ),
+};
+
+/** Embedded at its content height inside a popover: no scroll area or dock. */
+export const EmbeddedInAPopover: Story = {
+ render: () => (
+ <Popover
+ label="Comments"
+ width={380}
+ padding={0}
+ content={
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ layout="embedded"
+ container="card"
+ density="compact"
+ onSubmit={() => {}}
+ />
+ }>
+ <Button label="Show comments" />
+ </Popover>
+ ),
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index d0e9e537e7..818d52658b 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -571,6 +571,11 @@
"path": "components/lab/comment-thread",
"aliases": []
},
+ {
+ "name": "component-lab-comments",
+ "path": "components/lab/comments",
+ "aliases": []
+ },
{
"name": "component-lab-diff-viewer",
"path": "components/lab/diff-viewer",
@@ -1910,6 +1915,16 @@
"path": "examples/comment-thread/in-a-popover",
"aliases": []
},
+ {
+ "name": "example-comments-inline-comments",
+ "path": "examples/comments/inline-comments",
+ "aliases": []
+ },
+ {
+ "name": "example-comments-inside-a-card",
+ "path": "examples/comments/inside-a-card",
+ "aliases": []
+ },
{
"name": "example-complex-selector-deadline-picker",
"path": "examples/complex-selector/deadline-picker",
@@ -4280,6 +4295,11 @@
"path": "showcases/comment-thread/margin-comment",
"aliases": []
},
+ {
+ "name": "showcase-comments-panel",
+ "path": "showcases/comments/panel",
+ "aliases": []
+ },
{
"name": "showcase-complex-selector-default",
"path": "showcases/complex-selector/default",
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index be46e30b33..e1da4a52f5 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -2046,5 +2046,45 @@
"@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."
+ },
+ "@astryx.comments.commentsLabel": {
+ "defaultMessage": "Threads in {label}",
+ "description": "Accessible name of the scrolling list of comment threads in a lab Comments panel. `label` is the panel's own accessible name, e.g. \"Comments\" or \"Launch plan\"."
+ },
+ "@astryx.comments.emptyDescription": {
+ "defaultMessage": "Start the discussion with a comment.",
+ "description": "Description under the empty-state title of a lab Comments panel when the viewer can comment."
+ },
+ "@astryx.comments.emptyReadOnlyDescription": {
+ "defaultMessage": "There is no discussion on this item.",
+ "description": "Description under the empty-state title of a lab Comments panel the viewer can only read."
+ },
+ "@astryx.comments.emptyTitle": {
+ "defaultMessage": "No comments yet",
+ "description": "Title of the empty state of a lab Comments panel with no comments or activity."
+ },
+ "@astryx.comments.label": {
+ "defaultMessage": "Comments",
+ "description": "Default accessible name of the lab Comments region, which holds the comment threads about one item. Hosts usually override it with the item's own noun."
+ },
+ "@astryx.comments.loadFailed": {
+ "defaultMessage": "Comments couldn't load",
+ "description": "Error Banner title in a lab Comments panel when its comments failed to load."
+ },
+ "@astryx.comments.loadOlder": {
+ "defaultMessage": "Load earlier comments",
+ "description": "Button above the threads of a lab Comments panel that loads the previous page of comments."
+ },
+ "@astryx.comments.loading": {
+ "defaultMessage": "Loading comments",
+ "description": "Visually hidden text read by screen readers while a lab Comments panel shows comment-shaped loading placeholders."
+ },
+ "@astryx.comments.olderFailed": {
+ "defaultMessage": "Earlier comments couldn't load",
+ "description": "Error Banner title in a lab Comments panel when the page of earlier comments failed to load; a Retry action follows."
+ },
+ "@astryx.comments.postFailed": {
+ "defaultMessage": "Your comment couldn't be posted.",
+ "description": "Error shown above the new-comment composer of a lab Comments panel when posting failed; the draft is kept and a Retry action follows."
}
}
diff --git a/packages/lab/blocks/CommentsInCard.doc.mjs b/packages/lab/blocks/CommentsInCard.doc.mjs
new file mode 100644
index 0000000000..70c9adbc61
--- /dev/null
+++ b/packages/lab/blocks/CommentsInCard.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Inside a card',
+ displayName: 'Inside a card',
+ description:
+ 'Set container="card" on a card parent: threads become divider-bounded Sections, so cards never nest, and the composer docks at the bottom of the card.',
+ exampleFor: 'Comments',
+ isReady: true,
+ aspectRatio: 3 / 4,
+ componentsUsed: ['Comments', 'Card'],
+};
diff --git a/packages/lab/blocks/CommentsInCard.tsx b/packages/lab/blocks/CommentsInCard.tsx
new file mode 100644
index 0000000000..b75260adef
--- /dev/null
+++ b/packages/lab/blocks/CommentsInCard.tsx
@@ -0,0 +1,78 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input Controlled comments and a post callback
+ * @output A compact Comments panel filling a Card, its threads divider-bounded
+ * Sections so cards never nest
+ * @position Copyable Lab Comments example
+ */
+
+import {useState} from 'react';
+import {Card} from '@astryxdesign/core/Card';
+import {
+ Comments,
+ type CommentThreadData,
+ type CommentUser,
+} from '@astryxdesign/lab';
+
+const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};
+const MAYA: CommentUser = {id: 'maya', name: 'Maya Chen'};
+
+const INITIAL_COMMENTS: readonly CommentThreadData[] = [
+ {
+ id: 'kickoff',
+ author: MAYA,
+ body: 'Can you review the rollout plan before Friday?',
+ createdAt: '2026-09-30T19:00:00Z',
+ replies: [
+ {
+ id: 'kickoff-reply',
+ author: VIEWER,
+ body: 'On it. I will leave notes on the final cohort.',
+ createdAt: '2026-09-30T19:12:00Z',
+ },
+ ],
+ },
+ {
+ id: 'dashboard',
+ author: VIEWER,
+ body: 'I added the guardrail dashboard to the summary.',
+ createdAt: '2026-09-30T19:20:00Z',
+ },
+];
+
+export default function CommentsInCard() {
+ const [comments, setComments] = useState(INITIAL_COMMENTS);
+ const post = (body: string, parentId?: string) => {
+ const comment = {
+ id: `comment-${Date.now()}`,
+ author: VIEWER,
+ body,
+ createdAt: new Date().toISOString(),
+ };
+ setComments(current =>
+ parentId == null
+ ? [...current, comment]
+ : current.map(root =>
+ root.id === parentId
+ ? {...root, replies: [...(root.replies ?? []), comment]}
+ : root,
+ ),
+ );
+ };
+
+ return (
+ <Card padding={0} width={380} height={460}>
+ <Comments
+ label="Rollout plan"
+ comments={comments}
+ currentUser={VIEWER}
+ container="card"
+ density="compact"
+ onSubmit={post}
+ />
+ </Card>
+ );
+}
diff --git a/packages/lab/blocks/CommentsInline.doc.mjs b/packages/lab/blocks/CommentsInline.doc.mjs
new file mode 100644
index 0000000000..1edd39bccb
--- /dev/null
+++ b/packages/lab/blocks/CommentsInline.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Inline comments',
+ displayName: 'Inline comments',
+ description:
+ 'A realistic Markdown document review with highlighted passages synchronized to a Comments side panel. Selecting an unannotated passage starts a quoted thread; replies and resolution update host-owned data.',
+ exampleFor: 'Comments',
+ isReady: true,
+ aspectRatio: 3 / 2,
+ componentsUsed: ['Button', 'Card', 'Comments', 'HStack', 'Text', 'VStack'],
+};
diff --git a/packages/lab/blocks/CommentsInline.tsx b/packages/lab/blocks/CommentsInline.tsx
new file mode 100644
index 0000000000..cffc4cfde6
--- /dev/null
+++ b/packages/lab/blocks/CommentsInline.tsx
@@ -0,0 +1,297 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input A Markdown-like document, its anchored threads, and controlled
+ * document/thread selection
+ * @output A realistic document review: highlighted passages stay synchronized
+ * with a Comments side panel, and a selected passage starts a quoted thread
+ * @position Copyable Lab Comments inline-comments example
+ */
+
+import {useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {
+ borderVars,
+ colorVars,
+ focusVars,
+ radiusVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {
+ Comments,
+ type CommentAnchor,
+ type CommentData,
+ type CommentThreadData,
+ type CommentUser,
+} from '@astryxdesign/lab';
+
+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 ROLLOUT_PASSAGE =
+ 'The final cohort completes rollout in three days after the dry run.';
+const GUARDRAIL_PASSAGE =
+ 'Pause if the 95th percentile exceeds 420 ms for two consecutive checks.';
+const REVIEW_PASSAGE =
+ 'Publish the review note after the final cohort is complete.';
+
+const INITIAL_COMMENTS: readonly CommentThreadData[] = [
+ {
+ id: 'rollout-window',
+ author: MAYA,
+ body: 'Can we make the dry-run dependency explicit? It explains the extra day.',
+ createdAt: '2026-10-14T17:18:00Z',
+ anchor: {quote: ROLLOUT_PASSAGE},
+ replies: [
+ {
+ id: 'rollout-reply',
+ author: VIEWER,
+ body: 'Updated. The window now starts after the dry run finishes.',
+ createdAt: '2026-10-14T17:31:00Z',
+ },
+ ],
+ },
+ {
+ id: 'latency-threshold',
+ author: JORDAN,
+ body: 'This matches the alert. I would keep the two-check window to avoid pausing on a single spike.',
+ createdAt: '2026-10-14T18:04:00Z',
+ anchor: {quote: GUARDRAIL_PASSAGE},
+ isUnread: true,
+ },
+];
+
+const styles = stylex.create({
+ passage: {
+ appearance: 'none',
+ backgroundColor: colorVars['--color-background-yellow'],
+ borderStyle: 'solid',
+ borderWidth: 0,
+ borderBlockEndWidth: borderVars['--border-width'],
+ borderBlockEndColor: 'transparent',
+ borderRadius: radiusVars['--radius-inner'],
+ color: 'inherit',
+ cursor: 'pointer',
+ font: 'inherit',
+ lineHeight: 'inherit',
+ marginInline: spacingVars['--spacing-0-5'],
+ paddingBlock: 0,
+ paddingInline: spacingVars['--spacing-0-5'],
+ textAlign: 'start',
+ outlineStyle: {
+ default: 'none',
+ ':focus-visible': focusVars['--focus-outline-style'],
+ },
+ outlineWidth: focusVars['--focus-outline-width'],
+ outlineColor: focusVars['--focus-outline-color'],
+ outlineOffset: focusVars['--focus-outline-offset'],
+ },
+ selectedPassage: {
+ borderBlockEndColor: colorVars['--color-border-yellow'],
+ },
+ selectablePassage: {
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': colorVars['--color-background-yellow'],
+ },
+ borderBlockEndStyle: 'dashed',
+ borderBlockEndColor: colorVars['--color-border-emphasized'],
+ },
+ document: {
+ overflowY: 'auto',
+ },
+});
+
+function updateComment(
+ comments: readonly CommentThreadData[],
+ id: string,
+ update: (comment: CommentData) => CommentData,
+): CommentThreadData[] {
+ return comments.map(comment =>
+ comment.id === id
+ ? {...comment, ...update(comment)}
+ : {
+ ...comment,
+ replies: comment.replies?.map(reply =>
+ reply.id === id ? update(reply) : reply,
+ ),
+ },
+ );
+}
+
+export default function CommentsInline() {
+ const [comments, setComments] = useState<CommentThreadData[]>(() => [
+ ...INITIAL_COMMENTS,
+ ]);
+ const [selectedThreadId, setSelectedThreadId] = useState<string | null>(
+ 'rollout-window',
+ );
+ const [selectedPassage, setSelectedPassage] = useState<string | null>(null);
+ const [composerAnchor, setComposerAnchor] = useState<CommentAnchor>();
+ const nextId = useRef(1);
+
+ const post = (body: string, parentCommentId?: string) => {
+ const id = `review-comment-${nextId.current++}`;
+ const comment: CommentData = {
+ id,
+ author: VIEWER,
+ body,
+ createdAt: new Date().toISOString(),
+ };
+ if (parentCommentId != null) {
+ setComments(current =>
+ current.map(thread =>
+ thread.id === parentCommentId
+ ? {...thread, replies: [...(thread.replies ?? []), comment]}
+ : thread,
+ ),
+ );
+ return;
+ }
+ setComments(current => [...current, {...comment, anchor: composerAnchor}]);
+ setComposerAnchor(undefined);
+ setSelectedPassage(null);
+ setSelectedThreadId(id);
+ };
+
+ return (
+ <HStack gap={3} align="start">
+ <Card width={520} height={620} padding={4}>
+ <VStack gap={4} width="100%" xstyle={styles.document}>
+ <VStack gap={1}>
+ <Text as="h1" type="display-3" weight="bold">
+ Launch plan
+ </Text>
+ <Text type="supporting" color="secondary">
+ Draft · updated today
+ </Text>
+ </VStack>
+
+ <VStack gap={2}>
+ <Text as="h2" type="body" weight="bold">
+ Rollout
+ </Text>
+ <Text type="body">
+ Begin with the internal cohort, then expand by region.
+ <button
+ type="button"
+ {...stylex.props(
+ styles.passage,
+ selectedThreadId === 'rollout-window' &&
+ styles.selectedPassage,
+ )}
+ aria-label={`Open comments on “${ROLLOUT_PASSAGE}”`}
+ onClick={() => {
+ setSelectedPassage(null);
+ setComposerAnchor(undefined);
+ setSelectedThreadId('rollout-window');
+ }}>
+ {ROLLOUT_PASSAGE}
+ </button>
+ Owners confirm each step before the next begins.
+ </Text>
+ </VStack>
+
+ <VStack gap={2}>
+ <Text as="h2" type="body" weight="bold">
+ Guardrails
+ </Text>
+ <Text type="body">
+ Watch latency and error rate throughout the rollout.
+ <button
+ type="button"
+ {...stylex.props(
+ styles.passage,
+ selectedThreadId === 'latency-threshold' &&
+ styles.selectedPassage,
+ )}
+ aria-label={`Open comments on “${GUARDRAIL_PASSAGE}”`}
+ onClick={() => {
+ setSelectedPassage(null);
+ setComposerAnchor(undefined);
+ setSelectedThreadId('latency-threshold');
+ }}>
+ {GUARDRAIL_PASSAGE}
+ </button>
+ Resume only after the metric returns to baseline.
+ </Text>
+ </VStack>
+
+ <VStack gap={2} align="start">
+ <Text as="h2" type="body" weight="bold">
+ Review
+ </Text>
+ <Text type="body">
+ <button
+ type="button"
+ {...stylex.props(
+ styles.passage,
+ styles.selectablePassage,
+ selectedPassage === REVIEW_PASSAGE && styles.selectedPassage,
+ )}
+ aria-label={`Select “${REVIEW_PASSAGE}” for a comment`}
+ onClick={() => {
+ setSelectedThreadId(null);
+ setComposerAnchor(undefined);
+ setSelectedPassage(REVIEW_PASSAGE);
+ }}>
+ {REVIEW_PASSAGE}
+ </button>
+ </Text>
+ {selectedPassage === REVIEW_PASSAGE && (
+ <Button
+ label="Comment on selection"
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ setComposerAnchor({quote: REVIEW_PASSAGE});
+ setSelectedPassage(null);
+ }}
+ />
+ )}
+ </VStack>
+ </VStack>
+ </Card>
+
+ <Card width={360} height={620} padding={0}>
+ <Comments
+ label="Comments on Launch plan"
+ comments={comments}
+ currentUser={VIEWER}
+ container="card"
+ density="compact"
+ selectedThreadId={selectedThreadId}
+ onSelectedThreadChange={setSelectedThreadId}
+ composerAnchor={composerAnchor}
+ onComposerAnchorDismiss={() => setComposerAnchor(undefined)}
+ onSubmit={post}
+ onResolveThread={commentId =>
+ setComments(current =>
+ updateComment(current, commentId, comment => ({
+ ...comment,
+ isResolved: true,
+ resolvedBy: VIEWER,
+ })),
+ )
+ }
+ onReopenThread={commentId =>
+ setComments(current =>
+ updateComment(current, commentId, comment => ({
+ ...comment,
+ isResolved: false,
+ resolvedBy: undefined,
+ })),
+ )
+ }
+ />
+ </Card>
+ </HStack>
+ );
+}
diff --git a/packages/lab/blocks/CommentsShowcase.doc.mjs b/packages/lab/blocks/CommentsShowcase.doc.mjs
new file mode 100644
index 0000000000..3cf3db3006
--- /dev/null
+++ b/packages/lab/blocks/CommentsShowcase.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Comments panel',
+ displayName: 'Comments panel',
+ description:
+ 'A working Comments panel: threads with replies, reactions, edit history, controlled typing with hidden seen metadata, inline comments, a non-interrupting unread-reply reveal, an agent reply still being written, a resolved thread, a comment that failed to send, activity events, and earlier comments to load. Post, reply, react, edit, delete, and resolve; the host updates the controlled comments.',
+ exampleFor: 'Comments',
+ isReady: true,
+ isShowcase: true,
+ aspectRatio: 3 / 4,
+ componentsUsed: ['Comments', 'VStack'],
+};
diff --git a/packages/lab/blocks/CommentsShowcase.tsx b/packages/lab/blocks/CommentsShowcase.tsx
new file mode 100644
index 0000000000..f6352dbdfb
--- /dev/null
+++ b/packages/lab/blocks/CommentsShowcase.tsx
@@ -0,0 +1,341 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input Controlled comments, events, and every Comments callback
+ * @output A working Comments panel: threads with replies, reactions,
+ * edit history, inline comments, controlled typing and hidden seen metadata,
+ * a non-interrupting unread-reply reveal, an agent's reply in progress, a
+ * failed comment, activity events, and earlier comments to load
+ * @position Lab Comments's docsite showcase and copyable CLI block
+ */
+
+import {useRef, useState} from 'react';
+import {VStack} from '@astryxdesign/core/Layout';
+import {
+ DEFAULT_COMMENT_REACTIONS,
+ Comments,
+ type CommentData,
+ type CommentReactionOption,
+ type CommentThreadData,
+ type CommentUser,
+ type CommentVersion,
+ type CommentActivityEvent,
+} from '@astryxdesign/lab';
+
+const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};
+const MAYA: CommentUser = {id: 'maya', name: 'Maya Chen'};
+const NOAH: CommentUser = {id: 'noah', name: 'Noah Williams'};
+const ASSISTANT: CommentUser = {
+ id: 'release-assistant',
+ name: 'Release Assistant',
+ kind: 'agent',
+};
+
+const EVENTS: readonly CommentActivityEvent[] = [
+ {
+ id: 'checklist',
+ label: 'Rollout checklist attached',
+ description: 'Added the launch checklist to the discussion.',
+ createdAt: '2026-09-30T18:46:00Z',
+ actor: MAYA,
+ },
+ {
+ id: 'status',
+ label: 'Status changed to Ready for review',
+ createdAt: '2026-09-30T19:02:00Z',
+ },
+];
+
+const INITIAL_COMMENTS: readonly CommentThreadData[] = [
+ {
+ id: 'plan',
+ author: MAYA,
+ body: 'The revised rollout plan is ready. **Avery**, could you check the final cohort?',
+ createdAt: '2026-09-30T18:30:00Z',
+ isEdited: true,
+ isUnread: true,
+ typingUsers: [NOAH],
+ seenBy: [NOAH],
+ previousVersions: [
+ {
+ id: 'plan-v1',
+ body: 'The revised rollout plan is ready for review.',
+ editedAt: '2026-09-30T18:10:00Z',
+ author: MAYA,
+ },
+ ],
+ reactions: [
+ {
+ key: 'like',
+ label: '👍',
+ description: 'Like',
+ count: 2,
+ reactedByViewer: true,
+ actors: [VIEWER, NOAH],
+ },
+ ],
+ replies: [
+ {
+ id: 'plan-reply-1',
+ author: NOAH,
+ body: 'I checked the cohort and the guardrail query. Both look good.',
+ createdAt: '2026-09-30T18:42:00Z',
+ },
+ {
+ id: 'plan-reply-2',
+ author: ASSISTANT,
+ body: '',
+ createdAt: '2026-09-30T18:45:00Z',
+ progress: {label: 'Checking the rollout dependencies…'},
+ },
+ ],
+ },
+ {
+ id: 'inline',
+ author: NOAH,
+ body: 'Should this say three days? The dry run adds one.',
+ createdAt: '2026-09-30T18:52:00Z',
+ anchor: {quote: 'The final cohort completes rollout in two days.'},
+ replies: [
+ {
+ id: 'inline-reply-1',
+ author: MAYA,
+ body: 'Yes — I updated the rollout window to three days.',
+ createdAt: '2026-09-30T19:04:00Z',
+ isUnread: true,
+ },
+ ],
+ },
+ {
+ id: 'orphaned',
+ author: MAYA,
+ body: 'Typo: "Teh".',
+ createdAt: '2026-09-30T18:55:00Z',
+ anchor: {quote: 'Teh guardrail query runs hourly.', status: 'orphaned'},
+ isResolved: true,
+ resolvedBy: VIEWER,
+ },
+ {
+ id: 'failed',
+ author: VIEWER,
+ body: 'Posting this update failed, but the text is kept.',
+ createdAt: '2026-09-30T19:10:00Z',
+ status: 'error',
+ errorMessage: "Couldn't post this comment.",
+ },
+];
+
+function updateComment(
+ comments: readonly CommentThreadData[],
+ id: string,
+ update: (comment: CommentData) => CommentData,
+): CommentThreadData[] {
+ return comments.map(comment =>
+ comment.id === id
+ ? {...comment, ...update(comment)}
+ : {
+ ...comment,
+ replies: comment.replies?.map(reply =>
+ reply.id === id ? update(reply) : reply,
+ ),
+ },
+ );
+}
+
+function findComment(
+ comments: readonly CommentThreadData[],
+ id: string,
+): CommentData | undefined {
+ for (const comment of comments) {
+ if (comment.id === id) {
+ return comment;
+ }
+ const reply = comment.replies?.find(candidate => candidate.id === id);
+ if (reply != null) {
+ return reply;
+ }
+ }
+ return undefined;
+}
+
+export default function CommentsShowcase() {
+ const [comments, setComments] = useState<CommentThreadData[]>(() => [
+ ...INITIAL_COMMENTS,
+ ]);
+ const [selectedThreadId, setSelectedThreadId] = useState<string | null>(
+ 'plan',
+ );
+ const [hasOlderComments, setHasOlderComments] = useState(true);
+ const nextId = useRef(1);
+
+ const post = (body: string, parentCommentId?: string) => {
+ const comment = {
+ id: `demo-${nextId.current++}`,
+ author: VIEWER,
+ body,
+ createdAt: new Date().toISOString(),
+ };
+ setComments(current =>
+ parentCommentId == null
+ ? [...current, comment]
+ : current.map(root =>
+ root.id === parentCommentId
+ ? {...root, replies: [...(root.replies ?? []), comment]}
+ : root,
+ ),
+ );
+ };
+
+ const saveEdit = (commentId: string, body: string) =>
+ setComments(current =>
+ updateComment(current, commentId, comment => ({
+ ...comment,
+ body,
+ isEdited: true,
+ previousVersions: [
+ {
+ id: `${comment.id}-${Date.now()}`,
+ body: comment.body,
+ editedAt: new Date().toISOString(),
+ author: comment.author,
+ },
+ ...(comment.previousVersions ?? []),
+ ],
+ })),
+ );
+
+ const remove = (commentId: string) =>
+ setComments(current =>
+ current
+ .filter(comment => comment.id !== commentId)
+ .map(comment => ({
+ ...comment,
+ replies: comment.replies?.filter(reply => reply.id !== commentId),
+ })),
+ );
+
+ const react = (
+ commentId: string,
+ key: string,
+ picked?: CommentReactionOption,
+ ) => {
+ const option =
+ picked ??
+ DEFAULT_COMMENT_REACTIONS.find(candidate => candidate.key === key);
+ if (option == null) {
+ return;
+ }
+ setComments(current =>
+ updateComment(current, commentId, comment => {
+ const existing = comment.reactions?.find(
+ reaction => reaction.key === key,
+ );
+ const reactions =
+ existing == null
+ ? [
+ ...(comment.reactions ?? []),
+ {...option, count: 1, reactedByViewer: true, actors: [VIEWER]},
+ ]
+ : (comment.reactions ?? [])
+ .map(reaction =>
+ reaction.key === key
+ ? {
+ ...reaction,
+ count:
+ reaction.count + (reaction.reactedByViewer ? -1 : 1),
+ reactedByViewer: !reaction.reactedByViewer,
+ }
+ : reaction,
+ )
+ .filter(reaction => reaction.count > 0);
+ return {...comment, reactions};
+ }),
+ );
+ };
+
+ const setResolved = (commentId: string, isResolved: boolean) =>
+ setComments(current =>
+ current.map(comment =>
+ comment.id === commentId
+ ? {
+ ...comment,
+ isResolved,
+ resolvedBy: isResolved ? VIEWER : undefined,
+ }
+ : comment,
+ ),
+ );
+
+ const loadVersions = async (
+ commentId: string,
+ ): Promise<readonly CommentVersion[]> => {
+ const comment = findComment(comments, commentId);
+ if (comment == null) {
+ return [];
+ }
+ return [
+ {
+ id: `${comment.id}-current`,
+ body: comment.body,
+ editedAt: comment.updatedAt ?? comment.createdAt,
+ author: comment.author,
+ isCurrent: true,
+ },
+ ...(comment.previousVersions ?? []),
+ ];
+ };
+
+ return (
+ <VStack width="100%" height="100%">
+ <Comments
+ comments={comments}
+ events={EVENTS}
+ currentUser={VIEWER}
+ selectedThreadId={selectedThreadId}
+ onSelectedThreadChange={setSelectedThreadId}
+ density="compact"
+ hasOlderComments={hasOlderComments}
+ onLoadOlder={() => {
+ setComments(current => [
+ {
+ id: 'older',
+ author: NOAH,
+ body: 'Earlier context loads above the threads.',
+ createdAt: '2026-09-30T17:45:00Z',
+ },
+ ...current,
+ ]);
+ setHasOlderComments(false);
+ }}
+ agentCommands={[
+ {
+ command: 'ask',
+ name: 'Release Assistant',
+ description: 'Ask about the rollout',
+ },
+ ]}
+ onUploadImages={async files =>
+ files.map(file => ({url: URL.createObjectURL(file), alt: file.name}))
+ }
+ onSubmit={post}
+ onSaveEdit={saveEdit}
+ onDelete={remove}
+ onReact={react}
+ onResolveThread={id => setResolved(id, true)}
+ onReopenThread={id => setResolved(id, false)}
+ onRetryComment={commentId =>
+ setComments(current =>
+ updateComment(current, commentId, comment => ({
+ ...comment,
+ status: 'sent',
+ errorMessage: undefined,
+ })),
+ )
+ }
+ loadVersions={loadVersions}
+ />
+ </VStack>
+ );
+}
diff --git a/packages/lab/src/Comments/CommentParts.tsx b/packages/lab/src/Comments/CommentParts.tsx
index dc33c4032b..6fd49cd78d 100644
--- a/packages/lab/src/Comments/CommentParts.tsx
+++ b/packages/lab/src/Comments/CommentParts.tsx
@@ -20,9 +20,11 @@ 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 {Card} from '@astryxdesign/core/Card';
import {Center} from '@astryxdesign/core/Center';
import {Dialog, DialogHeader} from '@astryxdesign/core/Dialog';
import {EmptyState} from '@astryxdesign/core/EmptyState';
+import {Item} from '@astryxdesign/core/Item';
import {
HStack,
Layout,
@@ -32,11 +34,13 @@ import {
} from '@astryxdesign/core/Layout';
import {Link} from '@astryxdesign/core/Link';
import {Section} from '@astryxdesign/core/Section';
+import {Skeleton} from '@astryxdesign/core/Skeleton';
import {Spinner} from '@astryxdesign/core/Spinner';
import {Text} from '@astryxdesign/core/Text';
import {Thumbnail} from '@astryxdesign/core/Thumbnail';
import {Timestamp} from '@astryxdesign/core/Timestamp';
import {Tooltip} from '@astryxdesign/core/Tooltip';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {useTranslator} from '@astryxdesign/core/i18n';
import {
borderVars,
@@ -46,13 +50,15 @@ import {
radiusVars,
spacingVars,
} from '@astryxdesign/core/theme/tokens.stylex';
-import type {AnyComment} from './utils';
+import {CommentIcon} from './icons';
+import {eventAnchorId, type AnyComment} from './utils';
import type {
CommentAnchor,
CommentHighlightColor,
CommentProgress,
CommentUser,
CommentVersion,
+ CommentActivityEvent,
} from './types';
/** The 28px avatar column every comment row, reply, and event aligns to. */
@@ -626,6 +632,62 @@ export function AvatarSpacer() {
);
}
+export function ActivityEventRow({
+ event,
+ renderEvent,
+}: {
+ event: CommentActivityEvent;
+ renderEvent?: (event: CommentActivityEvent) => ReactNode;
+}) {
+ const anchorId = eventAnchorId(event.id);
+ const href = event.href ?? `#${anchorId}`;
+ if (renderEvent != null) {
+ return (
+ <VStack id={anchorId} width="100%" data-comments-event-id={event.id}>
+ {renderEvent(event)}
+ </VStack>
+ );
+ }
+ return (
+ <Item
+ id={anchorId}
+ data-comments-event-id={event.id}
+ density="compact"
+ align="start"
+ xstyle={partStyles.eventRow}
+ startContent={
+ <Center xstyle={partStyles.avatarSpacer} aria-hidden="true">
+ <CommentIcon name="event" size="md" />
+ </Center>
+ }
+ label={event.label}
+ description={
+ event.actor != null || event.description != null ? (
+ <HStack gap={1} align="center" wrap="wrap">
+ {event.actor != null && <AuthorName author={event.actor} />}
+ {event.description != null && (
+ <Text type="supporting" color="secondary">
+ {event.description}
+ </Text>
+ )}
+ </HStack>
+ ) : undefined
+ }
+ endContent={
+ <Link href={href} type="supporting" color="secondary">
+ <Timestamp
+ value={event.createdAt}
+ format="relative_short"
+ type="inherit"
+ color="inherit"
+ isLive
+ />
+ </Link>
+ }
+ />
+ );
+}
+
export type HistoryState = {
comment: AnyComment;
versions: readonly CommentVersion[];
@@ -721,3 +783,155 @@ export function HistoryDialog({
</Dialog>
);
}
+
+function LoadingCommentRow({
+ container,
+ index,
+}: {
+ container: 'section' | 'card';
+ index: number;
+}) {
+ const content = (
+ <HStack gap={2} align="start" width="100%">
+ <Skeleton
+ width={AVATAR_SIZE}
+ height={AVATAR_SIZE}
+ radius="rounded"
+ index={index * 7}
+ />
+ <StackItem size="fill">
+ <VStack gap={1} width="100%">
+ <HStack gap={1} align="center" width="100%">
+ <Skeleton
+ width={index === 0 ? '38%' : '30%'}
+ height={spacingVars['--spacing-4']}
+ radius={1}
+ index={index * 7 + 1}
+ />
+ <Skeleton
+ width="18%"
+ height={spacingVars['--spacing-3']}
+ radius={1}
+ index={index * 7 + 2}
+ />
+ </HStack>
+ <Skeleton
+ width="96%"
+ height={spacingVars['--spacing-4']}
+ radius={1}
+ index={index * 7 + 3}
+ />
+ <Skeleton
+ width={index === 0 ? '82%' : '68%'}
+ height={spacingVars['--spacing-4']}
+ radius={1}
+ index={index * 7 + 4}
+ />
+ {index === 0 && (
+ <Skeleton
+ width="54%"
+ height={spacingVars['--spacing-4']}
+ radius={1}
+ index={index * 7 + 5}
+ />
+ )}
+ <HStack gap={1} align="center">
+ <Skeleton
+ width={`calc(${spacingVars['--spacing-8']} + ${spacingVars['--spacing-4']})`}
+ height={spacingVars['--spacing-6']}
+ radius={2}
+ index={index * 7 + 5}
+ />
+ <Skeleton
+ width={spacingVars['--spacing-8']}
+ height={spacingVars['--spacing-6']}
+ radius={2}
+ index={index * 7 + 6}
+ />
+ </HStack>
+ </VStack>
+ </StackItem>
+ </HStack>
+ );
+
+ return container === 'card' ? (
+ <Section
+ variant="transparent"
+ dividers={['top', 'bottom']}
+ padding={3}
+ width="100%"
+ xstyle={partStyles.sectionDividerOverlap}>
+ {content}
+ </Section>
+ ) : (
+ <Card variant="default" elevation="none" padding={3} width="100%">
+ {content}
+ </Card>
+ );
+}
+
+/** Comment-shaped placeholders in the same Card or Section the threads use. */
+export function CommentThreadLoadingSkeleton({
+ container,
+}: {
+ container: 'section' | 'card';
+}) {
+ const t = useTranslator();
+ return (
+ <VStack
+ gap={container === 'card' ? 0 : 2}
+ width="100%"
+ data-comments-loading="threads">
+ <VisuallyHidden>{t('@astryx.comments.loading')}</VisuallyHidden>
+ {[0, 1, 2].map(index => (
+ <LoadingCommentRow key={index} container={container} index={index} />
+ ))}
+ </VStack>
+ );
+}
+
+/** The two-row composer's shape: the input, then its buttons and Post. */
+export function CommentComposerLoadingSkeleton({
+ actionCount,
+}: {
+ actionCount: number;
+}) {
+ const actionSize = spacingVars['--spacing-8'];
+ return (
+ <Card
+ variant="default"
+ elevation="none"
+ padding={2}
+ width="100%"
+ xstyle={partStyles.loadingComposer}
+ data-comments-loading="composer">
+ <VStack gap={2} width="100%">
+ <Skeleton
+ width="42%"
+ height={spacingVars['--spacing-4']}
+ radius={1}
+ index={22}
+ />
+ <HStack gap={1} align="center" justify="between" width="100%">
+ <HStack gap={0.5} align="center">
+ {Array.from({length: actionCount}, (_, offset) => (
+ <Skeleton
+ key={offset}
+ width={actionSize}
+ height={actionSize}
+ radius={2}
+ index={23 + offset}
+ />
+ ))}
+ </HStack>
+ <Skeleton
+ width={actionSize}
+ height={actionSize}
+ radius={2}
+ index={23 + actionCount}
+ />
+ </HStack>
+ </VStack>
+ </Card>
+ );
+}
diff --git a/packages/lab/src/Comments/Comments.doc.mjs b/packages/lab/src/Comments/Comments.doc.mjs
new file mode 100644
index 0000000000..c16f65ba48
--- /dev/null
+++ b/packages/lab/src/Comments/Comments.doc.mjs
@@ -0,0 +1,648 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// @ts-check
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'Comments',
+ displayName: 'Comments',
+ group: 'Comments',
+ category: 'Chat',
+ keywords: [
+ 'discussion',
+ 'comments',
+ 'comment thread',
+ 'threads',
+ 'replies',
+ 'reactions',
+ 'activity',
+ 'timeline',
+ 'inline comments',
+ 'annotations',
+ 'review',
+ 'conversation',
+ ],
+ description:
+ 'The comments on one item: comment threads with one level of replies, reactions, edit history, controlled typing and seen metadata, inline-comment quotes, and activity events in time order, with a composer for new comments. Controlled: your app owns the data and every mutation; the panel owns presentation, selection, and focus.',
+ usage: {
+ description:
+ 'The Comments panel shows the conversation about a document, task, or record: its comment threads and activity, with a composer for new comments. Use it as a side panel or section that fills a sized container, or embedded at its content height inside a card or popover. Render a single thread with CommentThread and a standalone composer with CommentComposer.',
+ anatomy: [
+ {
+ name: 'Thread',
+ required: true,
+ description:
+ 'An outlined Card on a section parent, or an edge-to-edge Section with 1px dividers on a card parent. Selecting it opens the thread: the body unclamps, replies show, and the reply composer opens, taking focus on a pointer press.',
+ },
+ {
+ name: 'Avatar',
+ required: true,
+ description:
+ 'A 28×28 picture or initials: a circle for people, a rounded square for agents. In an open thread a 2px rail joins the avatars in segments.',
+ },
+ {
+ name: 'Header',
+ required: true,
+ description:
+ 'One avatar tall: name, relative time, Edited (opens the edit history), and Resolved. Mark as resolved or Reopen, Add reaction, Reply, Copy link, and the more menu (Edit, Delete) appear while the pointer or focus is on the thread, collapsing into the more menu when room runs out.',
+ },
+ {
+ name: 'Quoted passage',
+ required: false,
+ description:
+ 'An inline comment quotes its passage as an italic blockquote whose rule takes the highlight color. A passage edited away keeps a neutral rule and an Outdated badge.',
+ },
+ {
+ name: 'Body',
+ required: true,
+ description:
+ 'Markdown, clamped to three lines until the thread opens. Images open in a Lightbox. A comment still being written shows its progress instead.',
+ },
+ {
+ name: 'Reactions',
+ required: false,
+ description:
+ 'A toggle for each reaction, pressed where the viewer reacted; its tooltip names who reacted.',
+ },
+ {
+ name: 'Replies',
+ required: false,
+ description:
+ 'One level, behind View replies. A host-marked unread reply reveals without selecting the thread, moving focus, or opening the reply composer. Replying to a reply posts to the thread.',
+ },
+ {
+ name: 'Live state',
+ required: false,
+ description:
+ 'Controlled typing state appears at the end of an open thread, with its pulsing dots in the avatar column and its label on the comment-text line. Controlled `seenBy` metadata is available to comment render callbacks but has no default presentation.',
+ },
+ {
+ name: 'Activity event',
+ required: false,
+ description:
+ 'A timeline row for a status change or other event, interleaved with threads by time.',
+ },
+ {
+ name: 'Composer',
+ required: false,
+ description:
+ 'A two-row CommentComposer docked at the bottom (or top): the input above attach and emoji buttons and Post.',
+ },
+ ],
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Keep the data controlled: update `comments` after each callback. Return a Promise so the panel shows the pending state and, when it rejects, an error with Retry.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Match the surface: give a pane a definite height, use `layout="embedded"` inside a card or popover, and set `container="card"` on a card parent so cards never nest.',
+ },
+ {
+ guidance: true,
+ description:
+ 'For inline comments, keep anchoring in your app: pass each thread its `anchor`, mark it `orphaned` when it no longer resolves, and sync `selectedThreadId` with the passage you highlight.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep live state controlled and transport-neutral: map your collaboration layer to `typingUsers` and `seenBy`, and use `onComposerDraftChange` to publish local activity. `seenBy` stays hidden unless a comment render callback presents it. Debounce and expire transient activity in your app.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Put data fetching, authorization, or telemetry in render slots. Keep them in your app and pass the results as data.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Assume `selectedThreadId` moves focus or opens a composer. It reveals and scrolls the controlled thread without interrupting the viewer; only their Reply action opens the reply composer.',
+ },
+ ],
+ accessibility: [
+ {
+ name: 'Comment list',
+ category: 'Semantics',
+ description:
+ 'The threads sit in a log named after the region, such as "Threads in Launch plan", so screen readers hear new comments politely. Each comment is an article named by its author, and the region reports busy while comments load.',
+ },
+ {
+ name: 'Live updates',
+ category: 'Content',
+ criterion: '4.1.3 Status Messages',
+ description:
+ 'Typing is a polite status message with reduced-motion-safe dots. `seenBy` metadata has no default presentation and introduces no additional live region.',
+ },
+ {
+ name: 'Thread toggle',
+ category: 'Keyboard',
+ criterion: '2.1.1 Keyboard',
+ description:
+ 'Each thread has one toggle button (the WAI-ARIA Button pattern, with aria-pressed) named "Thread by" and its author. Enter or Space opens or closes it and keeps focus on it; a pointer press on the thread opens it with focus in the reply composer. The whole surface takes the system focus ring while the toggle has focus.',
+ },
+ {
+ name: 'Replies and actions',
+ category: 'Keyboard',
+ description:
+ 'View replies is a disclosure button with aria-expanded and aria-controls (the WAI-ARIA Disclosure pattern). The more menu follows the Menu Button pattern; when an edit is saved or cancelled, or the delete dialog closes, focus returns to it.',
+ },
+ {
+ name: 'Focus after changes',
+ category: 'Keyboard',
+ criterion: '2.4.3 Focus Order',
+ description:
+ 'Focus never drops to the page. After a delete it moves to the next thread, or to the thread when a reply was deleted. Load earlier comments keeps focus on itself, or on the Retry that replaces it when loading fails. A thread selected when the panel mounts opens without taking focus.',
+ },
+ {
+ name: 'Busy actions',
+ category: 'Keyboard',
+ description:
+ 'Post and reactions stay focusable while a request is in flight and refuse a second press, so focus never drops to the page mid-request.',
+ },
+ {
+ name: 'Errors',
+ category: 'Content',
+ criterion: '4.1.3 Status Messages',
+ description:
+ 'Failures show in alert Banners next to the thing that failed, each with Retry when the action can be repeated. A failed delete is announced once, assertively, as the confirmation dialog changes its text.',
+ },
+ ],
+ },
+ theming: {
+ targets: [
+ {
+ className: 'astryx-comments',
+ visualProps: ['layout', 'density', 'container'],
+ },
+ {
+ className: 'astryx-comment-thread',
+ visualProps: ['container'],
+ },
+ {
+ className: 'astryx-comment-composer',
+ },
+ ],
+ },
+ components: [
+ {
+ name: 'Comments',
+ displayName: 'Comments',
+ description:
+ 'Comment threads and activity events in time order, with a composer for new comments and the dialogs threads open.',
+ props: [
+ {
+ name: 'comments',
+ type: 'readonly CommentThreadData[]',
+ required: true,
+ description:
+ 'The threads: each thread’s first comment, carrying `replies` (one level), `reactions`, transient `typingUsers`, hidden per-comment `seenBy` metadata, `anchor` for inline comments, `isResolved`, `status`, `progress`, and per-comment permissions. `seenBy` remains available to comment render callbacks. Shown in time order with `events`.',
+ },
+ {
+ name: 'events',
+ type: 'readonly CommentActivityEvent[]',
+ description:
+ 'Activity on the item, interleaved with the threads by `createdAt` as compact timeline rows.',
+ },
+ {
+ name: 'currentUser',
+ type: 'CommentUser',
+ description:
+ 'The viewer: their own comments get Edit and Delete, and their avatar sits beside the reply composer. Authorization stays with your app.',
+ },
+ {
+ name: 'mode',
+ type: "'interactive' | 'non-editable' | 'read-only'",
+ default: "'interactive'",
+ description:
+ '`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.',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Accessible name of the Comments region. Defaults to the localized "Comments".',
+ },
+ {
+ name: 'composerPosition',
+ type: "'top' | 'bottom' | 'none'",
+ default: "'bottom'",
+ description: 'Where the composer for new comments renders.',
+ },
+ {
+ name: 'density',
+ type: "'compact' | 'balanced'",
+ default: "'balanced'",
+ description: 'Spacing between threads and around the list.',
+ },
+ {
+ name: 'container',
+ type: "'section' | 'card'",
+ default: "'section'",
+ description:
+ 'The parent surface. `section` renders each thread as an outlined Card; `card` renders divider-bounded Sections whose dividers overlap into single lines.',
+ },
+ {
+ name: 'layout',
+ type: "'pane' | 'embedded'",
+ default: "'pane'",
+ description:
+ '`pane` fills its container and scrolls, with the composer docked. `embedded` takes its content’s height inside a host surface: no scroll area or dock, and on a card parent no outer rules.',
+ },
+ {
+ name: 'composerPlaceholder',
+ type: 'string',
+ description:
+ 'Placeholder of the new-comment composer. Defaults to the localized "Write a comment…", with replies saying "Reply to <name>…"; a custom value replaces both.',
+ },
+ {
+ name: 'selectedThreadId',
+ type: 'string | null',
+ description:
+ 'The open thread, controlled, for hosts that sync threads with a document. A host-selected thread opens its body and replies and scrolls into view without moving focus or opening the reply composer.',
+ },
+ {
+ name: 'onSelectedThreadChange',
+ type: '(threadId: string | null) => void',
+ description:
+ 'Called when the viewer opens a thread or closes the open one.',
+ },
+ {
+ name: 'composerAnchor',
+ type: 'CommentAnchor',
+ description:
+ 'The passage a new comment will attach to, quoted in the composer. An anchor that arrives while the panel is on screen moves focus to the composer.',
+ },
+ {
+ name: 'onComposerAnchorDismiss',
+ type: '() => void',
+ description:
+ 'Adds Remove quoted text to the composer’s quote; clear `composerAnchor` when it is called.',
+ },
+ {
+ name: 'composerControls',
+ type: 'ReactNode',
+ description:
+ 'Product-owned controls in the new-comment composer’s footer, after its attach and emoji buttons.',
+ },
+ {
+ name: 'highlightColor',
+ type: "'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'",
+ default: "'yellow'",
+ description:
+ 'The palette color your app highlights passages in. Quotes draw their rule in its `--color-border-<color>` token.',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'Shows comment-shaped placeholders and reports the region busy.',
+ },
+ {
+ name: 'loadError',
+ type: 'string',
+ description:
+ 'Shows an error Banner above the threads, for comments that failed to load.',
+ },
+ {
+ name: 'onRetryLoad',
+ type: '() => void | Promise<void>',
+ description:
+ 'Adds Retry to the `loadError` Banner; a Promise keeps Retry busy until it settles.',
+ },
+ {
+ name: 'hasOlderComments',
+ type: 'boolean',
+ default: 'false',
+ description: 'Shows Load earlier comments above the threads.',
+ },
+ {
+ name: 'isLoadingOlder',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'Holds Load earlier comments busy while your app fetches the page. A Promise from `onLoadOlder` does the same on its own.',
+ },
+ {
+ name: 'onLoadOlder',
+ type: '() => void | Promise<void>',
+ description:
+ 'Loads the previous page: prepend it to `comments`. A rejected Promise shows an error Banner whose Retry takes the button’s place.',
+ },
+ {
+ name: 'isSubmitting',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'Host-controlled pending state for the composers. Promise callbacks get a built-in pending state as well.',
+ },
+ {
+ name: 'onComposerDraftChange',
+ type: '(value: string, context: CommentComposerContext) => void',
+ description:
+ 'Reports drafts owned inside Comments: new comments, replies, and edits. It includes programmatic seeds and reports an empty value after submit, cancel, or a target switch. Route each update by `context`; debounce and expire typing in your app.',
+ },
+ {
+ name: 'composerError',
+ type: 'string',
+ description:
+ 'Host-controlled error above the new-comment composer. A rejected `onSubmit` shows its own error with Retry.',
+ },
+ {
+ name: 'reactionOptions',
+ type: 'readonly CommentReactionOption[]',
+ default: 'DEFAULT_COMMENT_REACTIONS',
+ description:
+ 'The reactions Add reaction offers: Like, Love, Haha, Wow, Sad, and Celebrate by default, named in the viewer’s language. Give your own options a `description` to name them.',
+ },
+ {
+ name: 'onSubmit',
+ type: '(content: string, parentCommentId?: string) => void | Promise<void>',
+ description:
+ 'Posts a comment or a reply. Replies always receive the thread’s first comment as the parent. A rejected Promise restores the draft and shows an error with Retry.',
+ },
+ {
+ name: 'onSaveEdit',
+ type: '(commentId: string, content: string) => void | Promise<void>',
+ description:
+ 'Adds Edit to the viewer’s own comments and saves the new Markdown. A rejected Promise shows an error Banner with Retry.',
+ },
+ {
+ name: 'onDelete',
+ type: '(commentId: string) => void | Promise<void>',
+ description:
+ 'Adds Delete to the viewer’s own comments, confirmed in a dialog first. A rejected Promise keeps the dialog open with the error.',
+ },
+ {
+ name: 'onRetryComment',
+ type: '(commentId: string) => void | Promise<void>',
+ description: 'Adds Retry to a comment whose `status` is `error`.',
+ },
+ {
+ name: 'onReact',
+ type: '(commentId: string, reactionKey: string, option?: CommentReactionOption) => void | Promise<void>',
+ description: 'Toggles the viewer’s reaction by its stable key.',
+ },
+ {
+ name: 'onResolveThread',
+ type: '(commentId: string) => void | Promise<void>',
+ description:
+ 'Adds Mark as resolved to open threads. Set `isResolved` when the call succeeds, and filter resolved threads where they should not show.',
+ },
+ {
+ name: 'onReopenThread',
+ type: '(commentId: string) => void | Promise<void>',
+ description:
+ 'Adds Reopen to resolved threads. Clear `isResolved` when the call succeeds.',
+ },
+ {
+ name: 'loadVersions',
+ type: '(commentId: string) => Promise<readonly CommentVersion[]>',
+ description:
+ 'Loads a comment’s edit history, newest first. `previousVersions` works when the data is already loaded.',
+ },
+ {
+ name: 'onUploadImages',
+ type: '(files: readonly File[], context: CommentComposerContext) => CommentUploadedImage[] | Promise<CommentUploadedImage[]>',
+ description:
+ 'Uploads images attached, pasted, or dropped in a composer and appends them as Markdown images. Your endpoint authorizes the viewer and validates the files.',
+ },
+ {
+ name: 'composerTriggers',
+ type: 'readonly ChatComposerTrigger[]',
+ description:
+ 'Typeahead triggers for every composer, such as an `@` people search whose tokens your Markdown plugins render.',
+ },
+ {
+ name: 'agentCommands',
+ type: 'readonly CommentAgentCommand[]',
+ description:
+ 'Agents a comment can address: typing `/` lists them, and a posted comment shows the command as the agent’s chip. Your app runs the agent.',
+ },
+ {
+ name: 'markdownPlugins',
+ type: 'readonly MarkdownPluginEntry[]',
+ description:
+ 'Block Markdown plugins for comment bodies, such as embeds for your own entities.',
+ },
+ {
+ name: 'markdownInlinePlugins',
+ type: 'readonly MarkdownInlinePlugin[]',
+ description:
+ 'Inline Markdown plugins for comment bodies, such as the mentions your triggers insert.',
+ },
+ {
+ name: 'getReplyMention',
+ type: '(author: CommentUser) => string | undefined',
+ description:
+ 'Seeds a reply to a reply with a mention of its author in your mention format.',
+ },
+ {
+ name: 'hasEmojiPicker',
+ type: 'boolean',
+ default: 'true',
+ description: 'Whether composers offer the emoji picker.',
+ },
+ {
+ name: 'emptyState',
+ type: 'ReactNode',
+ description: 'Replaces the default no-comments state.',
+ },
+ {
+ name: 'renderAnchor',
+ type: '(comment: CommentThreadData, defaultAnchor: ReactNode) => ReactNode',
+ description:
+ 'Replaces a thread’s quoted passage, for example to link it back to the document.',
+ },
+ {
+ 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: 'renderEvent',
+ type: '(event: CommentActivityEvent) => ReactNode',
+ description: 'Replaces an activity event’s timeline row.',
+ },
+ {
+ name: 'renderAdditionalActions',
+ type: '(comment: CommentData) => ReactNode',
+ description:
+ 'Adds product actions to a comment’s header, after the built-in ones.',
+ },
+ {
+ name: 'renderComposer',
+ type: '(props: CommentComposerRenderProps) => ReactNode',
+ description:
+ 'Replaces every composer’s input while the panel keeps its draft, pending, error, and context state. Your composer owns its own focus and keyboard handling.',
+ },
+ ],
+ },
+ {name: 'CommentThread'},
+ {name: 'CommentComposer'},
+ ],
+ playground: {
+ defaults: {
+ comments: [
+ {
+ id: 'preview-root',
+ author: {id: 'avery', name: 'Avery Kim'},
+ body: 'The final states are ready for review.',
+ createdAt: '2026-09-30T19:00:00Z',
+ reactions: [
+ {
+ key: 'like',
+ label: '👍',
+ count: 2,
+ reactedByViewer: true,
+ },
+ ],
+ replies: [
+ {
+ id: 'preview-reply',
+ author: {id: 'maya', name: 'Maya Chen'},
+ body: 'Reviewed the empty and error states.',
+ createdAt: '2026-09-30T19:10:00Z',
+ },
+ ],
+ },
+ ],
+ events: [
+ {
+ id: 'preview-event',
+ label: 'Status changed to Ready for review',
+ createdAt: '2026-09-30T19:15:00Z',
+ },
+ ],
+ currentUser: {id: 'avery', name: 'Avery Kim'},
+ mode: 'read-only',
+ density: 'compact',
+ container: 'section',
+ },
+ },
+ examples: [
+ {
+ label: 'Comments panel',
+ code: `import {useState} from 'react';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Comments} from '@astryxdesign/lab';
+
+const viewer = {id: 'avery', name: 'Avery Kim'};
+
+export default function Example() {
+ const [comments, setComments] = useState([
+ {
+ id: 'root',
+ author: {id: 'maya', name: 'Maya Chen'},
+ body: 'Can you review the rollout plan before Friday?',
+ createdAt: '2026-09-30T19:00:00Z',
+ },
+ ]);
+ const post = (body, parentId) => {
+ const comment = {
+ id: 'comment-' + Date.now(),
+ author: viewer,
+ body,
+ createdAt: new Date().toISOString(),
+ };
+ setComments(current =>
+ parentId == null
+ ? [...current, comment]
+ : current.map(root =>
+ root.id === parentId
+ ? {...root, replies: [...(root.replies ?? []), comment]}
+ : root,
+ ),
+ );
+ };
+ return (
+ <VStack width={560} height={420}>
+ <Comments
+ comments={comments}
+ currentUser={viewer}
+ density="compact"
+ onSubmit={post}
+ />
+ </VStack>
+ );
+}`,
+ },
+ {
+ label: 'Inside a card',
+ code: `import {Card} from '@astryxdesign/core/Card';
+import {Comments} from '@astryxdesign/lab';
+
+<Card padding={0} width={360} height={440}>
+ <Comments
+ comments={comments}
+ currentUser={viewer}
+ container="card"
+ density="compact"
+ onSubmit={post}
+ />
+</Card>`,
+ },
+ {
+ label: 'Inline comments',
+ code: `import {Comments} from '@astryxdesign/lab';
+
+<Comments
+ comments={[
+ {
+ id: 'inline',
+ author: {id: 'maya', name: 'Maya Chen'},
+ body: 'Should this say three days?',
+ createdAt: '2026-09-30T19:00:00Z',
+ anchor: {quote: 'The final cohort completes rollout in two days.'},
+ },
+ ]}
+ currentUser={viewer}
+ selectedThreadId={selectedThreadId}
+ onSelectedThreadChange={setSelectedThreadId}
+ composerAnchor={selection}
+ onComposerAnchorDismiss={() => setSelection(undefined)}
+ onSubmit={post}
+/>`,
+ },
+ {
+ label: 'Live collaboration state',
+ code: `import {Comments} from '@astryxdesign/lab';
+
+<Comments
+ comments={comments.map(thread => ({
+ ...thread,
+ typingUsers: typingUsersByThread[thread.id] ?? [],
+ seenBy: seenByComment[thread.id] ?? [],
+ replies: thread.replies?.map(reply => ({
+ ...reply,
+ seenBy: seenByComment[reply.id] ?? [],
+ })),
+ }))}
+ currentUser={viewer}
+ onSubmit={post}
+ onComposerDraftChange={(value, context) =>
+ publishTyping({context, isTyping: value.trim() !== ''})
+ }
+/>`,
+ },
+ {
+ label: 'Resolved threads',
+ code: `import {Comments} from '@astryxdesign/lab';
+
+<Comments
+ comments={showResolved ? comments : comments.filter(c => !c.isResolved)}
+ currentUser={viewer}
+ onSubmit={post}
+ onResolveThread={id => setResolved(id, true)}
+ onReopenThread={id => setResolved(id, false)}
+/>`,
+ },
+ ],
+};
diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsx
new file mode 100644
index 0000000000..fcf3d1a958
--- /dev/null
+++ b/packages/lab/src/Comments/Comments.test.tsx
@@ -0,0 +1,1335 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState, type ReactNode} from 'react';
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+// jsdom has no layout, so the measuring OverflowList is replaced by one that
+// collapses exactly the comment actions a test names.
+const overflowControl = vi.hoisted(() => ({collapsed: new Set<string>()}));
+vi.mock('@astryxdesign/core/OverflowList', async () => {
+ const React = await import('react');
+ type Item = {
+ child: React.ReactElement<{'data-comment-action'?: string}>;
+ index: number;
+ };
+ return {
+ OverflowList: ({
+ children,
+ onOverflowChange,
+ gap: _gap,
+ collapseFrom: _collapseFrom,
+ xstyle: _xstyle,
+ ...rest
+ }: {
+ children: React.ReactNode;
+ onOverflowChange?: (items: Item[]) => void;
+ gap?: number;
+ collapseFrom?: string;
+ xstyle?: unknown;
+ }) => {
+ const items = React.Children.toArray(children).map((child, index) => ({
+ child: child as Item['child'],
+ index,
+ }));
+ const collapsed = items.filter(item =>
+ overflowControl.collapsed.has(
+ item.child.props['data-comment-action'] ?? '',
+ ),
+ );
+ const collapsedKey = collapsed
+ .map(item => item.child.props['data-comment-action'])
+ .join(',');
+ React.useLayoutEffect(() => {
+ if (collapsed.length > 0) {
+ onOverflowChange?.(collapsed);
+ }
+ // Re-run only when the collapsed set changes.
+ }, [collapsedKey]);
+ return (
+ <div {...rest}>
+ {items
+ .filter(item => !collapsed.includes(item))
+ .map(item => item.child)}
+ </div>
+ );
+ },
+ };
+});
+
+import {Comments} from './Comments';
+import type {
+ CommentComposerRenderProps,
+ CommentData,
+ CommentThreadData,
+ CommentUser,
+} from './types';
+
+const VIEWER: CommentUser = {id: 'avery', name: 'Avery Kim'};
+const OTHER: CommentUser = {id: 'maya', name: 'Maya Chen'};
+const AGENT: CommentUser = {
+ id: 'release-bot',
+ name: 'Release Assistant',
+ kind: 'agent',
+ avatarUrl: '/agent-logo.png',
+};
+
+const COMMENTS: readonly CommentThreadData[] = [
+ {
+ id: 'root-1',
+ author: VIEWER,
+ body: 'The final states are **ready** for review.',
+ createdAt: '2026-09-30T19:00:00Z',
+ isEdited: true,
+ previousVersions: [
+ {
+ id: 'root-1-v1',
+ body: 'Earlier wording',
+ editedAt: '2026-09-30T18:00:00Z',
+ author: VIEWER,
+ },
+ ],
+ reactions: [
+ {
+ key: 'like',
+ label: '👍',
+ description: 'Like',
+ count: 2,
+ reactedByViewer: true,
+ actors: [VIEWER, OTHER],
+ },
+ ],
+ replies: [
+ {
+ id: 'reply-1',
+ author: OTHER,
+ body: 'A one-level reply',
+ createdAt: '2026-09-30T19:10:00Z',
+ },
+ ],
+ },
+];
+
+/** A plain composer standing in for the contenteditable one. */
+function TestComposer(props: CommentComposerRenderProps) {
+ return (
+ <section
+ aria-label={props.contextLabel ?? 'New comment'}
+ data-placeholder={props.placeholder}>
+ <output>{props.value}</output>
+ <button
+ type="button"
+ onClick={() =>
+ props.onChange(
+ props.context.kind === 'reply'
+ ? `${props.value}Reply body`
+ : props.context.kind === 'edit'
+ ? 'Edited comment body'
+ : 'New comment body',
+ )
+ }>
+ Set draft
+ </button>
+ <button type="button" onClick={() => props.onSubmit(props.value)}>
+ Submit composer
+ </button>
+ {props.error != null && <p role="alert">{props.error}</p>}
+ {props.onCancel != null && (
+ <button type="button" onClick={props.onCancel}>
+ Cancel composer
+ </button>
+ )}
+ </section>
+ );
+}
+
+const renderComposer = (props: CommentComposerRenderProps) => (
+ <TestComposer {...props} />
+);
+
+function articleByAuthor(name: string): HTMLElement {
+ const article = Array.from(document.querySelectorAll('article')).find(
+ candidate =>
+ candidate.querySelector(`[data-author-name="${name}"]`) != null,
+ );
+ if (article == null) {
+ throw new Error(`Article not found: ${name}`);
+ }
+ return article;
+}
+
+function threadSurface(threadId: string): HTMLElement {
+ const surface = document.querySelector(`[data-thread-id="${threadId}"]`);
+ if (!(surface instanceof HTMLElement)) {
+ throw new Error(`Thread not found: ${threadId}`);
+ }
+ return surface;
+}
+
+async function flush() {
+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 0)));
+}
+
+async function click(element: Element) {
+ await act(async () => {
+ fireEvent.click(element);
+ await Promise.resolve();
+ });
+}
+
+function menuItem(name: string): HTMLElement {
+ // Menus sit in a [popover] that jsdom never shows, so query with `hidden`.
+ const item = screen
+ .getAllByRole('menuitem', {hidden: true})
+ .find(candidate => candidate.textContent?.includes(name));
+ if (item == null) {
+ throw new Error(`Menu item not found: ${name}`);
+ }
+ return item;
+}
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+class IntersectionObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+}
+
+const writeText = vi.fn();
+
+// jsdom lacks the Popover API: track each popover's open state and dispatch
+// the toggle events Astryx listens for.
+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,
+ });
+});
+
+beforeEach(() => {
+ overflowControl.collapsed = new Set();
+ writeText.mockReset();
+ writeText.mockResolvedValue(undefined);
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+ vi.stubGlobal('IntersectionObserver', IntersectionObserverStub);
+ Object.defineProperty(globalThis.navigator, 'clipboard', {
+ configurable: true,
+ value: {writeText},
+ });
+ Element.prototype.scrollIntoView = () => {};
+ Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {
+ configurable: true,
+ value(this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ },
+ });
+ Object.defineProperty(HTMLDialogElement.prototype, 'close', {
+ configurable: true,
+ value(this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ },
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function Sized({children}: {children: ReactNode}) {
+ return <div style={{height: 600}}>{children}</div>;
+}
+
+describe('Comments rendering', () => {
+ it('renders threads, Markdown bodies, reactions, and a collapsed reply', () => {
+ render(
+ <Sized>
+ <Comments comments={COMMENTS} currentUser={VIEWER} />
+ </Sized>,
+ );
+
+ expect(screen.getByRole('region', {name: 'Comments'})).toBeTruthy();
+ const article = articleByAuthor('Avery Kim');
+ expect(within(article).getByText('ready').tagName).toBe('STRONG');
+ expect(
+ within(article).getByRole('button', {name: 'Like: 2'}),
+ ).toHaveAttribute('aria-pressed', 'true');
+ // Replies start hidden behind the disclosure link.
+ expect(screen.getByText('View 1 reply')).toBeTruthy();
+ expect(screen.queryByText('A one-level reply')).toBeNull();
+ });
+
+ it('renders the empty state when there is nothing to show', () => {
+ render(
+ <Sized>
+ <Comments comments={[]} currentUser={VIEWER} onSubmit={vi.fn()} />
+ </Sized>,
+ );
+ expect(screen.getByText('No comments yet')).toBeTruthy();
+ expect(
+ screen.getByText('Start the discussion with a comment.'),
+ ).toBeTruthy();
+ });
+
+ it('interleaves activity events with threads by time', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ id: 'early',
+ author: OTHER,
+ body: 'First',
+ createdAt: '2026-09-30T19:00:00Z',
+ },
+ {
+ id: 'late',
+ author: VIEWER,
+ body: 'Third',
+ createdAt: '2026-09-30T19:20:00Z',
+ },
+ ]}
+ events={[
+ {
+ id: 'status',
+ label: 'Status changed to Ready for review',
+ createdAt: '2026-09-30T19:10:00Z',
+ },
+ ]}
+ />
+ </Sized>,
+ );
+ const order = Array.from(
+ document.querySelectorAll('[data-thread-id], [data-comments-event-id]'),
+ ).map(
+ element =>
+ element.getAttribute('data-thread-id') ??
+ element.getAttribute('data-comments-event-id'),
+ );
+ expect(order).toEqual(['early', 'status', 'late']);
+ });
+
+ it('marks agents with a badge and shows a comment still being written as its progress', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ id: 'agent-root',
+ author: AGENT,
+ body: '',
+ createdAt: '2026-09-30T19:00:00Z',
+ progress: {
+ label: 'Checking the rollout…',
+ link: {label: 'Open session', href: '#session'},
+ },
+ },
+ ]}
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ onReact={vi.fn()}
+ />
+ </Sized>,
+ );
+ const article = articleByAuthor('Release Assistant');
+ expect(within(article).getByText('Agent')).toBeTruthy();
+ expect(within(article).getByRole('status').textContent).toBe(
+ 'Checking the rollout…',
+ );
+ expect(
+ within(article).getByRole('link', {name: 'Open session'}),
+ ).toBeTruthy();
+ // A comment still being written takes no replies or reactions.
+ expect(within(article).queryByRole('button', {name: 'Reply'})).toBeNull();
+ expect(
+ within(article).queryByRole('button', {name: 'Add reaction'}),
+ ).toBeNull();
+ });
+
+ it('removes the fading New badge from layout when its animation ends', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[{...COMMENTS[0], isUnread: true, replies: []}]}
+ />
+ </Sized>,
+ );
+ const badge = document.querySelector('[data-comment-unread-badge="true"]');
+ expect(badge?.textContent).toBe('New');
+ fireEvent.animationEnd(badge as Element);
+ expect(
+ document.querySelector('[data-comment-unread-badge="true"]'),
+ ).toBeNull();
+ });
+
+ it('reveals unread replies without selecting, focusing, or opening a composer', () => {
+ const onSelectedThreadChange = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ ...COMMENTS[0],
+ replies: [
+ {
+ id: 'unread-reply',
+ author: OTHER,
+ body: 'A new unseen reply.',
+ createdAt: '2026-09-30T19:10:00Z',
+ isUnread: true,
+ },
+ ],
+ },
+ ]}
+ currentUser={VIEWER}
+ composerPosition="none"
+ onSubmit={vi.fn()}
+ onSelectedThreadChange={onSelectedThreadChange}
+ />
+ </Sized>,
+ );
+
+ expect(threadSurface('root-1').getAttribute('data-selected')).toBe('false');
+ const reveal = document.querySelector(
+ '[data-unread-replies-revealed="true"]',
+ );
+ expect(reveal).not.toBeNull();
+ expect(
+ within(reveal as HTMLElement).getByText('A new unseen reply.'),
+ ).toBeTruthy();
+ expect(within(reveal as HTMLElement).getByText('New')).toBeTruthy();
+ expect(screen.queryByRole('button', {name: 'Hide replies'})).toBeNull();
+ expect(document.querySelector('[data-reply-composer]')).toBeNull();
+ expect(onSelectedThreadChange).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(document.body);
+ });
+
+ it('shows read-only reactions but no control that changes data', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ mode="read-only"
+ onSubmit={vi.fn()}
+ onReact={vi.fn()}
+ onSaveEdit={vi.fn()}
+ onDelete={vi.fn()}
+ />
+ </Sized>,
+ );
+ const article = articleByAuthor('Avery Kim');
+ expect(
+ within(article).getByRole('button', {name: 'Like: 2'}),
+ ).toBeDisabled();
+ expect(within(article).queryByRole('button', {name: 'Reply'})).toBeNull();
+ expect(
+ within(article).queryByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ ).toBeNull();
+ expect(screen.queryByRole('textbox')).toBeNull();
+ });
+
+ it('keeps reply and react in non-editable mode, without edit or delete', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ mode="non-editable"
+ onSubmit={vi.fn()}
+ onReact={vi.fn()}
+ onSaveEdit={vi.fn()}
+ onDelete={vi.fn()}
+ />
+ </Sized>,
+ );
+ const article = articleByAuthor('Avery Kim');
+ expect(within(article).getByRole('button', {name: 'Reply'})).toBeTruthy();
+ expect(
+ within(article).getByRole('button', {name: 'Add reaction'}),
+ ).toBeTruthy();
+ expect(
+ within(article).queryByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ ).toBeNull();
+ });
+
+ it('uses divider-bounded Sections inside a card parent', () => {
+ render(
+ <Sized>
+ <Comments comments={COMMENTS} container="card" />
+ </Sized>,
+ );
+ expect(threadSurface('root-1').getAttribute('data-thread-surface')).toBe(
+ 'section',
+ );
+ });
+
+ it('renders embedded at content height, without the chat layout', () => {
+ render(
+ <Comments
+ comments={COMMENTS}
+ container="card"
+ layout="embedded"
+ composerPosition="none"
+ />,
+ );
+ const region = screen.getByRole('region', {name: 'Comments'});
+ expect(region.getAttribute('data-layout')).toBe('embedded');
+ expect(region.querySelector('[role="log"]')).toBeNull();
+ });
+
+ it('shows the loading shape while loading', () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[]}
+ isLoading
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ />
+ </Sized>,
+ );
+ expect(screen.getByText('Loading comments')).toBeTruthy();
+ expect(
+ document.querySelector('[data-comments-loading="composer"]'),
+ ).not.toBeNull();
+ });
+});
+
+describe('Comments live collaboration seams', () => {
+ it('shows typing only after the thread opens and keeps seen-by metadata hidden by default', async () => {
+ const seenBy = [OTHER, AGENT] as const;
+ const renderBody = vi.fn((comment: CommentData) => (
+ <span>{comment.body}</span>
+ ));
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ ...COMMENTS[0],
+ replies: [],
+ typingUsers: [VIEWER, OTHER, OTHER, AGENT],
+ seenBy,
+ },
+ ]}
+ currentUser={VIEWER}
+ renderBody={renderBody}
+ />
+ </Sized>,
+ );
+
+ expect(
+ screen.queryByText('Maya Chen and Release Assistant are typing…'),
+ ).toBeNull();
+ expect(screen.queryByText('Seen by')).toBeNull();
+ expect(document.querySelector('[data-comment-seen-by]')).toBeNull();
+ expect(renderBody).toHaveBeenCalledWith(expect.objectContaining({seenBy}));
+
+ await click(screen.getByRole('button', {name: 'Thread by Avery Kim'}));
+ const typingStatus = screen
+ .getByText('Maya Chen and Release Assistant are typing…')
+ .closest('[role="status"]');
+ expect(typingStatus).not.toBeNull();
+ expect(
+ (typingStatus as HTMLElement).style.getPropertyValue(
+ '--astryx-chat-typing-indicator-dots-column-width',
+ ),
+ ).not.toBe('');
+ });
+
+ it('reports a new-comment draft with its anchor and clears it after posting', async () => {
+ const onComposerDraftChange = vi.fn();
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const anchor = {quote: 'The rollout completes on Friday.'};
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ composerAnchor={anchor}
+ onSubmit={onSubmit}
+ onComposerDraftChange={onComposerDraftChange}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+
+ const composer = screen.getByRole('region', {name: 'New comment'});
+ await click(within(composer).getByText('Set draft'));
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('New comment body', {
+ kind: 'comment',
+ anchor,
+ });
+ await click(within(composer).getByText('Submit composer'));
+ await flush();
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('', {
+ kind: 'comment',
+ anchor,
+ });
+ });
+
+ it('restores a failed draft without reporting a false clear', async () => {
+ const onComposerDraftChange = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={vi.fn().mockRejectedValue(new Error('offline'))}
+ onComposerDraftChange={onComposerDraftChange}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+
+ const composer = screen.getByRole('region', {name: 'New comment'});
+ await click(within(composer).getByText('Set draft'));
+ await click(within(composer).getByText('Submit composer'));
+ await flush();
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('New comment body', {
+ kind: 'comment',
+ });
+ expect(onComposerDraftChange).not.toHaveBeenCalledWith('', {
+ kind: 'comment',
+ });
+ });
+});
+
+describe('Comments threads', () => {
+ it('opens a pressed thread into its reply composer and shows its replies', async () => {
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ await click(screen.getByRole('button', {name: 'Thread by Avery Kim'}));
+ expect(threadSurface('root-1').getAttribute('data-selected')).toBe('true');
+ expect(screen.getByText('A one-level reply')).toBeTruthy();
+ expect(
+ screen.getByRole('region', {name: 'Replying to Avery Kim'}),
+ ).toHaveAttribute('data-placeholder', 'Reply to Avery Kim…');
+ });
+
+ it('keeps one thread selected at a time', async () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ id: 'a',
+ author: OTHER,
+ body: 'First',
+ createdAt: '2026-09-30T19:00:00Z',
+ },
+ {
+ id: 'b',
+ author: VIEWER,
+ body: 'Second',
+ createdAt: '2026-09-30T19:05:00Z',
+ },
+ ]}
+ />
+ </Sized>,
+ );
+ await click(screen.getByRole('button', {name: 'Thread by Maya Chen'}));
+ expect(threadSurface('a').getAttribute('data-selected')).toBe('true');
+ await click(screen.getByRole('button', {name: 'Thread by Avery Kim'}));
+ expect(threadSurface('a').getAttribute('data-selected')).toBe('false');
+ expect(threadSurface('b').getAttribute('data-selected')).toBe('true');
+ });
+
+ it('posts a reply to a reply under the thread, seeded by getReplyMention', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const onComposerDraftChange = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={onSubmit}
+ onComposerDraftChange={onComposerDraftChange}
+ getReplyMention={author => `@${author.id} `}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ await click(screen.getByText('View 1 reply'));
+ await click(
+ within(articleByAuthor('Maya Chen')).getByRole('button', {name: 'Reply'}),
+ );
+ const composer = screen.getByRole('region', {
+ name: 'Replying to Maya Chen',
+ });
+ expect(composer.querySelector('output')?.textContent).toBe('@maya ');
+ const replyContext = {
+ kind: 'reply' as const,
+ parentCommentId: 'root-1',
+ repliedToCommentId: 'reply-1',
+ };
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith(
+ '@maya ',
+ replyContext,
+ );
+ await click(within(composer).getByText('Set draft'));
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith(
+ '@maya Reply body',
+ replyContext,
+ );
+ await click(within(composer).getByText('Submit composer'));
+ await flush();
+ expect(onSubmit).toHaveBeenCalledWith('@maya Reply body', 'root-1');
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('', replyContext);
+ expect(
+ screen.queryByRole('region', {name: 'Replying to Maya Chen'}),
+ ).toBeNull();
+ });
+
+ it('posts a new comment and clears the draft', async () => {
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={onSubmit}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ const composer = screen.getByRole('region', {name: 'New comment'});
+ await click(within(composer).getByText('Set draft'));
+ await click(within(composer).getByText('Submit composer'));
+ await flush();
+ expect(onSubmit).toHaveBeenCalledWith('New comment body', undefined);
+ expect(composer.querySelector('output')?.textContent).toBe('');
+ });
+
+ it('restores a rejected draft and shows a generic error', async () => {
+ const onSubmit = vi.fn().mockRejectedValue(new Error('backend detail'));
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={onSubmit}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ const composer = screen.getByRole('region', {name: 'New comment'});
+ await click(within(composer).getByText('Set draft'));
+ await click(within(composer).getByText('Submit composer'));
+ await flush();
+ expect(composer.querySelector('output')?.textContent).toBe(
+ 'New comment body',
+ );
+ expect(within(composer).getByRole('alert').textContent).toBe(
+ "Your comment couldn't be posted.",
+ );
+ expect(document.body.textContent).not.toContain('backend detail');
+ });
+
+ it('edits the viewer’s own comment from the more menu', async () => {
+ const onSaveEdit = vi.fn().mockResolvedValue(undefined);
+ const onComposerDraftChange = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSaveEdit={onSaveEdit}
+ onComposerDraftChange={onComposerDraftChange}
+ onDelete={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ await click(
+ within(articleByAuthor('Avery Kim')).getByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ );
+ await flush();
+ await click(menuItem('Edit'));
+ const editor = screen.getByRole('region', {name: 'Editing comment'});
+ const editContext = {kind: 'edit' as const, commentId: 'root-1'};
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith(
+ COMMENTS[0].body,
+ editContext,
+ );
+ await click(within(editor).getByText('Set draft'));
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith(
+ 'Edited comment body',
+ editContext,
+ );
+ await click(within(editor).getByText('Submit composer'));
+ await flush();
+ expect(onSaveEdit).toHaveBeenCalledWith('root-1', 'Edited comment body');
+ expect(onComposerDraftChange).toHaveBeenLastCalledWith('', editContext);
+ expect(screen.queryByRole('region', {name: 'Editing comment'})).toBeNull();
+ });
+
+ it('confirms a deletion before calling the host', async () => {
+ const onDelete = vi.fn().mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onDelete={onDelete}
+ />
+ </Sized>,
+ );
+ await click(
+ within(articleByAuthor('Avery Kim')).getByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ );
+ await flush();
+ await click(menuItem('Delete'));
+ expect(onDelete).not.toHaveBeenCalled();
+ expect(document.body.textContent).toContain(
+ 'This action cannot be undone.',
+ );
+ const dialog = document.querySelector('dialog[open]');
+ if (!(dialog instanceof HTMLDialogElement)) {
+ throw new Error('Delete confirmation not found');
+ }
+ await click(within(dialog).getByRole('button', {name: 'Delete'}));
+ await flush();
+ expect(onDelete).toHaveBeenCalledWith('root-1');
+ });
+
+ it('toggles a reaction and picks a new one from Add reaction', async () => {
+ const onReact = vi.fn().mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onReact={onReact}
+ />
+ </Sized>,
+ );
+ const article = articleByAuthor('Avery Kim');
+ await click(within(article).getByRole('button', {name: 'Like: 2'}));
+ expect(onReact).toHaveBeenCalledWith('root-1', 'like', undefined);
+ await flush();
+ await click(within(article).getByRole('button', {name: 'Add reaction'}));
+ // Popover content sits in a closed [popover] for jsdom's accessibility
+ // tree, so it is queried with `hidden`.
+ await click(screen.getByRole('button', {name: 'Celebrate', hidden: true}));
+ expect(onReact).toHaveBeenLastCalledWith(
+ 'root-1',
+ 'celebrate',
+ expect.objectContaining({key: 'celebrate', label: '🎉'}),
+ );
+ });
+
+ it('shows a failed reaction as an error Banner whose Retry reacts again', async () => {
+ const onReact = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('nope'))
+ .mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onReact={onReact}
+ />
+ </Sized>,
+ );
+ await click(
+ within(articleByAuthor('Avery Kim')).getByRole('button', {
+ name: 'Like: 2',
+ }),
+ );
+ await flush();
+ const banner = screen.getByRole('alert');
+ expect(banner.textContent).toContain("Your reaction couldn't be saved.");
+ await click(within(banner).getByRole('button', {name: 'Retry'}));
+ await flush();
+ expect(onReact).toHaveBeenCalledTimes(2);
+ expect(screen.queryByRole('alert')).toBeNull();
+ });
+
+ it('copies a link to the comment', async () => {
+ render(
+ <Sized>
+ <Comments
+ comments={[{...COMMENTS[0], replies: []}]}
+ currentUser={OTHER}
+ />
+ </Sized>,
+ );
+ await click(screen.getByRole('button', {name: 'Copy comment link'}));
+ await flush();
+ expect(writeText).toHaveBeenCalledWith(
+ expect.stringMatching(/#comment-root-1$/),
+ );
+ expect(
+ screen.getByRole('button', {name: 'Comment link copied'}),
+ ).toBeTruthy();
+ });
+
+ it('collapses header actions into the more menu when space runs low', async () => {
+ overflowControl.collapsed = new Set(['reply', 'link']);
+ const onSubmit = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={[{...COMMENTS[0], replies: []}]}
+ currentUser={OTHER}
+ onSubmit={onSubmit}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ await flush();
+ const article = articleByAuthor('Avery Kim');
+ expect(within(article).queryByRole('button', {name: 'Reply'})).toBeNull();
+ await click(
+ within(article).getByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ );
+ await flush();
+ expect(menuItem('Reply')).toBeTruthy();
+ expect(menuItem('Copy comment link')).toBeTruthy();
+ });
+
+ it('loads and shows the edit history', async () => {
+ const loadVersions = vi.fn().mockResolvedValue([
+ {
+ id: 'current',
+ body: 'Current wording',
+ editedAt: '2026-09-30T19:00:00Z',
+ isCurrent: true,
+ },
+ {
+ id: 'previous',
+ body: 'Previous wording',
+ editedAt: '2026-09-30T18:00:00Z',
+ },
+ ]);
+ render(
+ <Sized>
+ <Comments comments={COMMENTS} loadVersions={loadVersions} />
+ </Sized>,
+ );
+ await click(screen.getByRole('button', {name: 'View edit history'}));
+ await flush();
+ expect(loadVersions).toHaveBeenCalledWith('root-1');
+ expect(document.body.textContent).toContain('Previous wording');
+ expect(document.body.textContent).toContain('Current version');
+ });
+
+ it('retries a comment that failed to send', async () => {
+ const onRetryComment = vi.fn().mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ id: 'failed',
+ author: VIEWER,
+ body: 'Kept text',
+ createdAt: '2026-09-30T19:00:00Z',
+ status: 'error',
+ errorMessage: "Couldn't post this comment.",
+ },
+ ]}
+ currentUser={VIEWER}
+ onRetryComment={onRetryComment}
+ />
+ </Sized>,
+ );
+ const banner = screen.getByRole('alert');
+ expect(banner.textContent).toContain("Couldn't post this comment.");
+ await click(within(banner).getByRole('button', {name: 'Retry'}));
+ await flush();
+ expect(onRetryComment).toHaveBeenCalledWith('failed');
+ });
+
+ it('loads earlier comments, and offers Retry when that fails', async () => {
+ const onLoadOlder = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ hasOlderComments
+ onLoadOlder={onLoadOlder}
+ />
+ </Sized>,
+ );
+ await click(screen.getByRole('button', {name: 'Load earlier comments'}));
+ await flush();
+ const banner = screen.getByRole('alert');
+ expect(banner.textContent).toContain("Earlier comments couldn't load");
+ await click(within(banner).getByRole('button', {name: 'Retry'}));
+ await flush();
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ expect(
+ screen.getByRole('button', {name: 'Load earlier comments'}),
+ ).toBeTruthy();
+ });
+});
+
+describe('Comments resolved and inline threads', () => {
+ it('resolves an open thread and reopens a resolved one', async () => {
+ const onResolveThread = vi.fn().mockResolvedValue(undefined);
+ const onReopenThread = vi.fn().mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={[
+ {
+ id: 'open',
+ author: OTHER,
+ body: 'Open thread',
+ createdAt: '2026-09-30T19:00:00Z',
+ },
+ {
+ id: 'done',
+ author: OTHER,
+ body: 'Resolved thread',
+ createdAt: '2026-09-30T19:05:00Z',
+ isResolved: true,
+ resolvedBy: VIEWER,
+ },
+ ]}
+ currentUser={VIEWER}
+ onResolveThread={onResolveThread}
+ onReopenThread={onReopenThread}
+ />
+ </Sized>,
+ );
+ await click(
+ within(threadSurface('open')).getByRole('button', {
+ name: 'Mark as resolved',
+ }),
+ );
+ expect(onResolveThread).toHaveBeenCalledWith('open');
+ const resolved = threadSurface('done');
+ expect(within(resolved).getByText('Resolved')).toBeTruthy();
+ await click(within(resolved).getByRole('button', {name: 'Reopen'}));
+ expect(onReopenThread).toHaveBeenCalledWith('done');
+ });
+
+ it('quotes anchored passages and marks orphaned ones Outdated', () => {
+ render(
+ <Sized>
+ <Comments
+ highlightColor="blue"
+ comments={[
+ {
+ id: 'inline',
+ author: OTHER,
+ body: 'Should this say three days?',
+ createdAt: '2026-09-30T19:00:00Z',
+ anchor: {quote: 'The rollout completes in two days.'},
+ },
+ {
+ id: 'orphaned',
+ author: VIEWER,
+ body: 'Typo.',
+ createdAt: '2026-09-30T19:05:00Z',
+ anchor: {quote: 'Teh query runs hourly.', status: 'orphaned'},
+ },
+ ]}
+ />
+ </Sized>,
+ );
+ const inline = threadSurface('inline');
+ expect(
+ inline
+ .querySelector('[data-quote-rule="highlight"]')
+ ?.getAttribute('data-highlight-color'),
+ ).toBe('blue');
+ const orphaned = threadSurface('orphaned');
+ expect(within(orphaned).getByText('Outdated')).toBeTruthy();
+ expect(
+ orphaned.querySelector('[data-quote-rule="neutral"]'),
+ ).not.toBeNull();
+ });
+
+ it('lets the host own selection for highlight sync', async () => {
+ function Host() {
+ const [selected, setSelected] = useState<string | null>(null);
+ return (
+ <Sized>
+ <button type="button" onClick={() => setSelected('root-1')}>
+ Select from document
+ </button>
+ <output data-testid="selected">{selected ?? 'none'}</output>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ selectedThreadId={selected}
+ onSelectedThreadChange={setSelected}
+ onSubmit={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>
+ );
+ }
+ render(<Host />);
+ await click(screen.getByText('Select from document'));
+ await flush();
+ expect(threadSurface('root-1').getAttribute('data-selected')).toBe('true');
+ expect(screen.getByText('A one-level reply')).toBeTruthy();
+ await click(screen.getByRole('button', {name: 'Thread by Avery Kim'}));
+ expect(screen.getByTestId('selected').textContent).toBe('none');
+ });
+
+ it('quotes the composer anchor and lets the viewer remove it', async () => {
+ const onDismiss = vi.fn();
+ render(
+ <Sized>
+ <Comments
+ comments={[]}
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ composerAnchor={{quote: 'Guardrail alerts page within five minutes.'}}
+ onComposerAnchorDismiss={onDismiss}
+ />
+ </Sized>,
+ );
+ const quote = document.querySelector('[data-composer-anchor="quote"]');
+ expect(quote?.textContent).toContain(
+ 'Guardrail alerts page within five minutes.',
+ );
+ await click(screen.getByRole('button', {name: 'Remove quoted text'}));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+});
+
+/** Lets a requested focus land: rows move it a frame after the commit. */
+async function nextFrame() {
+ await act(
+ () =>
+ new Promise<void>(resolve =>
+ requestAnimationFrame(() => setTimeout(resolve, 0)),
+ ),
+ );
+}
+
+describe('Comments keyboard and focus', () => {
+ it('opens a thread selected at mount without taking focus', async () => {
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ selectedThreadId="root-1"
+ onSelectedThreadChange={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ await nextFrame();
+ expect(threadSurface('root-1').getAttribute('data-selected')).toBe('true');
+ expect(screen.getByText('A one-level reply')).toBeTruthy();
+ expect(document.body).toHaveFocus();
+ });
+
+ it('opens a thread from the keyboard, leaving focus on it', async () => {
+ const user = userEvent.setup();
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSubmit={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ const toggle = screen.getByRole('button', {name: 'Thread by Avery Kim'});
+ toggle.focus();
+ await user.keyboard('{Enter}');
+ await nextFrame();
+ expect(threadSurface('root-1').getAttribute('data-selected')).toBe('true');
+ expect(screen.getByText('A one-level reply')).toBeTruthy();
+ expect(toggle).toHaveFocus();
+ });
+
+ it('returns focus to the comment’s actions when an edit is cancelled', async () => {
+ const user = userEvent.setup();
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={VIEWER}
+ onSaveEdit={vi.fn()}
+ onDelete={vi.fn()}
+ renderComposer={renderComposer}
+ />
+ </Sized>,
+ );
+ const actions = within(articleByAuthor('Avery Kim')).getByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ });
+ await click(actions);
+ await flush();
+ await click(menuItem('Edit'));
+ const editor = screen.getByRole('region', {name: 'Editing comment'});
+ await user.click(within(editor).getByText('Cancel composer'));
+ await nextFrame();
+ expect(screen.queryByRole('region', {name: 'Editing comment'})).toBeNull();
+ // The header remounts after the edit; its new actions button has focus.
+ expect(
+ within(articleByAuthor('Avery Kim')).getByRole('button', {
+ name: "Actions for Avery Kim's comment",
+ }),
+ ).toHaveFocus();
+ });
+
+ it('moves focus to the thread after deleting a reply, and announces a failure once', async () => {
+ const onDelete = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ currentUser={OTHER}
+ onDelete={onDelete}
+ selectedThreadId="root-1"
+ onSelectedThreadChange={vi.fn()}
+ />
+ </Sized>,
+ );
+ const openDialog = async () => {
+ await click(
+ within(articleByAuthor('Maya Chen')).getByRole('button', {
+ name: "Actions for Maya Chen's comment",
+ }),
+ );
+ await flush();
+ await click(menuItem('Delete'));
+ const dialog = document.querySelector('dialog[open]');
+ if (!(dialog instanceof HTMLDialogElement)) {
+ throw new Error('Delete confirmation not found');
+ }
+ return dialog;
+ };
+ const dialog = await openDialog();
+ await click(within(dialog).getByRole('button', {name: 'Delete'}));
+ await flush();
+ const failure = "This comment couldn't be deleted. Try again.";
+ expect(dialog.textContent).toContain(failure);
+ const assertive = document.querySelector(
+ '[data-astryx-live-region="assertive"]',
+ );
+ await waitFor(() => expect(assertive?.textContent).toContain(failure));
+ // The retry succeeds; focus lands on the thread's first comment.
+ await click(within(dialog).getByRole('button', {name: 'Delete'}));
+ await flush();
+ await nextFrame();
+ expect(onDelete).toHaveBeenCalledTimes(2);
+ expect(articleByAuthor('Avery Kim')).toHaveFocus();
+ });
+
+ it('keeps focus on the earlier-comments control as it turns into Retry and back', async () => {
+ const user = userEvent.setup();
+ const onLoadOlder = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue(undefined);
+ render(
+ <Sized>
+ <Comments
+ comments={COMMENTS}
+ hasOlderComments
+ onLoadOlder={onLoadOlder}
+ />
+ </Sized>,
+ );
+ screen.getByRole('button', {name: 'Load earlier comments'}).focus();
+ await user.keyboard('{Enter}');
+ await flush();
+ const banner = screen
+ .getByText("Earlier comments couldn't load")
+ .closest<HTMLElement>('[data-comments-older-error]');
+ if (banner == null) {
+ throw new Error('Earlier-comments failure not found');
+ }
+ expect(within(banner).getByRole('button', {name: 'Retry'})).toHaveFocus();
+ await user.keyboard('{Enter}');
+ await flush();
+ expect(onLoadOlder).toHaveBeenCalledTimes(2);
+ expect(
+ screen.getByRole('button', {name: 'Load earlier comments'}),
+ ).toHaveFocus();
+ });
+});
diff --git a/packages/lab/src/Comments/Comments.tsx b/packages/lab/src/Comments/Comments.tsx
new file mode 100644
index 0000000000..a7af237d43
--- /dev/null
+++ b/packages/lab/src/Comments/Comments.tsx
@@ -0,0 +1,643 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Comments.tsx
+ * @input Uses React, StyleX, ChatLayout, ChatMessageList, Banner, Button,
+ * EmptyState, and the Comments family's controller, rows, and composer
+ * @output Exports Comments and CommentsProps
+ * @position The comments on one item: its comment threads and activity
+ * events in time order, with a composer for new comments. A pane that fills
+ * its container and scrolls, or an embedded block at its content's height.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Comments/index.ts (exports)
+ * - /packages/lab/src/Comments/Comments.doc.mjs
+ * - /packages/lab/blocks/CommentsShowcase.tsx
+ */
+
+import {
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+ type Ref,
+} from 'react';
+import {flushSync} from 'react-dom';
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '@astryxdesign/core';
+import {Banner} from '@astryxdesign/core/Banner';
+import {Button} from '@astryxdesign/core/Button';
+import {ChatLayout, ChatMessageList} from '@astryxdesign/core/Chat';
+import {EmptyState} from '@astryxdesign/core/EmptyState';
+import {VStack} from '@astryxdesign/core/Layout';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+import {useTranslator} from '@astryxdesign/core/i18n';
+import {CommentComposerBase} from './CommentComposer';
+import {
+ ActivityEventRow,
+ CommentComposerLoadingSkeleton,
+ CommentThreadLoadingSkeleton,
+ ErrorBanner,
+} from './CommentParts';
+import {CommentRow, THREAD_DIVIDERS, type ThreadDivider} from './CommentRow';
+import {
+ CommentsContextProvider,
+ useCommentsController,
+} from './CommentsContext';
+import {timelineTime} from './utils';
+import type {
+ CommentAnchor,
+ CommentComposerContext,
+ CommentThreadData,
+ CommentThreadSharedProps,
+ CommentActivityEvent,
+} from './types';
+
+export interface CommentsProps
+ extends
+ CommentThreadSharedProps,
+ Omit<
+ BaseProps<HTMLElement>,
+ keyof CommentThreadSharedProps | 'onChange' | 'onSubmit'
+ > {
+ /** Ref forwarded to the root element. */
+ ref?: Ref<HTMLElement>;
+ /**
+ * The threads, controlled: each thread's first comment, carrying its
+ * replies. Shown in time order with `events`, oldest first unless the list
+ * itself runs newest first.
+ */
+ comments: readonly CommentThreadData[];
+ /** Activity on the item, interleaved with the threads by time. */
+ events?: readonly CommentActivityEvent[];
+ /** Accessible name of the Comments region. Defaults to the localized
+ * "Comments". */
+ label?: string;
+ /** Where the composer for new comments renders. @default 'bottom' */
+ composerPosition?: 'top' | 'bottom' | 'none';
+ /** @default 'balanced' */
+ density?: 'compact' | 'balanced';
+ /**
+ * `pane` fills its container and scrolls, with the composer docked at the
+ * bottom: a comments panel. `embedded` takes its content's height inside
+ * a host surface such as a Card or Popover: no scroll area or dock, and on
+ * a card parent no rule above the first thread or below the last.
+ * @default 'pane'
+ */
+ layout?: 'pane' | 'embedded';
+ /**
+ * The selected thread's id, for hosts that sync selection with a document:
+ * highlight the selected thread's passage, or select a thread from its
+ * highlight. Host selection opens the body and replies and scrolls the thread
+ * into view without moving focus or opening the reply composer. Omit it to
+ * let the panel own selection.
+ */
+ selectedThreadId?: string | null;
+ /** Called when the viewer selects (`threadId`) or deselects (`null`) a thread. */
+ onSelectedThreadChange?: (threadId: string | null) => void;
+ /**
+ * The passage a new comment will attach to, such as the viewer's text
+ * selection. The composer quotes it and takes focus; the host attaches it
+ * on submit and clears it afterwards.
+ */
+ composerAnchor?: CommentAnchor;
+ /** Adds Remove quoted text to the composer's quoted passage. */
+ onComposerAnchorDismiss?: () => void;
+ /**
+ * Product-owned controls in the new-comment composer's footer, after its
+ * attach and emoji buttons. Keep it to one short control.
+ */
+ composerControls?: ReactNode;
+ /** Shows comment-shaped placeholders instead of the threads. */
+ isLoading?: boolean;
+ /** Shows an error Banner; with `onRetryLoad`, a Retry action. */
+ loadError?: string;
+ onRetryLoad?: () => void | Promise<void>;
+ /** Adds Load earlier comments above the threads. */
+ hasOlderComments?: boolean;
+ isLoadingOlder?: boolean;
+ /** Loads the previous page; the host prepends it to `comments`. */
+ onLoadOlder?: () => void | Promise<void>;
+ /** Host-owned error for the new-comment composer. */
+ composerError?: string;
+ /** Replaces the default no-comments state. */
+ emptyState?: ReactNode;
+ /** Replaces the default activity event row. */
+ renderEvent?: (event: CommentActivityEvent) => ReactNode;
+}
+
+type TimelineEntry =
+ | {kind: 'comment'; value: CommentThreadData}
+ | {kind: 'event'; value: CommentActivityEvent};
+
+const NO_EVENTS: readonly CommentActivityEvent[] = [];
+
+const styles = stylex.create({
+ root: {
+ minHeight: 0,
+ overflow: 'hidden',
+ },
+ timeline: {
+ position: 'relative',
+ zIndex: 0,
+ isolation: 'isolate',
+ },
+ // A card parent's Sections bleed to the panel's edges through the message
+ // list's padding.
+ bleedCompact: {
+ width: `calc(100% + (${spacingVars['--spacing-3']} * 2))`,
+ marginInline: `calc(-1 * ${spacingVars['--spacing-3']})`,
+ marginBlockStart: `calc(-1 * ${spacingVars['--spacing-2']})`,
+ },
+ bleedBalanced: {
+ width: `calc(100% + (${spacingVars['--spacing-4']} * 2))`,
+ marginInline: `calc(-1 * ${spacingVars['--spacing-4']})`,
+ marginBlockStart: `calc(-1 * ${spacingVars['--spacing-4']})`,
+ },
+ // ChatLayout's dock pads one spacing step less than ChatMessageList, so a
+ // docked composer would stick out past the threads' edge. One step of
+ // inset restores it.
+ composerDock: {
+ paddingInline: spacingVars['--spacing-1'],
+ },
+});
+
+/**
+ * The comments on one item: comment threads with one level of replies,
+ * reactions, edit history, inline-comment quotes, and activity events, with
+ * a composer for new comments. Controlled: the host owns the data and every
+ * mutation; the panel owns presentation, selection, and focus.
+ *
+ * @example
+ * ```
+ * <Comments
+ * comments={comments}
+ * events={events}
+ * currentUser={viewer}
+ * onSubmit={post}
+ * onReact={toggleReaction}
+ * />
+ * ```
+ */
+export function Comments({
+ comments,
+ events = NO_EVENTS,
+ label: labelProp,
+ composerPosition = 'bottom',
+ density = 'balanced',
+ layout = 'pane',
+ selectedThreadId,
+ onSelectedThreadChange,
+ composerAnchor,
+ onComposerAnchorDismiss,
+ composerControls,
+ isLoading = false,
+ loadError,
+ onRetryLoad,
+ hasOlderComments = false,
+ isLoadingOlder = false,
+ onLoadOlder,
+ composerError,
+ emptyState,
+ renderEvent,
+ currentUser,
+ mode = 'interactive',
+ container = 'section',
+ composerPlaceholder,
+ highlightColor = 'yellow',
+ reactionOptions,
+ agentCommands,
+ composerTriggers,
+ markdownPlugins,
+ markdownInlinePlugins,
+ getReplyMention,
+ hasEmojiPicker = true,
+ isSubmitting,
+ onComposerDraftChange,
+ onSubmit,
+ onSaveEdit,
+ onDelete,
+ onReact,
+ onRetryComment,
+ onResolveThread,
+ onReopenThread,
+ loadVersions,
+ onUploadImages,
+ renderAnchor,
+ renderBody,
+ renderVersionBody,
+ renderAdditionalActions,
+ renderComposer,
+ ref,
+ xstyle,
+ className,
+ style,
+ ...rest
+}: CommentsProps) {
+ const t = useTranslator();
+ const label = labelProp ?? t('@astryx.comments.label');
+ const [draft, setDraft] = useState('');
+ const draftRef = useRef('');
+ const [topComposerError, setTopComposerError] = useState<string>();
+ const [loadingOlder, setLoadingOlder] = useState(false);
+ const [olderError, setOlderError] = useState<string>();
+ const [olderFailureCount, setOlderFailureCount] = useState(0);
+ const loadingOlderRef = useRef(false);
+ const loadOlderButtonRef = useRef<HTMLButtonElement>(null);
+ const olderRetryRef = useRef<HTMLButtonElement>(null);
+ 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 timelineEntries = useMemo<TimelineEntry[]>(() => {
+ const direction =
+ comments.length > 1 &&
+ timelineTime(comments[0].createdAt) >
+ timelineTime(comments[comments.length - 1].createdAt)
+ ? -1
+ : 1;
+ return [
+ ...comments.map(value => ({kind: 'comment' as const, value})),
+ ...events.map(value => ({kind: 'event' as const, value})),
+ ].sort(
+ (first, second) =>
+ direction *
+ (timelineTime(first.value.createdAt) -
+ timelineTime(second.value.createdAt)),
+ );
+ }, [comments, events]);
+ const roots = useMemo(
+ () =>
+ timelineEntries.flatMap(entry =>
+ entry.kind === 'comment' ? [entry.value] : [],
+ ),
+ [timelineEntries],
+ );
+ const topComposerContext: CommentComposerContext =
+ composerAnchor != null
+ ? {kind: 'comment', anchor: composerAnchor}
+ : {kind: 'comment'};
+
+ const {value, dialogs, submit} = 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,
+ onSelectedThreadChange,
+ roots,
+ rootRef,
+ });
+
+ // An anchor the panel mounts with is restored state, not a selection
+ // the viewer just made, so it shows without moving focus; an anchor that
+ // arrives while the panel is on screen takes focus.
+ const [mountedAnchorQuote, setMountedAnchorQuote] = useState(
+ composerAnchor?.quote,
+ );
+ if (
+ mountedAnchorQuote != null &&
+ composerAnchor?.quote !== mountedAnchorQuote
+ ) {
+ setMountedAnchorQuote(undefined);
+ }
+ const anchorFocusKey =
+ composerAnchor != null && composerAnchor.quote !== mountedAnchorQuote
+ ? `anchor:${composerAnchor.quote}`
+ : undefined;
+
+ const submitComment = async (
+ content: string,
+ context: CommentComposerContext,
+ ) => {
+ const submitted = content.trim();
+ setTopComposerError(undefined);
+ const result = await submit(content);
+ if (result === 'posted') {
+ // Text typed while the post was in flight stays in the draft.
+ if (draftRef.current.trim() === submitted) {
+ draftRef.current = '';
+ setDraft('');
+ onComposerDraftChange?.('', context);
+ }
+ } else if (result === 'failed') {
+ draftRef.current = submitted;
+ setDraft(submitted);
+ onComposerDraftChange?.(submitted, context);
+ setTopComposerError(t('@astryx.comments.postFailed'));
+ }
+ };
+
+ const loadOlder = async () => {
+ if (onLoadOlder == null || loadingOlderRef.current) {
+ return;
+ }
+ // The button and the failure Banner's Retry swap places; focus follows
+ // whichever is showing so it never drops to <body>.
+ const active = document.activeElement;
+ const hadFocus =
+ active != null &&
+ (active === loadOlderButtonRef.current ||
+ active === olderRetryRef.current);
+ loadingOlderRef.current = true;
+ setLoadingOlder(true);
+ let focusTarget: 'load' | 'retry' = 'load';
+ try {
+ await onLoadOlder();
+ // Commit now, so the control that replaced the old one can take focus.
+ flushSync(() => {
+ setOlderError(undefined);
+ setLoadingOlder(false);
+ });
+ } catch {
+ focusTarget = 'retry';
+ flushSync(() => {
+ setOlderError(t('@astryx.comments.olderFailed'));
+ // A new Banner per failure, so a failed retry announces again.
+ setOlderFailureCount(count => count + 1);
+ setLoadingOlder(false);
+ });
+ } finally {
+ loadingOlderRef.current = false;
+ }
+ if (hadFocus) {
+ const control =
+ focusTarget === 'retry'
+ ? olderRetryRef.current
+ : loadOlderButtonRef.current;
+ // With no earlier page left the button is gone; the region keeps focus.
+ (control ?? rootRef.current)?.focus();
+ }
+ };
+
+ const canCompose =
+ mode !== 'read-only' && composerPosition !== 'none' && onSubmit != null;
+ const composer = canCompose ? (
+ <CommentComposerBase
+ context={topComposerContext}
+ anchor={composerAnchor}
+ onAnchorDismiss={onComposerAnchorDismiss}
+ focusKey={anchorFocusKey}
+ value={draft}
+ onChange={next => {
+ draftRef.current = next;
+ setDraft(next);
+ setTopComposerError(undefined);
+ onComposerDraftChange?.(next, topComposerContext);
+ }}
+ onSubmit={next => void submitComment(next, topComposerContext)}
+ placeholder={
+ composerPlaceholder ?? t('@astryx.commentComposer.placeholder')
+ }
+ isSubmitting={value.isSubmitting}
+ error={topComposerError ?? composerError}
+ onRetryError={
+ topComposerError != null
+ ? () => void submitComment(draft, topComposerContext)
+ : undefined
+ }
+ highlightColor={highlightColor}
+ triggers={composerTriggers ?? []}
+ agentCommands={value.agentCommands}
+ hasEmojiPicker={hasEmojiPicker}
+ controls={composerControls}
+ onActionPendingChange={value.composerActionPendingChange}
+ onUploadImages={
+ onUploadImages == null
+ ? undefined
+ : files => onUploadImages(files, topComposerContext)
+ }
+ renderComposer={renderComposer}
+ />
+ ) : null;
+ const loadingComposer =
+ isLoading && mode !== 'read-only' && composerPosition !== 'none' ? (
+ <CommentComposerLoadingSkeleton
+ actionCount={
+ (onUploadImages == null ? 0 : 1) + (hasEmojiPicker ? 1 : 0)
+ }
+ />
+ ) : null;
+ const visibleComposer = isLoading ? loadingComposer : composer;
+
+ const isEmbedded = layout === 'embedded';
+ // A pane bleeds a card parent's Sections to the panel edge through the
+ // message list's padding; an embedded list has no list padding to cross.
+ const bleedsToPanelEdge = container === 'card' && !isEmbedded;
+ // Inside a host's Card or Popover, its border bounds the list, so the first
+ // and last threads drop their outer rules.
+ const dividersAt = (index: number): readonly ThreadDivider[] =>
+ isEmbedded && container === 'card'
+ ? THREAD_DIVIDERS.filter(
+ divider =>
+ !(divider === 'top' && index === 0 && !hasOlderComments) &&
+ !(divider === 'bottom' && index === timelineEntries.length - 1),
+ )
+ : THREAD_DIVIDERS;
+ const renderedEmptyState =
+ emptyState === undefined ? (
+ <EmptyState
+ title={t('@astryx.comments.emptyTitle')}
+ description={
+ canCompose
+ ? t('@astryx.comments.emptyDescription')
+ : t('@astryx.comments.emptyReadOnlyDescription')
+ }
+ isCompact
+ />
+ ) : (
+ emptyState
+ );
+ const timelineXstyle = [
+ styles.timeline,
+ bleedsToPanelEdge &&
+ (density === 'compact' ? styles.bleedCompact : styles.bleedBalanced),
+ ];
+
+ const loadingStack = (
+ <VStack
+ width={bleedsToPanelEdge ? undefined : '100%'}
+ xstyle={timelineXstyle}>
+ <CommentThreadLoadingSkeleton container={container} />
+ </VStack>
+ );
+ const timelineStack = (
+ <VStack
+ width={bleedsToPanelEdge ? undefined : '100%'}
+ gap={container === 'card' ? 0 : density === 'compact' ? 2 : 4}
+ xstyle={timelineXstyle}>
+ {hasOlderComments && (
+ <VStack gap={1} align="center" width="100%">
+ {olderError != null ? (
+ <ErrorBanner
+ key={olderFailureCount}
+ actionRef={olderRetryRef}
+ content={{
+ title: olderError,
+ actionLabel: t('@astryx.comments.retry'),
+ onAction: () => void loadOlder(),
+ }}
+ data-comments-older-error="banner"
+ />
+ ) : (
+ <Button
+ ref={loadOlderButtonRef}
+ label={t('@astryx.comments.loadOlder')}
+ variant="ghost"
+ size="sm"
+ isLoading={isLoadingOlder || loadingOlder}
+ isDisabled={onLoadOlder == null}
+ onClick={() => void loadOlder()}
+ />
+ )}
+ </VStack>
+ )}
+ {timelineEntries.map((entry, index) =>
+ entry.kind === 'event' ? (
+ <ActivityEventRow
+ key={`event-${entry.value.id}`}
+ event={entry.value}
+ renderEvent={renderEvent}
+ />
+ ) : (
+ <CommentRow
+ key={`comment-${entry.value.id}`}
+ comment={entry.value}
+ depth={0}
+ threadId={entry.value.id}
+ dividers={dividersAt(index)}
+ />
+ ),
+ )}
+ </VStack>
+ );
+ const listDensity = density === 'compact' ? 'compact' : 'balanced';
+ const isEmpty = timelineEntries.length === 0 && !hasOlderComments;
+
+ return (
+ <CommentsContextProvider value={value}>
+ <VStack
+ as="section"
+ ref={setRootRef}
+ tabIndex={-1}
+ aria-label={label}
+ aria-busy={isLoading || undefined}
+ gap={3}
+ width="100%"
+ height={isEmbedded ? undefined : '100%'}
+ {...rest}
+ {...mergeProps(
+ themeProps('comments', {layout, density, container}),
+ stylex.props(!isEmbedded && styles.root, xstyle),
+ className,
+ style,
+ )}>
+ {loadError != null && (
+ <Banner
+ status="error"
+ role="alert"
+ title={t('@astryx.comments.loadFailed')}
+ description={loadError}
+ container="section"
+ endContent={
+ onRetryLoad != null ? (
+ <Button
+ label={t('@astryx.comments.retry')}
+ variant="ghost"
+ size="sm"
+ clickAction={onRetryLoad}
+ />
+ ) : undefined
+ }
+ />
+ )}
+
+ {composerPosition === 'top' && visibleComposer}
+
+ {isEmbedded ? (
+ <>
+ {isLoading
+ ? loadingStack
+ : isEmpty
+ ? loadError != null
+ ? null
+ : renderedEmptyState
+ : timelineStack}
+ {composerPosition === 'bottom' && visibleComposer}
+ </>
+ ) : (
+ <ChatLayout
+ composer={
+ composerPosition === 'bottom' && visibleComposer != null ? (
+ <VStack width="100%" xstyle={styles.composerDock}>
+ {visibleComposer}
+ </VStack>
+ ) : null
+ }
+ density={listDensity}
+ emptyState={loadError != null ? null : renderedEmptyState}>
+ {isLoading ? (
+ <ChatMessageList
+ align="top"
+ density={listDensity}
+ gap={0}
+ isStreaming
+ aria-label={t('@astryx.comments.commentsLabel', {label})}>
+ {loadingStack}
+ </ChatMessageList>
+ ) : isEmpty ? null : (
+ <ChatMessageList
+ align="top"
+ density={listDensity}
+ gap={0}
+ aria-label={t('@astryx.comments.commentsLabel', {label})}>
+ {timelineStack}
+ </ChatMessageList>
+ )}
+ </ChatLayout>
+ )}
+
+ {dialogs}
+ </VStack>
+ </CommentsContextProvider>
+ );
+}
+
+Comments.displayName = 'Comments';
diff --git a/packages/lab/src/Comments/icons.tsx b/packages/lab/src/Comments/icons.tsx
index 48f30b65b0..7fad42ee94 100644
--- a/packages/lab/src/Comments/icons.tsx
+++ b/packages/lab/src/Comments/icons.tsx
@@ -27,6 +27,7 @@ export const COMMENT_ICON_KEYS = {
delete: 'comment:delete',
attach: 'comment:attach',
emoji: 'comment:emoji',
+ event: 'comment:event',
} as const;
export type CommentIconName = keyof typeof COMMENT_ICON_KEYS;
@@ -97,6 +98,11 @@ const FALLBACK_GLYPHS: Record<
'M8.5 14.5a4 4 0 0 0 7 0',
'M9 10h.01M15 10h.01',
]),
+ // A point on a timeline.
+ event: glyph([
+ 'M12 3v5.5M12 15.5V21',
+ 'M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z',
+ ]),
};
/**
diff --git a/packages/lab/src/Comments/index.ts b/packages/lab/src/Comments/index.ts
index ddca9bcbd5..e1cd88b72d 100644
--- a/packages/lab/src/Comments/index.ts
+++ b/packages/lab/src/Comments/index.ts
@@ -4,11 +4,13 @@
/**
* @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
+ * @input Imports Comments, CommentThread, CommentComposer, and their types
+ * @output Exports the lab Comments family
+ * @position Lab Comments entry point; re-exported by packages/lab/src/index.ts
*/
+export {Comments} from './Comments';
+export type {CommentsProps} from './Comments';
export {CommentThread} from './CommentThread';
export type {CommentThreadProps} from './CommentThread';
export {CommentComposer} from './CommentComposer';
@@ -33,4 +35,5 @@ export type {
CommentUploadedImage,
CommentUser,
CommentVersion,
+ CommentActivityEvent,
} from './types';
diff --git a/packages/lab/src/Comments/types.ts b/packages/lab/src/Comments/types.ts
index d1af4a7d36..5c8dfc4ac5 100644
--- a/packages/lab/src/Comments/types.ts
+++ b/packages/lab/src/Comments/types.ts
@@ -213,6 +213,18 @@ export interface CommentThreadData extends CommentData {
canResolve?: boolean;
}
+/** A timeline row for a status change or other activity on the item. */
+export interface CommentActivityEvent {
+ id: string;
+ /** What happened, as a sentence: "Status changed to Ready for review". */
+ label: string;
+ description?: string;
+ createdAt: string | number;
+ actor?: CommentUser;
+ /** Where the event's time links. */
+ href?: string;
+}
+
/** Which composer a callback came from. */
export type CommentComposerContext =
| {
diff --git a/packages/lab/src/Comments/utils.ts b/packages/lab/src/Comments/utils.ts
index ed141d7341..fdae951ba9 100644
--- a/packages/lab/src/Comments/utils.ts
+++ b/packages/lab/src/Comments/utils.ts
@@ -3,10 +3,11 @@
/**
* @file utils.ts
* @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
+ * @output Exports the Comments family's pure helpers: element ids, Markdown
+ * serialization of images, draft appends, timeline ordering, and focus
+ * bookkeeping
+ * @position Internal helpers shared by Comments, CommentThread, and
+ * CommentComposer; not exported from the package
*/
import type {
@@ -28,6 +29,11 @@ export function replyComposerId(parentId: string): string {
return `${commentAnchorId(parentId)}-reply-composer`;
}
+/** The element id of an activity event row. */
+export function eventAnchorId(eventId: string): string {
+ return `comments-event-${encodeURIComponent(eventId)}`;
+}
+
/** Whether focus is inside `region`, or already lost to <body>. */
export function shouldRestoreFocusFrom(region: Element | null): boolean {
const active = document.activeElement;
@@ -85,6 +91,15 @@ export function appendDraftInline(value: string, content: string): string {
return `${value} ${content}`;
}
+/** A createdAt value as epoch milliseconds; seconds are scaled up. */
+export function timelineTime(value: string | number): number {
+ if (typeof value === 'number') {
+ return value < 1_000_000_000_000 ? value * 1_000 : value;
+ }
+ const parsed = Date.parse(value);
+ return Number.isNaN(parsed) ? 0 : parsed;
+}
+
/**
* 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.
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 71539fe1a3..9e69dbc58a 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -40,8 +40,10 @@ export {
type CommentPinProps,
} from './CommentPin';
-// CommentThread and CommentComposer — standalone comment conversation surfaces
+// Comments family — a panel, standalone thread, and controlled composer
export {
+ Comments,
+ type CommentsProps,
CommentThread,
type CommentThreadProps,
CommentComposer,
@@ -65,6 +67,7 @@ export {
type CommentUploadedImage,
type CommentUser,
type CommentVersion,
+ type CommentActivityEvent,
} from './Comments';
// TransferList — controlled dual-panel collection input