Skip to content

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

TypeScript

feat(lab): add CommentComposer (#7606)

Ernest5c208f6a4377
diff --git a/.changeset/lab-comment-composer-catalog.md b/.changeset/lab-comment-composer-catalog.md
new file mode 100644
index 0000000000..50009bb09e
--- /dev/null
+++ b/.changeset/lab-comment-composer-catalog.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] i18n catalog: add the English messages used by the Lab CommentComposer for its input, image upload, inline quote, emoji action, cancel action, and retry affordance.
+
+@ernestt
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 2a55857bb3..feae13873b 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -353,5 +353,9 @@
{
"component": "lab/CommentPin",
"reason": "CommentPin sets its fixed 4px speech-bubble corner with the logical border-end-start-radius longhand (the other corners use logical longhands too), so it mirrors under RTL by construction, and switches transform origin from left-bottom to right-bottom. Absolute examples place the inline-start edge at the anchor and translate only on the block axis, so bottom-start placement mirrors without a physical inline offset. Its flex row, avatar overlap, and padding use logical properties; avatars and the numeric count have no directional glyph or keyboard semantics to reverse."
+ },
+ {
+ "component": "lab/CommentComposer",
+ "reason": "CommentComposer stacks an optional quoted passage, the core ChatComposer input, and a footer row of attach, emoji, product controls, and the core ChatSendButton. Every inset, gap, and corner is a logical property or a flex gap, its glyphs (attach, emoji, close) are non-directional, and its only positioned affordances are core Popover and typeahead menus, which the core audit covers. Nothing it owns has a horizontal semantic to mirror."
}
]
diff --git a/apps/storybook/stories/Comments.stories.tsx b/apps/storybook/stories/Comments.stories.tsx
new file mode 100644
index 0000000000..15be2e5400
--- /dev/null
+++ b/apps/storybook/stories/Comments.stories.tsx
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {CommentComposer} from '@astryxdesign/lab';
+import CommentComposerShowcase from '../../../packages/lab/blocks/CommentComposerShowcase';
+
+const meta: Meta = {
+ title: 'Lab/Comments',
+ component: CommentComposer,
+ tags: ['autodocs'],
+ parameters: {layout: 'centered'},
+};
+
+export default meta;
+type Story = StoryObj;
+
+/** A controlled standalone composer that posts into a short list. */
+export const Composer: Story = {
+ render: () => <CommentComposerShowcase />,
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index aeb873cf68..919670841f 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -556,6 +556,11 @@
"path": "components/lab/code-editor",
"aliases": []
},
+ {
+ "name": "component-lab-comment-composer",
+ "path": "components/lab/comment-composer",
+ "aliases": []
+ },
{
"name": "component-lab-comment-pin",
"path": "components/lab/comment-pin",
@@ -4250,6 +4255,11 @@
"path": "showcases/command-palette/default",
"aliases": []
},
+ {
+ "name": "showcase-comment-composer-new-comment",
+ "path": "showcases/comment-composer/new-comment",
+ "aliases": []
+ },
{
"name": "showcase-comment-pin-avatar-first-annotations",
"path": "showcases/comment-pin/avatar-first-annotations",
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index b863b96873..881ec86875 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1782,5 +1782,53 @@
"@astryx.emojiPicker.groupFlags": {
"defaultMessage": "Flags",
"description": "Heading of the Unicode CLDR emoji group of flags in a lab EmojiPicker."
+ },
+ "@astryx.comments.retry": {
+ "defaultMessage": "Retry",
+ "description": "Action on an error Banner in a lab Comments panel or comment composer that repeats the action that failed."
+ },
+ "@astryx.commentComposer.placeholder": {
+ "defaultMessage": "Write a comment…",
+ "description": "Default placeholder of a lab CommentComposer, the input for a new comment in a discussion."
+ },
+ "@astryx.commentComposer.noAgents": {
+ "defaultMessage": "No agents",
+ "description": "Shown in a lab CommentComposer's slash-command menu when no AI agent matches what was typed after `/`."
+ },
+ "@astryx.commentComposer.agents": {
+ "defaultMessage": "Agents",
+ "description": "Accessible name of a lab CommentComposer's slash-command menu, which lists the AI agents a comment can address."
+ },
+ "@astryx.commentComposer.uploadFailed": {
+ "defaultMessage": "Images couldn't be added",
+ "description": "Error Banner title in a lab CommentComposer when uploading attached images failed; a Retry action follows."
+ },
+ "@astryx.commentComposer.imagesOnly": {
+ "defaultMessage": "Only image files can be added",
+ "description": "Error Banner title in a lab CommentComposer when a non-image file was attached, pasted, or dropped."
+ },
+ "@astryx.commentComposer.chooseImages": {
+ "defaultMessage": "Choose images",
+ "description": "Action on a lab CommentComposer's error Banner that opens the file chooser for images."
+ },
+ "@astryx.commentComposer.imageAlt": {
+ "defaultMessage": "Image attachment",
+ "description": "Alt text a lab CommentComposer writes into the comment for an uploaded image that came with none."
+ },
+ "@astryx.commentComposer.removeQuote": {
+ "defaultMessage": "Remove quoted text",
+ "description": "Button beside the quoted passage in a lab CommentComposer that drops the quote from the new inline comment."
+ },
+ "@astryx.commentComposer.attachImages": {
+ "defaultMessage": "Attach images",
+ "description": "Button in a lab CommentComposer that opens the file chooser to add images to the comment."
+ },
+ "@astryx.commentComposer.addEmoji": {
+ "defaultMessage": "Add emoji",
+ "description": "Button in a lab CommentComposer that opens the emoji picker, and the accessible name of that picker's popover."
+ },
+ "@astryx.commentComposer.cancel": {
+ "defaultMessage": "Cancel",
+ "description": "Text button beside the label of a lab CommentComposer that is editing an existing comment; it discards the edit."
}
}
diff --git a/packages/lab/blocks/CommentComposerShowcase.doc.mjs b/packages/lab/blocks/CommentComposerShowcase.doc.mjs
new file mode 100644
index 0000000000..bb71311782
--- /dev/null
+++ b/packages/lab/blocks/CommentComposerShowcase.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'New comment',
+ displayName: 'New comment',
+ description:
+ 'A comment composer quoting the passage it comments on: type, add an emoji, and post with Enter or Post.',
+ exampleFor: 'CommentComposer',
+ isReady: true,
+ isShowcase: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['CommentComposer', 'VStack', 'Text'],
+};
diff --git a/packages/lab/blocks/CommentComposerShowcase.tsx b/packages/lab/blocks/CommentComposerShowcase.tsx
new file mode 100644
index 0000000000..ffa194221d
--- /dev/null
+++ b/packages/lab/blocks/CommentComposerShowcase.tsx
@@ -0,0 +1,45 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input A controlled draft and a list of posted comments
+ * @output A comment composer that posts into a short list above it
+ * @position Lab CommentComposer's docsite showcase and copyable CLI block
+ */
+
+import {useState} from 'react';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {CommentComposer} from '@astryxdesign/lab';
+
+export default function CommentComposerShowcase() {
+ const [draft, setDraft] = useState('');
+ const [posted, setPosted] = useState<string[]>([]);
+
+ return (
+ <VStack gap={3} width={420}>
+ {posted.length === 0 ? (
+ <Text type="supporting" color="secondary">
+ Nothing posted yet.
+ </Text>
+ ) : (
+ posted.map((body, index) => (
+ <Text key={index} type="body">
+ {body}
+ </Text>
+ ))
+ )}
+ <CommentComposer
+ value={draft}
+ onChange={setDraft}
+ onSubmit={body => {
+ setPosted(current => [...current, body]);
+ setDraft('');
+ }}
+ anchor={{quote: 'Guardrail alerts page the release oncall.'}}
+ onAnchorDismiss={() => {}}
+ />
+ </VStack>
+ );
+}
diff --git a/packages/lab/src/Comments/CommentComposer.doc.mjs b/packages/lab/src/Comments/CommentComposer.doc.mjs
new file mode 100644
index 0000000000..aaa8d0db2a
--- /dev/null
+++ b/packages/lab/src/Comments/CommentComposer.doc.mjs
@@ -0,0 +1,177 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// @ts-check
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'CommentComposer',
+ displayName: 'Comment Composer',
+ group: 'Comments',
+ category: 'Chat',
+ keywords: ['comment box', 'comment input', 'reply box', 'composer'],
+ description:
+ 'A comment composer: an input that grows to five lines, with typeahead triggers and pasted or dropped images, above attach and emoji buttons and Post. Controlled: your app owns the draft.',
+ usage: {
+ description:
+ 'A comment composer writes a new comment. Use it where comments start outside a Comments panel, such as a new margin comment on a text selection. Comments and CommentThread use it for new comments, replies, and edits.',
+ anatomy: [
+ {
+ name: 'Quoted passage',
+ required: false,
+ description:
+ 'The passage a new inline comment attaches to, in a muted card above the input.',
+ },
+ {
+ name: 'Input',
+ required: true,
+ description:
+ 'Grows with its text to five lines. Enter posts; Shift+Enter adds a line.',
+ },
+ {
+ name: 'Footer',
+ required: true,
+ description:
+ 'Attach images (with `onUploadImages`), Add emoji, your `controls`, then Post at the end.',
+ },
+ ],
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Clear the draft once the comment posts, and keep it when posting fails: show `error` with `onRetry`.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Name the input for its context with `label` when the placeholder alone would be vague, such as "Reply to Maya Chen".',
+ },
+ {
+ guidance: false,
+ description:
+ 'Disable the composer while posting. Pass `isSubmitting`: the input keeps focus, and Post stays focusable but refuses a second press.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Put long instructions in the placeholder. It disappears as the viewer types; keep guidance in surrounding text.',
+ },
+ ],
+ },
+ props: [
+ {
+ name: 'value',
+ type: 'string',
+ required: true,
+ description: 'The draft, controlled.',
+ },
+ {
+ name: 'onChange',
+ type: '(value: string) => void',
+ required: true,
+ description:
+ 'Called with the new draft as the viewer types, picks an emoji, or uploads an image.',
+ },
+ {
+ name: 'onSubmit',
+ type: '(value: string) => void',
+ required: true,
+ description:
+ 'Posts the draft from Enter or Post. Empty drafts never post.',
+ },
+ {
+ name: 'placeholder',
+ type: 'string',
+ description:
+ 'Placeholder, and the input’s accessible name unless `label` is set. Defaults to the localized "Write a comment…".',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible name of the input.',
+ },
+ {
+ name: 'isSubmitting',
+ type: 'boolean',
+ default: 'false',
+ description:
+ 'Holds the attach and emoji buttons while a post is in flight, and makes Post refuse a second press. The composer reports busy.',
+ },
+ {
+ name: 'error',
+ type: 'string',
+ description: 'Shows an error Banner above the composer.',
+ },
+ {
+ name: 'onRetry',
+ type: '() => void',
+ description: 'Adds Retry to the `error` Banner.',
+ },
+ {
+ name: 'anchor',
+ type: 'CommentAnchor',
+ description:
+ 'The passage a new inline comment attaches to, quoted above the input.',
+ },
+ {
+ name: 'onAnchorDismiss',
+ type: '() => void',
+ description:
+ 'Adds Remove quoted text to the quoted passage; clear `anchor` when it is called.',
+ },
+ {
+ name: 'highlightColor',
+ type: "'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'",
+ default: "'yellow'",
+ description:
+ 'The palette color your app highlights passages in; the quote draws its rule in it.',
+ },
+ {
+ name: 'onUploadImages',
+ type: '(files: readonly File[]) => CommentUploadedImage[] | Promise<CommentUploadedImage[]>',
+ description:
+ 'Uploads attached, pasted, or dropped images and appends them to the draft as Markdown. Adds the attach button.',
+ },
+ {
+ name: 'triggers',
+ type: 'readonly ChatComposerTrigger[]',
+ description: 'Typeahead triggers, such as an `@` people search.',
+ },
+ {
+ name: 'agentCommands',
+ type: 'readonly CommentAgentCommand[]',
+ description: 'Agents the comment can address: typing `/` lists them.',
+ },
+ {
+ name: 'hasEmojiPicker',
+ type: 'boolean',
+ default: 'true',
+ description: 'Whether the Add emoji button shows.',
+ },
+ {
+ name: 'controls',
+ type: 'ReactNode',
+ description: 'Product-owned controls after the attach and emoji buttons.',
+ },
+ ],
+ examples: [
+ {
+ label: 'New comment',
+ code: `import {useState} from 'react';
+import {CommentComposer} from '@astryxdesign/lab';
+
+export default function Example() {
+ const [draft, setDraft] = useState('');
+ return (
+ <CommentComposer
+ value={draft}
+ onChange={setDraft}
+ onSubmit={body => {
+ post(body);
+ setDraft('');
+ }}
+ />
+ );
+}`,
+ },
+ ],
+};
diff --git a/packages/lab/src/Comments/CommentComposer.test.tsx b/packages/lab/src/Comments/CommentComposer.test.tsx
new file mode 100644
index 0000000000..320e28bcf9
--- /dev/null
+++ b/packages/lab/src/Comments/CommentComposer.test.tsx
@@ -0,0 +1,255 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import {act, fireEvent, render, screen, within} from '@testing-library/react';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+// The full emoji set renders slowly in jsdom; the composer only needs a few.
+vi.mock('../EmojiPicker/emojiData', () => ({
+ EMOJI_GROUPS: [
+ {
+ name: 'Activities',
+ emojis: [
+ ['🎉', 'Party popper', 'celebration tada'],
+ ['🎈', 'Balloon', 'celebration'],
+ ],
+ },
+ ],
+}));
+
+import {CommentComposer} from './CommentComposer';
+
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+beforeAll(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ Object.defineProperty(HTMLElement.prototype, 'matches', {
+ configurable: true,
+ writable: true,
+ value(this: HTMLElement, selector: string): boolean {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ },
+ });
+});
+
+afterAll(() => {
+ Object.defineProperty(HTMLElement.prototype, 'matches', {
+ configurable: true,
+ writable: true,
+ value: originalMatches,
+ });
+});
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+ Element.prototype.scrollIntoView = () => {};
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+async function settle() {
+ await act(() => new Promise<void>(resolve => setTimeout(resolve, 0)));
+}
+
+describe('CommentComposer', () => {
+ it('posts the draft from Post, and never an empty one', async () => {
+ const onSubmit = vi.fn();
+ const {rerender} = render(
+ <CommentComposer value="" onChange={() => {}} onSubmit={onSubmit} />,
+ );
+ const post = screen.getByRole('button', {name: /send/i});
+ expect(post).toBeDisabled();
+ rerender(
+ <CommentComposer
+ value="Looks good"
+ onChange={() => {}}
+ onSubmit={onSubmit}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: /send/i}));
+ expect(onSubmit).toHaveBeenCalledWith('Looks good');
+ });
+
+ it('shows the placeholder as the input’s name, and keeps Post focusable while submitting', () => {
+ const onSubmit = vi.fn();
+ const {container} = render(
+ <CommentComposer
+ value="Draft"
+ onChange={() => {}}
+ onSubmit={onSubmit}
+ isSubmitting
+ />,
+ );
+ expect(
+ screen.getByRole('textbox', {name: 'Write a comment…'}),
+ ).toBeTruthy();
+ // Busy never disables Post, so focus can't drop to <body>; a second press
+ // is refused, and the composer reports busy.
+ const post = screen.getByRole('button', {name: /send/i});
+ expect(post).not.toBeDisabled();
+ fireEvent.click(post);
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(container.querySelector('.astryx-comment-composer')).toHaveAttribute(
+ 'aria-busy',
+ 'true',
+ );
+ // A button with a tooltip stays focusable while disabled.
+ expect(screen.getByRole('button', {name: 'Add emoji'})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+
+ it('appends a picked emoji to the draft', async () => {
+ function Host() {
+ const [value, setValue] = useState('Ship it');
+ return (
+ <>
+ <output data-testid="draft">{value}</output>
+ <CommentComposer
+ value={value}
+ onChange={setValue}
+ onSubmit={() => {}}
+ />
+ </>
+ );
+ }
+ render(<Host />);
+ fireEvent.click(screen.getByRole('button', {name: 'Add emoji'}));
+ await settle();
+ // The frequent row lists it before its group does.
+ fireEvent.click(
+ screen.getAllByRole('button', {name: 'Party popper', hidden: true})[0],
+ );
+ expect(screen.getByTestId('draft').textContent).toBe('Ship it 🎉');
+ });
+
+ it('uploads attached images and appends them as Markdown', async () => {
+ const onChange = vi.fn();
+ const onUploadImages = vi
+ .fn()
+ .mockResolvedValue([{url: 'https://example.com/a b.png', alt: 'Chart'}]);
+ render(
+ <CommentComposer
+ value="See this"
+ onChange={onChange}
+ onSubmit={() => {}}
+ onUploadImages={onUploadImages}
+ />,
+ );
+ expect(screen.getByRole('button', {name: 'Attach images'})).toBeTruthy();
+ const input = document.querySelector('input[type="file"]');
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('File input not found');
+ }
+ const file = new File(['png'], 'chart.png', {type: 'image/png'});
+ await act(async () => {
+ fireEvent.change(input, {target: {files: [file]}});
+ await Promise.resolve();
+ });
+ await settle();
+ expect(onUploadImages).toHaveBeenCalledWith([file]);
+ expect(onChange).toHaveBeenCalledWith(
+ 'See this\n\n![Chart](https://example.com/a%20b.png)',
+ );
+ });
+
+ it('refuses files that are not images', async () => {
+ const onUploadImages = vi.fn();
+ render(
+ <CommentComposer
+ value=""
+ onChange={() => {}}
+ onSubmit={() => {}}
+ onUploadImages={onUploadImages}
+ />,
+ );
+ const input = document.querySelector('input[type="file"]');
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('File input not found');
+ }
+ await act(async () => {
+ fireEvent.change(input, {
+ target: {
+ files: [new File(['%PDF'], 'doc.pdf', {type: 'application/pdf'})],
+ },
+ });
+ });
+ expect(onUploadImages).not.toHaveBeenCalled();
+ expect(screen.getByRole('alert').textContent).toContain(
+ 'Only image files can be added',
+ );
+ });
+
+ it('shows an error with Retry, and a quoted passage the viewer can remove', () => {
+ const onRetry = vi.fn();
+ const onAnchorDismiss = vi.fn();
+ render(
+ <CommentComposer
+ value="Draft"
+ onChange={() => {}}
+ onSubmit={() => {}}
+ error="Your comment couldn't be posted."
+ onRetry={onRetry}
+ anchor={{quote: 'Guardrail alerts page within five minutes.'}}
+ onAnchorDismiss={onAnchorDismiss}
+ highlightColor="green"
+ />,
+ );
+ const alert = screen.getByRole('alert');
+ fireEvent.click(within(alert).getByRole('button', {name: 'Retry'}));
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ expect(
+ document
+ .querySelector('[data-composer-anchor="quote"] [data-quote-rule]')
+ ?.getAttribute('data-highlight-color'),
+ ).toBe('green');
+ fireEvent.click(screen.getByRole('button', {name: 'Remove quoted text'}));
+ expect(onAnchorDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves the emoji button out when hasEmojiPicker is false, and adds controls', () => {
+ render(
+ <CommentComposer
+ value=""
+ onChange={() => {}}
+ onSubmit={() => {}}
+ hasEmojiPicker={false}
+ controls={<button type="button">Pin to moment</button>}
+ />,
+ );
+ expect(screen.queryByRole('button', {name: 'Add emoji'})).toBeNull();
+ expect(screen.getByRole('button', {name: 'Pin to moment'})).toBeTruthy();
+ });
+});
diff --git a/packages/lab/src/Comments/CommentComposer.tsx b/packages/lab/src/Comments/CommentComposer.tsx
new file mode 100644
index 0000000000..cc8431e2ee
--- /dev/null
+++ b/packages/lab/src/Comments/CommentComposer.tsx
@@ -0,0 +1,680 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CommentComposer.tsx
+ * @input Uses React, StyleX, ChatComposer, ChatComposerInput, ChatSendButton,
+ * Popover, IconButton, Card, EmojiPicker, Typeahead's static source
+ * @output Exports CommentComposer and CommentComposerProps, and the internal
+ * CommentComposerBase the Comments family's threads use
+ * @position A comment's two-row composer: the input (growing to five lines,
+ * with typeahead triggers and pasted or dropped images) above small attach
+ * and emoji buttons and Post. Used standalone, by Comments for new
+ * comments, and by CommentThread for replies and edits.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Comments/index.ts (exports)
+ * - /packages/lab/src/Comments/CommentComposer.doc.mjs
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+ type ReactNode,
+ type Ref,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '@astryxdesign/core';
+import {Avatar} from '@astryxdesign/core/Avatar';
+import {Card} from '@astryxdesign/core/Card';
+import {
+ ChatComposer,
+ ChatComposerInput,
+ ChatSendButton,
+ type ChatComposerInputHandle,
+ type ChatComposerTrigger,
+ type ChatComposerTriggerItem,
+} from '@astryxdesign/core/Chat';
+import {Icon} from '@astryxdesign/core/Icon';
+import {IconButton} from '@astryxdesign/core/IconButton';
+import {HStack, StackItem, VStack} from '@astryxdesign/core/Layout';
+import {Popover} from '@astryxdesign/core/Popover';
+import {Text} from '@astryxdesign/core/Text';
+import {createStaticSource} from '@astryxdesign/core/Typeahead';
+import {radiusVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+import {useTranslator} from '@astryxdesign/core/i18n';
+import {EmojiPicker} from '../EmojiPicker';
+import {agentToken} from './CommentMarkdown';
+import {
+ ErrorBanner,
+ MetadataActionLink,
+ MetadataSeparator,
+ QuotedPassage,
+ type ErrorBannerContent,
+} from './CommentParts';
+import {CommentIcon} from './icons';
+import {appendDraftBlock, appendDraftInline, imagesToMarkdown} from './utils';
+import type {
+ CommentAgentCommand,
+ CommentAnchor,
+ CommentComposerContext,
+ CommentComposerRenderProps,
+ CommentHighlightColor,
+ CommentUploadedImage,
+} from './types';
+
+const styles = stylex.create({
+ // Concentric with the composer: its container radius less its compact
+ // padding is the inner radius.
+ quoteCard: {
+ borderRadius: radiusVars['--radius-inner'],
+ },
+});
+
+// ChatComposer's themeable radius variable, set on its frame so the body and
+// its concentric inner radius both follow: comment composers use the
+// container radius instead of the rounder chat radius.
+const COMPOSER_RADIUS_STYLE: CSSProperties & Record<`--${string}`, string> = {
+ '--_chat-composer-radius': radiusVars['--radius-container'],
+};
+
+/* The picker's width is the Popover's, which the Popover clamps to the room
+ beside its trigger; the picker fills whatever it gets. */
+const PICKER_WIDTH = `calc(${spacingVars['--spacing-8']} * 11)`;
+
+/* Clicks on these keep their own meaning inside the composer; a click anywhere
+ else in it focuses the input. */
+const COMPOSER_CONTROL_SELECTOR = [
+ 'a[href]',
+ 'button',
+ 'input',
+ 'label',
+ 'select',
+ 'textarea',
+ '[contenteditable="true"]',
+ '[role="button"]',
+ '[role="link"]',
+ '[role="menuitem"]',
+ '[role="tab"]',
+ '[role="textbox"]',
+].join(', ');
+/* A layer the composer opens (the picker, a tooltip) renders inside it but is
+ not part of its typing surface. */
+const COMPOSER_LAYER_SELECTOR = '[popover], [role="dialog"]';
+
+const NO_TRIGGERS: readonly ChatComposerTrigger[] = [];
+const NO_AGENT_COMMANDS: readonly CommentAgentCommand[] = [];
+
+type AgentCommandItem = ChatComposerTriggerItem & {
+ auxiliaryData: CommentAgentCommand;
+};
+
+function renderAgentCommandItem(item: ChatComposerTriggerItem): ReactNode {
+ const agent = (item as AgentCommandItem).auxiliaryData;
+ return (
+ <HStack gap={2} align="center">
+ <Avatar
+ name={agent.name}
+ src={agent.logoUrl}
+ size="sm"
+ shape="rounded"
+ tooltip={false}
+ />
+ <VStack gap={0.5}>
+ <Text weight="semibold">{`/${agent.command} <prompt>`}</Text>
+ <Text type="supporting" color="secondary">
+ {`${agent.name} · ${agent.description}`}
+ </Text>
+ </VStack>
+ </HStack>
+ );
+}
+
+/** The `/` menu of the agents a comment can address, or null for none. */
+function useAgentCommandTrigger(
+ agents: readonly CommentAgentCommand[],
+): ChatComposerTrigger | null {
+ const t = useTranslator();
+ const noAgentsText = t('@astryx.commentComposer.noAgents');
+ const agentsLabel = t('@astryx.commentComposer.agents');
+ return useMemo(() => {
+ if (agents.length === 0) {
+ return null;
+ }
+ const items: AgentCommandItem[] = agents.map(agent => ({
+ id: agent.command,
+ label: `/${agent.command}`,
+ auxiliaryData: agent,
+ }));
+ return {
+ character: '/',
+ searchSource: createStaticSource(items, {
+ keywords: item => [item.auxiliaryData.command, item.auxiliaryData.name],
+ }),
+ renderItem: renderAgentCommandItem,
+ onSelect: item => agentToken((item as AgentCommandItem).auxiliaryData),
+ emptySearchResultsText: noAgentsText,
+ menuLabel: agentsLabel,
+ };
+ }, [agents, agentsLabel, noAgentsText]);
+}
+
+/** Props the family's threads pass to their composers. */
+export interface CommentComposerBaseProps {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: (value: string) => void;
+ placeholder: string;
+ label?: string;
+ isSubmitting: boolean;
+ error?: string;
+ /** Adds a Retry action to `error`'s Banner. */
+ onRetryError?: () => void;
+ onCancel?: () => void;
+ contextLabel?: string;
+ context: CommentComposerContext;
+ anchor?: CommentAnchor;
+ onAnchorDismiss?: () => void;
+ highlightColor: CommentHighlightColor;
+ onUploadImages?: (
+ files: readonly File[],
+ ) =>
+ readonly CommentUploadedImage[] | Promise<readonly CommentUploadedImage[]>;
+ triggers: readonly ChatComposerTrigger[];
+ agentCommands: readonly CommentAgentCommand[];
+ hasEmojiPicker: boolean;
+ controls?: ReactNode;
+ /** Focuses the input whenever it changes, e.g. when Reply opens it. */
+ focusKey?: string;
+ /** Reports an upload in flight, so a thread can hold its other actions. */
+ onActionPendingChange?: (isPending: boolean) => void;
+ renderComposer?: (props: CommentComposerRenderProps) => ReactNode;
+ rootRef?: Ref<HTMLElement>;
+ rootProps?: Omit<BaseProps<HTMLElement>, 'onChange' | 'onSubmit'>;
+}
+
+/** The composer every Comments surface shares. */
+export function CommentComposerBase({
+ anchor,
+ agentCommands,
+ context,
+ contextLabel,
+ controls,
+ error,
+ focusKey,
+ hasEmojiPicker,
+ highlightColor,
+ isSubmitting,
+ label,
+ onActionPendingChange,
+ onAnchorDismiss,
+ onCancel,
+ onChange,
+ onRetryError,
+ onSubmit,
+ onUploadImages,
+ placeholder,
+ renderComposer,
+ rootProps,
+ rootRef,
+ triggers: hostTriggers,
+ value,
+}: CommentComposerBaseProps) {
+ const t = useTranslator();
+ const agentCommandTrigger = useAgentCommandTrigger(agentCommands);
+ const triggers = useMemo(
+ () =>
+ agentCommandTrigger == null
+ ? [...hostTriggers]
+ : [...hostTriggers, agentCommandTrigger],
+ [agentCommandTrigger, hostTriggers],
+ );
+ const latestValueRef = useRef(value);
+ latestValueRef.current = value;
+ const isMountedRef = useRef(true);
+ const actionPendingRef = useRef(false);
+ const imageInputRef = useRef<HTMLInputElement>(null);
+ const inputRef = useRef<ChatComposerInputHandle | null>(null);
+ // Focus lands once per `focusKey`, when the input attaches: the handle ref
+ // re-attaches on commits, and the last key focused guards against a repeat.
+ const focusedKeyRef = useRef<string | undefined>(undefined);
+ const attachInput = useCallback(
+ (handle: ChatComposerInputHandle | null) => {
+ inputRef.current = handle;
+ if (focusKey == null) {
+ focusedKeyRef.current = undefined;
+ } else if (handle != null && focusedKeyRef.current !== focusKey) {
+ focusedKeyRef.current = focusKey;
+ handle.focus();
+ }
+ },
+ [focusKey],
+ );
+ const [actionError, setActionError] = useState<ErrorBannerContent>();
+ const [isActionPending, setIsActionPending] = useState(false);
+ const [isPickerOpen, setIsPickerOpen] = useState(false);
+
+ const updateActionPending = useCallback(
+ (nextPending: boolean) => {
+ if (actionPendingRef.current === nextPending) {
+ return;
+ }
+ actionPendingRef.current = nextPending;
+ setIsActionPending(nextPending);
+ onActionPendingChange?.(nextPending);
+ },
+ [onActionPendingChange],
+ );
+ useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ if (actionPendingRef.current) {
+ actionPendingRef.current = false;
+ onActionPendingChange?.(false);
+ }
+ };
+ }, [onActionPendingChange]);
+
+ const uploadImages = async (files: readonly File[]) => {
+ if (onUploadImages == null || files.length === 0) {
+ return;
+ }
+ setActionError(undefined);
+ try {
+ const uploaded = await onUploadImages(files);
+ if (!isMountedRef.current) {
+ return;
+ }
+ const markdown = imagesToMarkdown(
+ uploaded,
+ t('@astryx.commentComposer.imageAlt'),
+ );
+ if (markdown !== '') {
+ onChange(appendDraftBlock(latestValueRef.current, markdown));
+ }
+ } catch {
+ if (isMountedRef.current) {
+ setActionError({
+ title: t('@astryx.commentComposer.uploadFailed'),
+ actionLabel: t('@astryx.comments.retry'),
+ onAction: () => beginImageUpload(files),
+ });
+ }
+ } finally {
+ if (isMountedRef.current) {
+ updateActionPending(false);
+ }
+ }
+ };
+
+ const beginImageUpload = (files: readonly File[]) => {
+ if (onUploadImages == null || files.length === 0) {
+ return;
+ }
+ const images = files.filter(file => file.type.startsWith('image/'));
+ if (images.length !== files.length) {
+ setActionError({
+ title: t('@astryx.commentComposer.imagesOnly'),
+ actionLabel: t('@astryx.commentComposer.chooseImages'),
+ onAction: () => imageInputRef.current?.click(),
+ });
+ return;
+ }
+ updateActionPending(true);
+ void uploadImages(images);
+ };
+
+ // Busy states never disable the input: a disabled contenteditable drops
+ // focus to <body> mid-submit. Duplicate submits are refused here instead.
+ const isBusy = isSubmitting || isActionPending;
+ const submitInput = (nextValue: string) => {
+ if (isBusy || nextValue.trim() === '') {
+ return;
+ }
+ onSubmit(nextValue);
+ };
+
+ const errorBanner: ErrorBannerContent | undefined =
+ error != null
+ ? {
+ title: error,
+ actionLabel:
+ onRetryError != null ? t('@astryx.comments.retry') : undefined,
+ onAction: onRetryError,
+ }
+ : actionError;
+
+ const composer =
+ renderComposer != null ? (
+ renderComposer({
+ value,
+ onChange,
+ onSubmit,
+ placeholder,
+ isSubmitting,
+ error,
+ contextLabel,
+ context,
+ onCancel,
+ })
+ ) : (
+ <VStack gap={1} width="100%" aria-busy={isBusy || undefined}>
+ {errorBanner != null && (
+ <ErrorBanner
+ content={errorBanner}
+ // The Banner unmounts once the retry starts; keep focus in the input.
+ onBeforeAction={() => inputRef.current?.focus()}
+ data-composer-error="banner"
+ />
+ )}
+ <ChatComposer
+ value={value}
+ onChange={onChange}
+ onSubmit={submitInput}
+ placeholder={placeholder}
+ density="compact"
+ elevation="none"
+ style={COMPOSER_RADIUS_STYLE}
+ input={
+ <VStack gap={1} width="100%">
+ {/* The quoted passage leads the new comment, in a muted card. */}
+ {anchor != null && (
+ <Card
+ variant="muted"
+ elevation="none"
+ padding={2}
+ width="100%"
+ xstyle={styles.quoteCard}
+ data-composer-anchor="quote">
+ <HStack gap={1} align="start" width="100%">
+ <StackItem size="fill">
+ <QuotedPassage
+ quote={anchor.quote}
+ highlightColor={highlightColor}
+ />
+ </StackItem>
+ {onAnchorDismiss != null && (
+ <IconButton
+ label={t('@astryx.commentComposer.removeQuote')}
+ tooltip={t('@astryx.commentComposer.removeQuote')}
+ variant="ghost"
+ size="sm"
+ icon={<Icon icon="close" />}
+ onClick={onAnchorDismiss}
+ />
+ )}
+ </HStack>
+ </Card>
+ )}
+ <ChatComposerInput
+ handleRef={attachInput}
+ value={value}
+ onChange={onChange}
+ onSubmit={submitInput}
+ placeholder={placeholder}
+ triggers={triggers}
+ hasHistory={false}
+ pasteAsToken={false}
+ maxRows={5}
+ onFiles={onUploadImages != null ? beginImageUpload : undefined}
+ label={label ?? placeholder}
+ />
+ </VStack>
+ }
+ footerActions={
+ <HStack gap={0.5} align="center">
+ {onUploadImages != null && (
+ <>
+ {/* FileInput has no icon-only trigger. */}
+ <input
+ ref={imageInputRef}
+ type="file"
+ accept="image/*"
+ multiple
+ hidden
+ disabled={isBusy}
+ onChange={event => {
+ const files = Array.from(event.currentTarget.files ?? []);
+ event.currentTarget.value = '';
+ beginImageUpload(files);
+ }}
+ />
+ <IconButton
+ label={t('@astryx.commentComposer.attachImages')}
+ tooltip={t('@astryx.commentComposer.attachImages')}
+ variant="ghost"
+ size="sm"
+ icon={<CommentIcon name="attach" color="inherit" />}
+ isDisabled={isBusy}
+ onClick={() => imageInputRef.current?.click()}
+ />
+ </>
+ )}
+ {hasEmojiPicker && (
+ <Popover
+ isOpen={isPickerOpen}
+ onOpenChange={setIsPickerOpen}
+ placement="above"
+ alignment="start"
+ label={t('@astryx.commentComposer.addEmoji')}
+ // The Popover's own autofocus lands on the picker's search
+ // field, its first control, once the Popover shows.
+ width={PICKER_WIDTH}
+ // The picker's headings run edge to edge.
+ padding={0}
+ content={
+ isPickerOpen ? (
+ <EmojiPicker
+ onSelect={emoji => {
+ onChange(
+ appendDraftInline(latestValueRef.current, emoji),
+ );
+ setIsPickerOpen(false);
+ inputRef.current?.focus();
+ }}
+ />
+ ) : null
+ }>
+ {triggerProps => (
+ <IconButton
+ ref={element => triggerProps.ref(element)}
+ label={t('@astryx.commentComposer.addEmoji')}
+ tooltip={t('@astryx.commentComposer.addEmoji')}
+ variant="ghost"
+ size="sm"
+ icon={<CommentIcon name="emoji" color="inherit" />}
+ isDisabled={isBusy}
+ aria-haspopup={triggerProps['aria-haspopup']}
+ aria-expanded={triggerProps['aria-expanded']}
+ aria-controls={triggerProps['aria-controls']}
+ onClick={event => {
+ if (!isBusy) {
+ triggerProps.onClick(event);
+ }
+ }}
+ />
+ )}
+ </Popover>
+ )}
+ {controls}
+ </HStack>
+ }
+ sendButton={
+ <ChatSendButton
+ size="sm"
+ // While a post is in flight Post stays focusable and refuses a
+ // second press (submitInput guards it); the composer reports
+ // busy. It disables only for an empty draft.
+ isDisabled={value.trim() === ''}
+ onSend={() => {
+ // Post disables once the draft clears; keep focus in the input.
+ inputRef.current?.focus();
+ submitInput(latestValueRef.current);
+ }}
+ />
+ }
+ />
+ </VStack>
+ );
+
+ const {xstyle, className, style, ...restRootProps} = rootProps ?? {};
+ return (
+ <VStack
+ ref={rootRef}
+ gap={2}
+ width="100%"
+ aria-busy={isBusy || undefined}
+ {...restRootProps}
+ {...mergeProps(
+ themeProps('comment-composer'),
+ stylex.props(xstyle),
+ className,
+ style,
+ )}
+ onClick={event => {
+ // The composer keeps its clicks: in a thread, a press on its empty
+ // space would otherwise reach the thread and collapse it.
+ event.stopPropagation();
+ const target = event.target as Element;
+ if (
+ target.closest(COMPOSER_CONTROL_SELECTOR) == null &&
+ target.closest(COMPOSER_LAYER_SELECTOR) == null
+ ) {
+ inputRef.current?.focus();
+ }
+ }}>
+ {context.kind === 'edit' && contextLabel != null && (
+ <HStack gap={1} align="center" wrap="wrap">
+ <Text type="supporting" color="secondary">
+ {contextLabel}
+ </Text>
+ {onCancel != null && (
+ <>
+ <MetadataSeparator type="supporting" />
+ <MetadataActionLink
+ label={t('@astryx.commentComposer.cancel')}
+ isDisabled={isBusy}
+ onClick={onCancel}
+ />
+ </>
+ )}
+ </HStack>
+ )}
+ {composer}
+ </VStack>
+ );
+}
+
+export interface CommentComposerProps extends Omit<
+ BaseProps<HTMLElement>,
+ 'onChange' | 'onSubmit'
+> {
+ /** Ref forwarded to the root element. */
+ ref?: Ref<HTMLElement>;
+ /** The draft, controlled. */
+ value: string;
+ onChange: (value: string) => void;
+ /** Posts the draft: Enter, or the Post button. Empty drafts never post. */
+ onSubmit: (value: string) => void;
+ /** Placeholder of the input. Defaults to the localized "Write a comment…". */
+ placeholder?: string;
+ /** Accessible name of the input. Defaults to the placeholder. */
+ label?: string;
+ /** Holds Post and the attach and emoji buttons while a post is in flight. */
+ isSubmitting?: boolean;
+ /** Shows an error Banner above the composer. */
+ error?: string;
+ /** Adds Retry to the error Banner. */
+ onRetry?: () => void;
+ /** The passage a new inline comment attaches to, quoted above the input. */
+ anchor?: CommentAnchor;
+ /** Adds Remove quoted text to the quoted passage. */
+ onAnchorDismiss?: () => void;
+ /** The palette color the host highlights passages in. @default 'yellow' */
+ highlightColor?: CommentHighlightColor;
+ /**
+ * Uploads images attached, pasted, or dropped in the input, and appends the
+ * stored images to the draft as Markdown. Adds the attach button.
+ */
+ onUploadImages?: (
+ files: readonly File[],
+ ) =>
+ readonly CommentUploadedImage[] | Promise<readonly CommentUploadedImage[]>;
+ /** Typeahead triggers, such as an `@` people search. */
+ triggers?: readonly ChatComposerTrigger[];
+ /** Agents the comment can address: typing `/` lists them. */
+ agentCommands?: readonly CommentAgentCommand[];
+ /** Whether the emoji picker button shows. @default true */
+ hasEmojiPicker?: boolean;
+ /**
+ * Product-owned controls after the attach and emoji buttons, such as a
+ * choice the host reads when the comment posts. Keep it to one short
+ * control: the footer does not wrap.
+ */
+ controls?: ReactNode;
+}
+
+/**
+ * A comment composer: a growing input with typeahead triggers and image
+ * paste, above attach and emoji buttons and Post. Controlled: the host owns
+ * the draft and clears it once the comment posts.
+ *
+ * @example
+ * ```
+ * <CommentComposer value={draft} onChange={setDraft} onSubmit={post} />
+ * ```
+ */
+export function CommentComposer({
+ value,
+ onChange,
+ onSubmit,
+ placeholder,
+ label,
+ isSubmitting = false,
+ error,
+ onRetry,
+ anchor,
+ onAnchorDismiss,
+ highlightColor = 'yellow',
+ onUploadImages,
+ triggers = NO_TRIGGERS,
+ agentCommands = NO_AGENT_COMMANDS,
+ hasEmojiPicker = true,
+ controls,
+ ref,
+ ...rootProps
+}: CommentComposerProps) {
+ const t = useTranslator();
+ return (
+ <CommentComposerBase
+ value={value}
+ onChange={onChange}
+ onSubmit={onSubmit}
+ placeholder={placeholder ?? t('@astryx.commentComposer.placeholder')}
+ label={label}
+ isSubmitting={isSubmitting}
+ error={error}
+ onRetryError={onRetry}
+ context={anchor != null ? {kind: 'comment', anchor} : {kind: 'comment'}}
+ anchor={anchor}
+ onAnchorDismiss={onAnchorDismiss}
+ highlightColor={highlightColor}
+ onUploadImages={onUploadImages}
+ triggers={triggers}
+ agentCommands={agentCommands}
+ hasEmojiPicker={hasEmojiPicker}
+ controls={controls}
+ rootRef={ref}
+ rootProps={rootProps}
+ />
+ );
+}
+
+CommentComposer.displayName = 'CommentComposer';
diff --git a/packages/lab/src/Comments/CommentMarkdown.tsx b/packages/lab/src/Comments/CommentMarkdown.tsx
new file mode 100644
index 0000000000..eab17bae04
--- /dev/null
+++ b/packages/lab/src/Comments/CommentMarkdown.tsx
@@ -0,0 +1,184 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CommentMarkdown.tsx
+ * @input Uses React, StyleX, Markdown, Lightbox, ChatTokenizedText, Avatar
+ * @output Exports CommentMarkdown (a comment body's Markdown, with images that
+ * open in a Lightbox and agent commands shown as chips) and agentToken
+ * @position Internal body renderer shared by comment rows and the edit
+ * history dialog
+ */
+
+import {createContext, useContext, useMemo, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Avatar} from '@astryxdesign/core/Avatar';
+import {
+ ChatTokenizedText,
+ type ChatComposerToken,
+} from '@astryxdesign/core/Chat';
+import {Lightbox, type LightboxMedia} from '@astryxdesign/core/Lightbox';
+import {Markdown, type MarkdownInlinePlugin} from '@astryxdesign/core/Markdown';
+import type {MarkdownPluginEntry} from '@astryxdesign/core/Markdown/plugins';
+import {focusVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import type {CommentAgentCommand} from './types';
+
+const styles = stylex.create({
+ image: {
+ display: 'block',
+ maxWidth: '100%',
+ height: 'auto',
+ marginBlock: spacingVars['--spacing-2'],
+ cursor: {
+ default: 'zoom-in',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ outlineStyle: {
+ default: 'none',
+ ':focus-visible': focusVars['--focus-outline-style'],
+ },
+ outlineWidth: focusVars['--focus-outline-width'],
+ outlineColor: focusVars['--focus-outline-color'],
+ outlineOffset: focusVars['--focus-outline-offset'],
+ },
+});
+
+/** An agent's chip: what the composer's `/` menu inserts, and what a posted
+ * comment shows in place of the command. */
+export function agentToken(agent: CommentAgentCommand): ChatComposerToken {
+ return {
+ value: `/${agent.command}`,
+ label: agent.name,
+ variant: 'info',
+ icon: (
+ <Avatar
+ name={agent.name}
+ src={agent.logoUrl}
+ size="xsm"
+ shape="rounded"
+ tooltip={false}
+ />
+ ),
+ };
+}
+
+function escapeRegExp(text: string): string {
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/** Shows `/<command>` in a posted comment as the agent's chip. */
+function agentCommandPlugin(
+ agents: readonly CommentAgentCommand[],
+): MarkdownInlinePlugin {
+ const byCommand = new Map(agents.map(agent => [agent.command, agent]));
+ return {
+ pattern: new RegExp(
+ `(^|\\s)/(${agents.map(agent => escapeRegExp(agent.command)).join('|')})(?=\\s|$)`,
+ 'g',
+ ),
+ render: (match, key) => {
+ const agent = byCommand.get(match[2] ?? '');
+ if (agent == null) {
+ return match[0];
+ }
+ const token = agentToken(agent);
+ // Set in the line as the composer sets it: centered on the text.
+ return (
+ <span key={key}>
+ {match[1]}
+ <ChatTokenizedText
+ tokens={[token]}
+ data-agent-command={agent.command}>
+ {token.value}
+ </ChatTokenizedText>
+ </span>
+ );
+ },
+ };
+}
+
+/* One Lightbox per body, opened at whichever of its images is pressed. */
+const CommentImageContext = createContext<
+ ((media: LightboxMedia) => void) | null
+>(null);
+
+function CommentImage({src, alt}: {src: string; alt: string}) {
+ const openImage = useContext(CommentImageContext);
+ const open = () => openImage?.({src, alt});
+ return (
+ <img
+ src={src}
+ alt={alt}
+ role="button"
+ tabIndex={0}
+ aria-haspopup="dialog"
+ data-comment-image="lightbox"
+ {...stylex.props(styles.image)}
+ onClick={event => {
+ // An image is its own control, not a press on the thread.
+ event.stopPropagation();
+ open();
+ }}
+ onKeyDown={event => {
+ if (event.key !== 'Enter' && event.key !== ' ') {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ open();
+ }}
+ />
+ );
+}
+
+const COMMENT_MARKDOWN_COMPONENTS = {image: CommentImage};
+
+const NO_INLINE_PLUGINS: readonly MarkdownInlinePlugin[] = [];
+const NO_PLUGINS: readonly MarkdownPluginEntry[] = [];
+
+/** A comment body: compact Markdown whose images open in a Lightbox. */
+export function CommentMarkdown({
+ body,
+ agentCommands,
+ plugins = NO_PLUGINS,
+ inlinePlugins = NO_INLINE_PLUGINS,
+}: {
+ body: string;
+ agentCommands: readonly CommentAgentCommand[];
+ plugins?: readonly MarkdownPluginEntry[];
+ inlinePlugins?: readonly MarkdownInlinePlugin[];
+}) {
+ const allInlinePlugins = useMemo(
+ () =>
+ agentCommands.length === 0
+ ? [...inlinePlugins]
+ : [...inlinePlugins, agentCommandPlugin(agentCommands)],
+ [agentCommands, inlinePlugins],
+ );
+ const [openedImage, setOpenedImage] = useState<LightboxMedia | null>(null);
+ return (
+ <CommentImageContext.Provider value={setOpenedImage}>
+ <Markdown
+ density="compact"
+ plugins={plugins}
+ inlinePlugins={allInlinePlugins}
+ autolink="gfm"
+ components={COMMENT_MARKDOWN_COMPONENTS}>
+ {body}
+ </Markdown>
+ {openedImage != null && (
+ <Lightbox
+ isOpen
+ media={openedImage}
+ hasZoom
+ onOpenChange={isOpen => {
+ if (!isOpen) {
+ setOpenedImage(null);
+ }
+ }}
+ />
+ )}
+ </CommentImageContext.Provider>
+ );
+}
diff --git a/packages/lab/src/Comments/CommentParts.tsx b/packages/lab/src/Comments/CommentParts.tsx
new file mode 100644
index 0000000000..0dd0c5ffc4
--- /dev/null
+++ b/packages/lab/src/Comments/CommentParts.tsx
@@ -0,0 +1,164 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CommentParts.tsx
+ * @input Uses React, StyleX, theme colors, Banner, Blockquote, Button, Link, Text
+ * @output Exports the small presentational parts owned by CommentComposer
+ * @position Internal building blocks for the Lab CommentComposer; later
+ * Comments-family components extend this module
+ */
+
+import type {Ref} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Banner} from '@astryxdesign/core/Banner';
+import {Blockquote} from '@astryxdesign/core/Blockquote';
+import {Button} from '@astryxdesign/core/Button';
+import {Link} from '@astryxdesign/core/Link';
+import {Text} from '@astryxdesign/core/Text';
+import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';
+import type {CommentHighlightColor} from './types';
+
+export const partStyles = stylex.create({
+ noWrap: {whiteSpace: 'nowrap'},
+ quoteText: {fontStyle: 'italic'},
+ fullWidth: {width: '100%'},
+});
+
+const highlightRules = stylex.create({
+ blue: {borderInlineStartColor: colorVars['--color-border-blue']},
+ cyan: {borderInlineStartColor: colorVars['--color-border-cyan']},
+ gray: {borderInlineStartColor: colorVars['--color-border-gray']},
+ green: {borderInlineStartColor: colorVars['--color-border-green']},
+ orange: {borderInlineStartColor: colorVars['--color-border-orange']},
+ pink: {borderInlineStartColor: colorVars['--color-border-pink']},
+ purple: {borderInlineStartColor: colorVars['--color-border-purple']},
+ red: {borderInlineStartColor: colorVars['--color-border-red']},
+ teal: {borderInlineStartColor: colorVars['--color-border-teal']},
+ yellow: {borderInlineStartColor: colorVars['--color-border-yellow']},
+});
+
+/** A failed action as an error Banner with its one recovery action. */
+export type ErrorBannerContent = {
+ title: string;
+ description?: string;
+ actionLabel?: string;
+ onAction?: () => void;
+ isActionDisabled?: boolean;
+};
+
+/** An inline failure announced when its error Banner mounts. */
+export function ErrorBanner({
+ actionRef,
+ content,
+ onBeforeAction,
+ ...dataProps
+}: {
+ actionRef?: Ref<HTMLButtonElement>;
+ content: ErrorBannerContent;
+ onBeforeAction?: () => void;
+ [dataAttribute: `data-${string}`]: string | undefined;
+}) {
+ const {actionLabel, description, isActionDisabled, onAction, title} = content;
+ return (
+ <Banner
+ status="error"
+ role="alert"
+ container="card"
+ title={title}
+ description={description}
+ xstyle={partStyles.fullWidth}
+ endContent={
+ actionLabel != null && onAction != null ? (
+ <Button
+ ref={actionRef}
+ label={actionLabel}
+ variant="ghost"
+ size="sm"
+ isDisabled={isActionDisabled}
+ onClick={() => {
+ onBeforeAction?.();
+ onAction();
+ }}
+ />
+ ) : undefined
+ }
+ {...dataProps}
+ />
+ );
+}
+
+export function MetadataSeparator({
+ type = 'body',
+}: {
+ type?: 'body' | 'supporting';
+}) {
+ return (
+ <Text as="span" type={type} color="secondary" aria-hidden="true">
+ ·
+ </Text>
+ );
+}
+
+/** A secondary text link that performs a compact composer action. */
+export function MetadataActionLink({
+ accessibleLabel,
+ actionRole,
+ isDisabled,
+ label,
+ onClick,
+ textType = 'supporting',
+}: {
+ accessibleLabel?: string;
+ actionRole?: 'history';
+ isDisabled?: boolean;
+ label: string;
+ onClick: () => void;
+ textType?: 'body' | 'supporting';
+}) {
+ return (
+ <Link
+ label={accessibleLabel ?? label}
+ type={textType}
+ color="secondary"
+ xstyle={partStyles.noWrap}
+ data-metadata-action={actionRole}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={isDisabled ? -1 : undefined}
+ onClick={event => {
+ event.preventDefault();
+ if (isDisabled !== true) {
+ onClick();
+ }
+ }}>
+ {label}
+ </Link>
+ );
+}
+
+/** A quoted passage in Markdown's blockquote style, clamped to two lines. */
+export function QuotedPassage({
+ quote,
+ highlightColor,
+}: {
+ quote: string;
+ highlightColor?: CommentHighlightColor;
+}) {
+ return (
+ <Blockquote
+ xstyle={
+ highlightColor != null ? highlightRules[highlightColor] : undefined
+ }
+ data-quote-rule={highlightColor != null ? 'highlight' : 'neutral'}
+ data-highlight-color={highlightColor}>
+ <Text
+ type="body"
+ color="inherit"
+ maxLines={2}
+ xstyle={partStyles.quoteText}>
+ {quote}
+ </Text>
+ </Blockquote>
+ );
+}
diff --git a/packages/lab/src/Comments/icons.tsx b/packages/lab/src/Comments/icons.tsx
new file mode 100644
index 0000000000..668233de9c
--- /dev/null
+++ b/packages/lab/src/Comments/icons.tsx
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file icons.tsx
+ * @input Uses React, Icon, getExtendedIcon, and useThemeName
+ * @output Exports CommentComposer's owned icon keys and renderer
+ * @position Internal glyphs for the Lab CommentComposer
+ */
+
+import type {SVGProps} from 'react';
+import {getExtendedIcon, Icon, type IconColor} from '@astryxdesign/core/Icon';
+import {useThemeName} from '@astryxdesign/core/theme';
+
+/** Theme registry keys owned by CommentComposer. */
+export const COMMENT_ICON_KEYS = {
+ attach: 'comment:attach',
+ emoji: 'comment:emoji',
+} as const;
+
+type CommentIconName = keyof typeof COMMENT_ICON_KEYS;
+type Glyph = (props: SVGProps<SVGSVGElement>) => React.JSX.Element;
+
+function glyph(paths: readonly string[]): Glyph {
+ function CommentComposerGlyph(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ {...props}>
+ {paths.map(d => (
+ <path key={d} d={d} />
+ ))}
+ </svg>
+ );
+ }
+ return CommentComposerGlyph;
+}
+
+const FALLBACK_GLYPHS: Record<CommentIconName, Glyph> = {
+ attach: glyph([
+ 'M19.5 11.5l-7.6 7.6a4.5 4.5 0 0 1-6.36-6.36l7.95-7.95a3 3 0 0 1 4.24 4.24l-7.6 7.6a1.5 1.5 0 0 1-2.12-2.12l7.07-7.07',
+ ]),
+ emoji: glyph([
+ 'M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z',
+ 'M8.5 14.5a4 4 0 0 0 7 0',
+ 'M9 10h.01M15 10h.01',
+ ]),
+};
+
+/** A composer glyph resolved through the active theme, with a bundled fallback. */
+export function CommentIcon({
+ name,
+ color = 'secondary',
+ size = 'sm',
+}: {
+ name: CommentIconName;
+ color?: IconColor;
+ size?: 'xsm' | 'sm' | 'md' | 'lg';
+}) {
+ const themeName = useThemeName();
+ const key = COMMENT_ICON_KEYS[name];
+ const hasOverride = getExtendedIcon(key, undefined, themeName) != null;
+ return (
+ <Icon
+ icon={hasOverride ? key : FALLBACK_GLYPHS[name]}
+ color={color}
+ size={size}
+ />
+ );
+}
diff --git a/packages/lab/src/Comments/index.ts b/packages/lab/src/Comments/index.ts
new file mode 100644
index 0000000000..9ea20374b4
--- /dev/null
+++ b/packages/lab/src/Comments/index.ts
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input CommentComposer implementation and its public data types
+ * @output Exports the Lab CommentComposer surface
+ * @position CommentComposer entry point; re-exported by packages/lab/src/index.ts
+ */
+
+export {CommentComposer} from './CommentComposer';
+export type {CommentComposerProps} from './CommentComposer';
+export type {
+ CommentAgentCommand,
+ CommentAnchor,
+ CommentComposerContext,
+ CommentComposerRenderProps,
+ CommentHighlightColor,
+ CommentImageUploader,
+ CommentUploadedImage,
+} from './types';
diff --git a/packages/lab/src/Comments/types.ts b/packages/lab/src/Comments/types.ts
new file mode 100644
index 0000000000..239e6558c9
--- /dev/null
+++ b/packages/lab/src/Comments/types.ts
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file types.ts
+ * @input No runtime dependencies
+ * @output Exports the data and callback types owned by CommentComposer
+ * @position Type contract for the Lab CommentComposer; later Comments-family
+ * components extend this shared vocabulary
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/Comments/index.ts (exports)
+ * - /packages/lab/src/Comments/CommentComposer.doc.mjs
+ */
+
+/**
+ * The passage an inline comment discusses. The host owns anchoring (the text
+ * selection, offsets, and re-resolving them after edits); the composer quotes
+ * the passage without owning its coordinates.
+ */
+export interface CommentAnchor {
+ /** The selected text, quoted above the composer. */
+ quote: string;
+ /**
+ * `orphaned` when edits removed the passage.
+ * @default 'anchored'
+ */
+ status?: 'anchored' | 'orphaned';
+}
+
+/** A palette color the host uses to connect a quoted passage to its highlight. */
+export type CommentHighlightColor =
+ | 'blue'
+ | 'cyan'
+ | 'gray'
+ | 'green'
+ | 'orange'
+ | 'pink'
+ | 'purple'
+ | 'red'
+ | 'teal'
+ | 'yellow';
+
+/** An image the host's upload flow stored. */
+export interface CommentUploadedImage {
+ /** URL of the stored image. */
+ url: string;
+ /** Description used as the image's alt text. */
+ alt: string;
+}
+
+/** Which comment workflow a composer callback belongs to. */
+export type CommentComposerContext =
+ | {
+ kind: 'comment';
+ /** The passage a new inline comment will attach to, when there is one. */
+ anchor?: CommentAnchor;
+ }
+ | {kind: 'edit'; commentId: string}
+ | {kind: 'reply'; parentCommentId: string; repliedToCommentId: string};
+
+/** What a `renderComposer` replacement receives. */
+export interface CommentComposerRenderProps {
+ value: string;
+ onChange: (value: string) => void;
+ onSubmit: (value: string) => void;
+ placeholder: string;
+ isSubmitting: boolean;
+ error?: string;
+ contextLabel?: string;
+ context: CommentComposerContext;
+ onCancel?: () => void;
+}
+
+/** An agent a comment can address with a slash command. */
+export interface CommentAgentCommand {
+ /** The command after the slash: `ask` for `/ask`. */
+ command: string;
+ /** The agent's display name. */
+ name: string;
+ /** What asking it does, shown in the slash-command menu. */
+ description: string;
+ /** Optional square logo; initials render without one. */
+ logoUrl?: string;
+}
+
+/** Uploads images and returns their stored URLs and alt text. */
+export type CommentImageUploader = (
+ files: readonly File[],
+ context: CommentComposerContext,
+) => readonly CommentUploadedImage[] | Promise<readonly CommentUploadedImage[]>;
diff --git a/packages/lab/src/Comments/utils.ts b/packages/lab/src/Comments/utils.ts
new file mode 100644
index 0000000000..9eeea4dd47
--- /dev/null
+++ b/packages/lab/src/Comments/utils.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file utils.ts
+ * @input Uploaded-image records and controlled draft strings
+ * @output Exports CommentComposer's Markdown serialization and draft helpers
+ * @position Internal pure helpers for the Lab CommentComposer
+ */
+
+import type {CommentUploadedImage} from './types';
+
+/** Alt text that cannot break out of Markdown's image brackets. */
+export function safeImageAlt(alt: string, fallback: string): string {
+ return alt.replace(/[[\]\r\n]+/g, ' ').trim() || fallback;
+}
+
+/** A URL that cannot break out of Markdown's image parentheses. */
+export function safeMarkdownImageUrl(url: string): string {
+ return url
+ .trim()
+ .replace(/[\s()]/g, character =>
+ character === '('
+ ? '%28'
+ : character === ')'
+ ? '%29'
+ : encodeURIComponent(character),
+ );
+}
+
+/** Uploaded images as Markdown, one paragraph each. */
+export function imagesToMarkdown(
+ images: readonly CommentUploadedImage[],
+ fallbackAlt: string,
+): string {
+ return images
+ .map(
+ image =>
+ `![${safeImageAlt(image.alt, fallbackAlt)}](${safeMarkdownImageUrl(image.url)})`,
+ )
+ .join('\n\n');
+}
+
+/** Appends a block (an image, say) to a draft as its own paragraph. */
+export function appendDraftBlock(value: string, block: string): string {
+ const draft = value.trimEnd();
+ return draft === '' ? block : `${draft}\n\n${block}`;
+}
+
+/** Appends inline content (an emoji, say) to a draft, spaced from its text. */
+export function appendDraftInline(value: string, content: string): string {
+ if (value === '' || /\s$/.test(value) || /^\s/.test(content)) {
+ return `${value}${content}`;
+ }
+ return `${value} ${content}`;
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index d5610c41f1..3d543e1750 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -40,6 +40,19 @@ export {
type CommentPinProps,
} from './CommentPin';
+// CommentComposer — controlled composer for new comments, replies, and edits
+export {
+ CommentComposer,
+ type CommentComposerProps,
+ type CommentAgentCommand,
+ type CommentAnchor,
+ type CommentComposerContext,
+ type CommentComposerRenderProps,
+ type CommentHighlightColor,
+ type CommentImageUploader,
+ type CommentUploadedImage,
+} from './Comments';
+
// TransferList — controlled dual-panel collection input
export {
TransferList,