Skip to content

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

TypeScript

feat(lab): add CommentPin (#7614)

Ernest428444239fc5
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index adc233b755..2a55857bb3 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -349,5 +349,9 @@
{
"component": "lab/EmojiPicker",
"reason": "EmojiPicker is a search field above CSS grids of emoji whose columns follow CSS direction, with sticky group headings and a footer preview in logical-property flex rows; its search glyph is radially symmetric. Its one direction-sensitive behavior, horizontal arrow keys, comes from core useGridFocus, which resolves direction per keydown with isRtlElement; that hook's RTL tests and EmojiPicker's own right-to-left keyboard test cover it, and no audit dimension measures keyboard direction."
+ },
+ {
+ "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."
}
]
diff --git a/apps/storybook/stories/CommentPin.stories.tsx b/apps/storybook/stories/CommentPin.stories.tsx
new file mode 100644
index 0000000000..4605b63947
--- /dev/null
+++ b/apps/storybook/stories/CommentPin.stories.tsx
@@ -0,0 +1,298 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {useEffect, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {CommentPin} from '@astryxdesign/lab';
+import {Text} from '@astryxdesign/core/Text';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+const PEOPLE = {
+ ada: {
+ id: 'ada',
+ name: 'Ada Lovelace',
+ avatarSrc: 'https://i.pravatar.cc/80?img=47',
+ },
+ lin: {
+ id: 'lin',
+ name: 'Lin Chen',
+ avatarSrc: 'https://i.pravatar.cc/80?img=32',
+ },
+ mira: {
+ id: 'mira',
+ name: 'Mira Patel',
+ avatarSrc: 'https://i.pravatar.cc/80?img=5',
+ },
+ noah: {
+ id: 'noah',
+ name: 'Noah Williams',
+ avatarSrc: 'https://i.pravatar.cc/80?img=12',
+ },
+ sam: {
+ id: 'sam',
+ name: 'Sam Rivera',
+ avatarSrc: 'https://i.pravatar.cc/80?img=15',
+ },
+};
+
+const styles = stylex.create({
+ story: {
+ padding: spacingVars['--spacing-8'],
+ },
+ row: {
+ alignItems: 'center',
+ minHeight: 44,
+ },
+ stateLabel: {
+ minWidth: 140,
+ },
+ canvas: {
+ position: 'relative',
+ width: 520,
+ height: 300,
+ overflow: 'hidden',
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-background-surface'],
+ boxShadow: shadowVars['--shadow-med'],
+ },
+ photo: {
+ display: 'block',
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover',
+ },
+ overMarker: {
+ position: 'absolute',
+ insetInlineStart: '38%',
+ insetBlockStart: '34%',
+ transform: 'translateY(-100%)',
+ },
+ margin: {
+ position: 'absolute',
+ insetBlock: 0,
+ insetInlineEnd: 0,
+ width: 72,
+ backgroundColor: colorVars['--color-background-muted'],
+ borderInlineStartWidth: 1,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border'],
+ },
+ marginMarker: {
+ position: 'absolute',
+ insetInlineStart: '50%',
+ insetBlockStart: '66%',
+ transform: 'translateY(-100%)',
+ },
+});
+
+function FocusedSelectedPin() {
+ const ref = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ ref.current?.focus();
+ }, []);
+ return (
+ <CommentPin
+ ref={ref}
+ label="Focused current annotation from Ada"
+ participants={[PEOPLE.ada]}
+ isSelected
+ />
+ );
+}
+
+const meta: Meta<typeof CommentPin> = {
+ title: 'Lab/CommentPin',
+ component: CommentPin,
+ tags: ['autodocs'],
+ parameters: {layout: 'centered'},
+ args: {
+ label: 'Open annotation from Ada',
+ participants: [PEOPLE.ada],
+ onClick: () => {},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof CommentPin>;
+
+export const Default: Story = {};
+
+export const Grouped: Story = {
+ args: {
+ label: 'Open 4 grouped annotations from Ada and Lin',
+ participants: [PEOPLE.ada, PEOPLE.lin],
+ threadCount: 4,
+ },
+};
+
+export const StateMatrix: Story = {
+ render: () => (
+ <VStack gap={3} xstyle={styles.story}>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Single
+ </Text>
+ <CommentPin
+ label="Open annotation from Ada"
+ participants={[PEOPLE.ada]}
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Selected
+ </Text>
+ <CommentPin
+ label="Current annotation from Ada"
+ participants={[PEOPLE.ada]}
+ isSelected
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Selected + focus
+ </Text>
+ <FocusedSelectedPin />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Other pin dimmed
+ </Text>
+ <CommentPin
+ label="Open another annotation from Mira"
+ participants={[PEOPLE.mira]}
+ isDimmed
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Grouped
+ </Text>
+ <CommentPin
+ label="Open 4 grouped annotations from Ada and Lin"
+ participants={[PEOPLE.ada, PEOPLE.lin]}
+ threadCount={4}
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Selected group
+ </Text>
+ <CommentPin
+ label="Current group of 12 annotations from Ada, Lin, and Mira"
+ participants={[PEOPLE.ada, PEOPLE.lin, PEOPLE.mira]}
+ threadCount={12}
+ isSelected
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Group overflow
+ </Text>
+ <CommentPin
+ label="Open 8 grouped annotations from Ada, Lin, and 3 others"
+ participants={[
+ PEOPLE.ada,
+ PEOPLE.lin,
+ PEOPLE.mira,
+ PEOPLE.noah,
+ PEOPLE.sam,
+ ]}
+ threadCount={8}
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Unread single
+ </Text>
+ <CommentPin
+ label="Open unread annotation from Mira"
+ participants={[PEOPLE.mira]}
+ unreadCount={1}
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Unread group
+ </Text>
+ <CommentPin
+ label="Open 8 grouped annotations from Ada, Lin, and 3 others, 3 unread"
+ participants={[
+ PEOPLE.ada,
+ PEOPLE.lin,
+ PEOPLE.mira,
+ PEOPLE.noah,
+ PEOPLE.sam,
+ ]}
+ threadCount={8}
+ unreadCount={3}
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Resolved
+ </Text>
+ <CommentPin
+ label="Open resolved annotation from Mira"
+ participants={[PEOPLE.mira]}
+ isResolved
+ />
+ </HStack>
+ <HStack gap={4} xstyle={styles.row}>
+ <Text type="supporting" xstyle={styles.stateLabel}>
+ Disabled / pending
+ </Text>
+ <CommentPin
+ label="Pending annotation from Ada"
+ participants={[PEOPLE.ada]}
+ isSelected
+ isDisabled
+ />
+ </HStack>
+ </VStack>
+ ),
+};
+
+export const OverContentAndInMargin: Story = {
+ render: function PlacementStory() {
+ const [selected, setSelected] = useState<'content' | 'margin' | null>(
+ 'content',
+ );
+ // aria-pressed toggle semantics: activating the selected pin clears it.
+ const toggle = (id: 'content' | 'margin') =>
+ setSelected(current => (current === id ? null : id));
+ return (
+ <div {...stylex.props(styles.canvas)}>
+ <img
+ src="https://images.unsplash.com/photo-1558655146-d09347e92766?w=1040&h=600&fit=crop&auto=format"
+ alt="Design materials arranged on a desk"
+ {...stylex.props(styles.photo)}
+ />
+ <CommentPin
+ label="Open 4 grouped annotations over the image"
+ participants={[PEOPLE.ada, PEOPLE.lin]}
+ threadCount={4}
+ isSelected={selected === 'content'}
+ isDimmed={selected != null && selected !== 'content'}
+ onClick={() => toggle('content')}
+ xstyle={styles.overMarker}
+ />
+ <div {...stylex.props(styles.margin)}>
+ <CommentPin
+ label="Open margin annotation from Mira"
+ participants={[PEOPLE.mira]}
+ isSelected={selected === 'margin'}
+ isDimmed={selected != null && selected !== 'margin'}
+ onClick={() => toggle('margin')}
+ xstyle={styles.marginMarker}
+ />
+ </div>
+ </div>
+ );
+ },
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 5c3581a115..aeb873cf68 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-pin",
+ "path": "components/lab/comment-pin",
+ "aliases": []
+ },
{
"name": "component-lab-diff-viewer",
"path": "components/lab/diff-viewer",
@@ -1885,6 +1890,11 @@
"path": "examples/command-palette/rich-items",
"aliases": []
},
+ {
+ "name": "example-comment-pin-host-owned-placement",
+ "path": "examples/comment-pin/host-owned-placement",
+ "aliases": []
+ },
{
"name": "example-complex-selector-deadline-picker",
"path": "examples/complex-selector/deadline-picker",
@@ -4240,6 +4250,11 @@
"path": "showcases/command-palette/default",
"aliases": []
},
+ {
+ "name": "showcase-comment-pin-avatar-first-annotations",
+ "path": "showcases/comment-pin/avatar-first-annotations",
+ "aliases": []
+ },
{
"name": "showcase-complex-selector-default",
"path": "showcases/complex-selector/default",
diff --git a/packages/lab/blocks/CommentPinInMargin.doc.mjs b/packages/lab/blocks/CommentPinInMargin.doc.mjs
new file mode 100644
index 0000000000..24021b68f3
--- /dev/null
+++ b/packages/lab/blocks/CommentPinInMargin.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Host-owned placement',
+ displayName: 'Comment pin in a document margin',
+ description:
+ 'A caller-positioned CommentPin in a document margin. The host maps its anchor to the pin’s logical bottom-start corner and owns the surrounding layout; the pin owns its compact interactive surface. Activating the pin toggles its selected state.',
+ exampleFor: 'CommentPin',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Card', 'CommentPin', 'Text', 'VStack'],
+};
diff --git a/packages/lab/blocks/CommentPinInMargin.tsx b/packages/lab/blocks/CommentPinInMargin.tsx
new file mode 100644
index 0000000000..8b30bcd9e3
--- /dev/null
+++ b/packages/lab/blocks/CommentPinInMargin.tsx
@@ -0,0 +1,77 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input A host-positioned CommentPin, its lead commenter, and local
+ * selected state
+ * @output A document passage with one comment pin in its margin; activating
+ * the pin toggles its selection and aria-pressed state
+ * @position Copyable Lab CommentPin placement example
+ */
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Card} from '@astryxdesign/core/Card';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Stack';
+import {colorVars, spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {CommentPin} from '@astryxdesign/lab';
+
+const styles = stylex.create({
+ document: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) 64px',
+ minHeight: 220,
+ },
+ content: {
+ padding: spacingVars['--spacing-5'],
+ },
+ margin: {
+ position: 'relative',
+ borderInlineStartWidth: 1,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border'],
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ // Inset far enough from the clipped Card edges that the selected ring and
+ // the farther-out keyboard focus outline stay fully visible.
+ pin: {
+ position: 'absolute',
+ insetInlineStart: spacingVars['--spacing-3'],
+ insetBlockStart: spacingVars['--spacing-10'],
+ transform: 'translateY(-100%)',
+ },
+});
+
+export default function CommentPinInMargin() {
+ const [isSelected, setIsSelected] = useState(false);
+ return (
+ <Card padding={0} width={520}>
+ <div {...stylex.props(styles.document)}>
+ <VStack gap={3} xstyle={styles.content}>
+ <Text as="h2" type="display-3" weight="bold">
+ Review notes
+ </Text>
+ <Text type="body">
+ The host owns the document anchor and margin layout. The pin stays a
+ compact action that identifies the lead commenter.
+ </Text>
+ <Text type="supporting" color="secondary">
+ Selecting the pin can open a thread beside this passage or in a
+ shared comments panel.
+ </Text>
+ </VStack>
+ <div aria-label="Comment margin" {...stylex.props(styles.margin)}>
+ <CommentPin
+ label="Open comment from Maya"
+ participants={[{id: 'maya', name: 'Maya Chen'}]}
+ isSelected={isSelected}
+ onClick={() => setIsSelected(current => !current)}
+ xstyle={styles.pin}
+ />
+ </div>
+ </div>
+ </Card>
+ );
+}
diff --git a/packages/lab/blocks/CommentPinShowcase.doc.mjs b/packages/lab/blocks/CommentPinShowcase.doc.mjs
new file mode 100644
index 0000000000..30b3a442bb
--- /dev/null
+++ b/packages/lab/blocks/CommentPinShowcase.doc.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: 'Avatar-first annotations',
+ displayName: 'Avatar-first annotations',
+ description:
+ 'Caller-positioned comment pins over media and in a content margin. Every coordinate maps to the pin’s logical bottom-start corner. The selected group caps its participants at three circles (two Avatars plus +3) and shows its unread count in an accent badge instead of the total; the unread margin pin shows the badge too. Other pins dim without becoming disabled, activating the selected pin again clears the selection, and no pin dims while nothing is selected.',
+ exampleFor: 'CommentPin',
+ isReady: true,
+ isShowcase: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['CommentPin', 'Text', 'VStack'],
+};
diff --git a/packages/lab/blocks/CommentPinShowcase.tsx b/packages/lab/blocks/CommentPinShowcase.tsx
new file mode 100644
index 0000000000..26cf7916fe
--- /dev/null
+++ b/packages/lab/blocks/CommentPinShowcase.tsx
@@ -0,0 +1,188 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @input Three caller-positioned comment pins, logical bottom-start anchors,
+ * participant/thread/unread counts, and controlled selected/dimmed state
+ * that may be empty
+ * @output A grouped pin with a three-circle participant cap and an unread
+ * badge, a resolved pin, and an unread margin pin; activating the selected
+ * pin clears the selection, and non-selected pins dim only while another pin
+ * is selected
+ * @position CommentPin docsite showcase and copyable Lab block
+ */
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {CommentPin} from '@astryxdesign/lab';
+import {Text} from '@astryxdesign/core/Text';
+import {VStack} from '@astryxdesign/core/Stack';
+import {
+ colorVars,
+ radiusVars,
+ shadowVars,
+ spacingVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+
+const PEOPLE = {
+ ada: {
+ id: 'ada',
+ name: 'Ada Lovelace',
+ avatarSrc: 'https://i.pravatar.cc/80?img=47',
+ },
+ lin: {
+ id: 'lin',
+ name: 'Lin Chen',
+ avatarSrc: 'https://i.pravatar.cc/80?img=32',
+ },
+ mira: {
+ id: 'mira',
+ name: 'Mira Patel',
+ avatarSrc: 'https://i.pravatar.cc/80?img=5',
+ },
+ noah: {
+ id: 'noah',
+ name: 'Noah Williams',
+ avatarSrc: 'https://i.pravatar.cc/80?img=12',
+ },
+ sam: {
+ id: 'sam',
+ name: 'Sam Rivera',
+ avatarSrc: 'https://i.pravatar.cc/80?img=15',
+ },
+};
+
+const styles = stylex.create({
+ root: {
+ width: '100%',
+ maxWidth: 720,
+ },
+ canvas: {
+ display: 'grid',
+ gridTemplateColumns: 'minmax(0, 1fr) 72px',
+ minHeight: 360,
+ overflow: 'hidden',
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: colorVars['--color-border'],
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-background-surface'],
+ boxShadow: shadowVars['--shadow-med'],
+ },
+ media: {
+ position: 'relative',
+ minWidth: 0,
+ minHeight: 360,
+ },
+ image: {
+ display: 'block',
+ width: '100%',
+ height: 360,
+ objectFit: 'cover',
+ },
+ groupedMarker: {
+ position: 'absolute',
+ insetInlineStart: '38%',
+ insetBlockStart: '30%',
+ transform: 'translateY(-100%)',
+ },
+ resolvedMarker: {
+ position: 'absolute',
+ insetInlineStart: '66%',
+ insetBlockStart: '69%',
+ transform: 'translateY(-100%)',
+ },
+ margin: {
+ position: 'relative',
+ minHeight: 360,
+ borderInlineStartWidth: 1,
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border'],
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ marginRule: {
+ position: 'absolute',
+ insetInlineStart: '50%',
+ insetBlock: spacingVars['--spacing-5'],
+ width: 1,
+ backgroundColor: colorVars['--color-border'],
+ },
+ marginMarker: {
+ position: 'absolute',
+ insetInlineStart: '50%',
+ insetBlockStart: '48%',
+ transform: 'translateY(-100%)',
+ },
+});
+
+type PinId = 'grouped' | 'margin' | 'resolved';
+
+export default function CommentPinShowcase() {
+ const [selected, setSelected] = useState<PinId | null>('grouped');
+ // aria-pressed toggle semantics: activating the selected pin clears it.
+ const toggle = (id: PinId) =>
+ setSelected(current => (current === id ? null : id));
+
+ return (
+ <VStack gap={4} xstyle={styles.root}>
+ <VStack gap={1}>
+ <Text as="h3" type="display-3" weight="bold">
+ Annotations keep identity at the anchor
+ </Text>
+ <Text type="supporting" color="secondary">
+ The host positions and groups markers; each marker owns only its
+ compact interactive surface.
+ </Text>
+ </VStack>
+
+ <div {...stylex.props(styles.canvas)}>
+ <div {...stylex.props(styles.media)}>
+ <img
+ src="https://images.unsplash.com/photo-1558655146-d09347e92766?w=1296&h=720&fit=crop&auto=format"
+ alt="Design materials arranged on a desk"
+ {...stylex.props(styles.image)}
+ />
+ <CommentPin
+ label="Open 6 grouped annotations from Ada, Lin, and 3 others, 2 unread"
+ participants={[
+ PEOPLE.ada,
+ PEOPLE.lin,
+ PEOPLE.mira,
+ PEOPLE.noah,
+ PEOPLE.sam,
+ ]}
+ threadCount={6}
+ unreadCount={2}
+ isSelected={selected === 'grouped'}
+ isDimmed={selected != null && selected !== 'grouped'}
+ onClick={() => toggle('grouped')}
+ xstyle={styles.groupedMarker}
+ />
+ <CommentPin
+ label="Open resolved annotation from Mira"
+ participants={[PEOPLE.mira]}
+ isResolved
+ isSelected={selected === 'resolved'}
+ isDimmed={selected != null && selected !== 'resolved'}
+ onClick={() => toggle('resolved')}
+ xstyle={styles.resolvedMarker}
+ />
+ </div>
+
+ <div aria-label="Annotation margin" {...stylex.props(styles.margin)}>
+ <span aria-hidden="true" {...stylex.props(styles.marginRule)} />
+ <CommentPin
+ label="Open unread margin annotation from Mira"
+ participants={[PEOPLE.mira]}
+ unreadCount={1}
+ isSelected={selected === 'margin'}
+ isDimmed={selected != null && selected !== 'margin'}
+ onClick={() => toggle('margin')}
+ xstyle={styles.marginMarker}
+ />
+ </div>
+ </div>
+ </VStack>
+ );
+}
diff --git a/packages/lab/src/CommentPin/CommentPin.doc.mjs b/packages/lab/src/CommentPin/CommentPin.doc.mjs
new file mode 100644
index 0000000000..ce47a51f83
--- /dev/null
+++ b/packages/lab/src/CommentPin/CommentPin.doc.mjs
@@ -0,0 +1,328 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommentPin.doc.mjs
+ * @input CommentPin API, anatomy, ownership boundaries, and examples
+ * @output Consumer documentation for the Lab comment pin
+ * @position CLI and docsite metadata; the runnable showcase lives in packages/lab/blocks
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentAnatomyElement[]} */
+const anatomy = [
+ {
+ name: 'Marker surface',
+ required: true,
+ description:
+ 'The compact speech-bubble button surface, with a fixed 4px logical bottom-start corner. It owns selected, resolved, disabled, hover, press, focus-visible, and grouped presentation, but no coordinates.',
+ },
+ {
+ name: 'Representative avatars',
+ required: true,
+ description:
+ 'One Avatar for a single thread. A group shows its distinct participants as an AvatarGroup capped at three circles: up to three Avatars, or two Avatars plus the overflow indicator when more than three people participate. Avatars are decorative inside the marker; the button label owns accessibility.',
+ },
+ {
+ name: 'Overflow indicator',
+ required: false,
+ description:
+ 'A +N AvatarGroupOverflow circle that takes the third position when a group has more than three distinct participants. Decorative and non-interactive inside the pin.',
+ },
+ {
+ name: 'Group count',
+ required: false,
+ description:
+ 'Exact total number of represented threads. Appears when threadCount is greater than one and no represented thread is unread; it is a quantity, not ordinal identity.',
+ },
+ {
+ name: 'Unread badge',
+ required: false,
+ description:
+ 'Accent badge with the number of unread represented threads. Whenever unreadCount is above zero it replaces the group count, and it also appears on single-thread pins.',
+ },
+];
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'CommentPin',
+ displayName: 'Comment Pin',
+ group: 'Comments',
+ category: 'Chat',
+ keywords: [
+ 'annotation',
+ 'marker',
+ 'pin',
+ 'comment',
+ 'thread',
+ 'anchor',
+ 'avatar',
+ 'grouped comments',
+ 'image annotation',
+ 'margin comment',
+ ],
+ description:
+ 'Avatar-first button for opening one anchored annotation thread or a caller-defined group. A single marker shows its lead participant; a grouped marker shows up to three participant circles (two plus +N beyond three) and the total thread count. Whenever any represented thread is unread, an accent badge shows the unread count instead. The host owns anchors, coordinates, grouping, collision handling, and the comments surface.',
+ props: [
+ {
+ name: 'label',
+ type: 'string',
+ description:
+ 'Required accessible action name and hover/focus tooltip. Include grouped, unread, or resolved context when it changes the action meaning, for example “Open 4 grouped annotations from Ada and Lin, 2 unread”.',
+ required: true,
+ },
+ {
+ name: 'participants',
+ type: 'readonly [CommentPinParticipant, ...CommentPinParticipant[]]',
+ description:
+ 'Non-empty ordered participants, lead first. A single pin renders the first. A grouped pin renders distinct IDs as an AvatarGroup of at most three circles: every participant when three or fewer are distinct, otherwise the first two plus a +N overflow circle. Pass every distinct participant so the overflow count is accurate. Each record has id, name, and optional avatarSrc.',
+ required: true,
+ },
+ {
+ name: 'threadCount',
+ type: 'number',
+ description:
+ 'Total represented threads. A finite positive integer above one switches to grouped presentation and displays the exact count. The host still owns the clustering policy.',
+ default: '1',
+ },
+ {
+ name: 'unreadCount',
+ type: 'number',
+ description:
+ 'Represented threads with unread activity. When above zero, an accent badge shows this number in place of the thread total, on single and grouped pins alike. Invalid values are ignored and values above threadCount are capped. Repeat the unread context in label.',
+ default: '0',
+ },
+ {
+ name: 'isSelected',
+ type: 'boolean',
+ description:
+ 'Whether the pin is the active annotation target. Draws a solid 2px accent outline outside the pin, keeping its elevation, plus aria-pressed; the shared offset focus outline remains farther outside for keyboard focus. Follow aria-pressed toggle semantics: activating the selected pin again should clear the host selection.',
+ default: 'false',
+ },
+ {
+ name: 'isDimmed',
+ type: 'boolean',
+ description:
+ 'Whether another pin is selected. Lowers this pin’s opacity without disabling it, so it remains available to switch selection. Leave it false on every pin when nothing is selected. Selected presentation wins if both are true.',
+ default: 'false',
+ },
+ {
+ name: 'isResolved',
+ type: 'boolean',
+ description:
+ 'Whether every represented thread is resolved. Reduces marker prominence while keeping it available; selected treatment wins visually when both are true.',
+ default: 'false',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Disables activation with native button semantics. Useful for a pending anchor before its thread exists.',
+ default: 'false',
+ },
+ {
+ name: 'onClick',
+ type: 'MouseEventHandler<HTMLButtonElement>',
+ description:
+ 'Product-owned activation handler. Open or select the represented thread/group here; CommentPin owns no comments or popover state.',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description:
+ 'StyleX layout customization for the button root. Hosts may position it over content or in a margin; absolute anchors map to the logical bottom-start corner by placing the inline-start edge at the anchor and translating the pin upward by its full height.',
+ },
+ ],
+ theming: {
+ targets: [
+ {
+ className: 'astryx-comment-pin',
+ visualProps: ['grouped', 'unread', 'selected', 'dimmed', 'resolved', 'disabled'],
+ },
+ ],
+ },
+ usage: {
+ anatomy,
+ description:
+ 'Use CommentPin as the interactive anchor for comments attached to images, documents, canvases, table regions, or content margins. Pass the distinct participants (lead first), the total number of threads the host grouped at that anchor, and how many of them are unread. The component intentionally has no coordinates, anchor IDs, thread IDs, clustering algorithm, popover, or Comments dependency: those stay with the product so the same marker can sit over transformed media or in normal document layout. Participant Avatars and the overflow circle suppress their own tooltips and interaction; the pin is the only button and its label is the complete action name.',
+ accessibility: [
+ {
+ name: 'Native button activation',
+ category: 'Keyboard',
+ criterion: '2.1.1 Keyboard',
+ description:
+ 'CommentPin is one native button. Tab reaches an enabled pin; Enter and Space activate it. A disabled pin uses native disabled semantics and is removed from sequential focus order.',
+ },
+ {
+ name: 'Selected state and name',
+ category: 'Semantics',
+ criterion: '4.1.2 Name, Role, Value',
+ description:
+ 'The required label is the button name and tooltip. aria-pressed communicates controlled selection; participant Avatars, the overflow circle, the visible thread total, and the unread badge remain decorative, so repeat grouped and unread context in label.',
+ },
+ {
+ name: 'Selection and focus',
+ category: 'Color contrast',
+ criterion: '1.4.11 Non-text Contrast',
+ description:
+ 'The solid 2px accent outline hugs the pin while the shared focus-visible outline sits farther outside it, so selection and keyboard focus remain distinguishable; forced colors uses the platform Highlight treatment. Verify both selected and selected-plus-focused states against the host surface.',
+ },
+ ],
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass the lead commenter first. For a group, pass every distinct participant ordered by how well they help users recognize the cluster; the pin shows up to three circles and summarizes the rest as +N.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Write a complete label that names the action and relevant context, such as “Open 4 grouped annotations from Ada and Lin”.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep coordinates, zoom/rotation transforms, collision handling, group membership, and thread selection in the host; position the pin with layout composition or xstyle.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Map an absolute anchor coordinate to the pin’s logical bottom-start corner, not its center. Place the pin’s inline-start edge at the anchor and translate it upward by its full height.',
+ },
+ {
+ guidance: true,
+ description:
+ 'When one pin is selected, pass isDimmed to the other pins instead of disabling them. They stay available to switch selection while the active pin holds visual focus. When nothing is selected, no pin dims.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Treat selection as an aria-pressed toggle: when the selected pin is activated again, clear the host selection.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Treat threadCount as quantity only. The Avatar identities stay primary even when the total is large.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass unreadCount whenever represented threads have unread activity. Its accent badge replaces the thread total so unread work is always visible; repeat the unread count in label.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use an ordinal number as the marker identity. Numbering becomes unstable and hard to scan as annotations are inserted, removed, filtered, or grouped.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Put interactive Avatar links or buttons inside the marker. The marker root owns the one action and accessible name.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Slice participants yourself to control the overflow. Pass every distinct participant so the +N circle reports the real number of hidden people.',
+ },
+ ],
+ },
+ examples: [
+ {
+ label: 'Single thread',
+ code: `<CommentPin
+ label="Open annotation from Ada"
+ participants={[{id: 'ada', name: 'Ada Lovelace', avatarSrc: '/ada.jpg'}]}
+ onClick={() => openThread('thread-1')}
+/>`,
+ },
+ {
+ label: 'Grouped threads',
+ code: `<CommentPin
+ label="Open 4 grouped annotations from Ada and Lin"
+ participants={[
+ {id: 'ada', name: 'Ada Lovelace', avatarSrc: '/ada.jpg'},
+ {id: 'lin', name: 'Lin Chen', avatarSrc: '/lin.jpg'},
+ ]}
+ threadCount={4}
+ isSelected={selectedCluster === 'cluster-1'}
+ onClick={() => setSelectedCluster('cluster-1')}
+/>`,
+ },
+ {
+ label: 'Unread threads with participant overflow',
+ code: `// Five distinct people: two Avatars plus a +3 circle.
+// Two unread threads: the accent badge shows 2 instead of the total.
+<CommentPin
+ label="Open 6 grouped annotations from Ada, Lin, and 3 others, 2 unread"
+ participants={[ada, lin, mira, noah, sam]}
+ threadCount={6}
+ unreadCount={2}
+ onClick={() => setSelectedCluster('cluster-2')}
+/>`,
+ },
+ {
+ label: 'Host-owned placement',
+ code: `const positions = stylex.create({
+ marker: {
+ position: 'absolute',
+ insetInlineStart: '42%',
+ insetBlockStart: '28%',
+ transform: 'translateY(-100%)',
+ },
+});
+
+<div className="annotated-content">
+ <img src="/diagram.png" alt="System diagram" />
+ <CommentPin
+ label="Open annotation from Mira"
+ participants={[{id: 'mira', name: 'Mira Patel'}]}
+ xstyle={positions.marker}
+ onClick={openAnnotation}
+ />
+</div>`,
+ },
+ ],
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
+export const docsZh = {
+ description:
+ '用于打开单个锚定批注线程或调用方定义线程组的头像优先按钮。单线程显示主要参与者头像;分组标记最多显示三个圆形(超过三人时显示两个头像和 +N),并显示线程总数;有未读线程时以强调色徽章显示未读数。',
+ propDescriptions: {
+ label: '必填的无障碍操作名称及悬停/聚焦提示;包含分组、未读或已解决上下文。',
+ participants: '有序参与者列表(主要参与者在前);单线程显示第一个;分组最多显示三个圆形,超过三位不同参与者时显示前两个头像和 +N 溢出圆形。',
+ threadCount: '所代表的线程总数;大于 1 时使用分组样式并显示准确数量。',
+ unreadCount: '有未读活动的线程数;大于 0 时以强调色徽章替代线程总数显示,单线程同样适用。',
+ isSelected: '标记是否为当前批注目标;再次激活已选中的标记时,宿主应清除选择(aria-pressed 切换语义)。',
+ isDimmed: '其他标记被选中时降低此标记的视觉突出度,但不禁用操作;未选中任何标记时不应降低。',
+ isResolved: '所代表的线程是否都已解决。',
+ isDisabled: '使用原生按钮语义禁用激活。',
+ onClick: '由产品拥有的激活处理函数。',
+ xstyle: '根按钮的 StyleX 布局样式;由宿主决定内容上方或边距中的位置。',
+ },
+};
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
+export const docsDense = {
+ description:
+ 'avatar-first annotation anchor; 1 lead Avatar for one thread; groups show max 3 circles (2 Avatars + +N beyond 3) + exact total; accent unread badge replaces the total when unreadCount > 0; host owns placement/grouping',
+ usage: {
+ description:
+ 'Interactive anchor for comments over content or in margins. Pass every distinct participant, the total thread count, and the unread thread count; keep coordinates, clustering, collisions, thread state, and opened UI in the host. Absolute coordinates map to the logical bottom-start corner, while another pin is selected its siblings use isDimmed and remain interactive, and activating the selected pin again clears the host selection.',
+ bestPractices: [
+ {guidance: true, description: 'Pass the lead commenter first and write a complete action label, including unread context.'},
+ {guidance: true, description: 'Use threadCount as quantity, never ordinal identity; pass unreadCount so unread work outranks the total.'},
+ {guidance: false, description: 'Nest interactive Avatars, slice participants to fake the overflow, or pass coordinates/grouping logic into the marker.'},
+ ],
+ },
+ propDescriptions: {
+ label: 'required action name + hover/focus tooltip; include grouped/unread context',
+ participants: 'non-empty ordered tuple of {id,name,avatarSrc?}; single renders 1; groups render ≤3 circles (2 + +N overflow beyond 3 distinct)',
+ threadCount: 'positive integer total; >1 selects grouped presentation; default 1',
+ unreadCount: 'unread represented threads; >0 shows accent badge instead of total (single and grouped); capped at threadCount; default 0',
+ isSelected: 'controlled active pin; solid 2px accent outline outside the pin + aria-pressed; host clears it when the selected pin is activated again',
+ isDimmed: 'controlled de-emphasis for non-selected siblings only while another pin is selected; remains interactive',
+ isResolved: 'controlled lower-prominence resolved state',
+ isDisabled: 'native disabled marker',
+ onClick: 'host activation handler',
+ xstyle: 'root layout/positioning styles; marker owns no coordinates',
+ },
+};
diff --git a/packages/lab/src/CommentPin/CommentPin.spec.md b/packages/lab/src/CommentPin/CommentPin.spec.md
new file mode 100644
index 0000000000..40a6255f6f
--- /dev/null
+++ b/packages/lab/src/CommentPin/CommentPin.spec.md
@@ -0,0 +1,307 @@
+---
+schema_version: 3
+template_version: 7
+kind: component
+id: component:CommentPin
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang, imdreamrunner]
+review_triggers:
+ [
+ public-api,
+ behavior,
+ layout,
+ theming,
+ accessibility,
+ interaction,
+ testing,
+ visual,
+ ]
+verified_by:
+ [
+ packages/lab/src/CommentPin/CommentPin.test.tsx,
+ apps/storybook/stories/CommentPin.stories.tsx,
+ packages/lab/blocks/CommentPinShowcase.tsx,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:component-test-sufficiency,
+ architecture:component-theming-surface,
+ architecture:interaction-modality,
+ architecture:public-component-api,
+ architecture:theme-tokens,
+ ]
+contributing: []
+system_specs: [spec:AST-002]
+---
+
+# CommentPin component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `@astryxdesign/lab` exports one `CommentPin` button, its props, and its participant data type. |
+| Behavior | A marker renders the first participant for one thread. A marker representing multiple threads renders its distinct participants as an AvatarGroup of at most three circles (two Avatars plus a +N overflow beyond three) and the total thread count. Whenever any represented thread is unread, an accent badge with the unread count replaces the total on single and grouped markers. |
+| End-user impact | Annotation anchors identify people rather than positions in an ordinal sequence. Grouped anchors keep a bounded set of participant identities while exposing the number of threads they open, and unread activity stays visible as a count. |
+| Builder impact | Callers provide every distinct participant in order, the total and unread thread counts, an accessible action label, activation behavior, and controlled selected/dimmed/resolved/disabled state. |
+| Compatibility/readiness | Additive experimental Lab component. Its API and visual treatment remain draft until product use and visual evidence settle them. |
+| Review checks | Reject ordinal identity, pin-owned clustering or coordinates, center-anchored placement, interactive descendant avatars, more than three participant circles, an unread count hidden behind the total, generated application copy, hidden thread-count semantics, dimming that disables sibling selection, or selected/resolved paint that obscures participant identity. |
+| Governing rules | `architecture:public-component-api`, `architecture:component-theming-surface`, `architecture:interaction-modality`, `architecture:component-test-sufficiency`, and `spec:AST-002`. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+CommentPin is the compact interactive surface for opening one anchored
+annotation thread or a caller-defined group of threads. It preserves a human
+identity cue at the anchor while remaining usable over content or in a content
+margin.
+
+## Compatibility and migration
+
+- Released default preserved: `not yet released`
+- Compatibility class: additive experimental Lab API
+- Controlled/uncontrolled behavior: selected, dimmed, resolved, and disabled
+ states and the unread count are caller-controlled; the component owns no
+ selection or read state
+- Migration decision: none; callers replace bespoke annotation-pin visuals after
+ the Lab contract is accepted
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- One button surface, its single/grouped visual transformation, and its
+ selected, dimmed, resolved, disabled, hover, press, and focus-visible
+ presentation.
+- Rendering ordered participant data through `Avatar`, or for a group through
+ `AvatarGroup` with a non-interactive `AvatarGroupOverflow`, without making
+ descendants interactive.
+- Showing the unread thread count in an accent badge whenever it is above
+ zero, otherwise the total represented thread count when that total is
+ greater than one.
+- The stable `comment-pin` theming target and state reflection.
+
+**Does not own / non-goals**
+
+- Thread data, unread tracking, authorization, loading, transport, selection
+ state, or the panel opened by activation — owned by the product callsite.
+- Clustering, participant ordering, anchor identity, coordinates, collision
+ handling, image transforms, margin layout, or connector lines — owned by the
+ product callsite.
+- Avatar loading/fallback, shape, and identity paint — delegated to
+ `component:Avatar`; overflow indicator paint — delegated to
+ `component:AvatarGroup`.
+- Ordinal numbering of annotations. Thread count is a quantity for a grouped
+ marker, never the marker's identity.
+
+## Public concepts
+
+Consumer prop syntax and examples remain in `CommentPin.doc.mjs`.
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------ | ----------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| participants | non-empty ordered participant tuple | every distinct identity in the thread or group, lead first; groups display at most three circles | every pin | required non-empty tuple | product supplies; component renders | experimental Lab | TypeScript rejects an empty tuple; untyped empty input falls back to a decorative anonymous Avatar and warns in development |
+| represented thread total | positive integer | number of threads opened by the marker; values above one select grouped presentation | every marker | `1` | product | experimental Lab | non-finite, fractional, or values below one resolve to one and warn in development |
+| unread thread total | non-negative integer no greater than the total | number of represented threads with unread activity; above zero, an accent badge replaces the total | every marker | `0` | product | experimental Lab | non-finite, fractional, or negative values are ignored; values above the total are capped; both warn in development |
+| selected state | selected, not selected | whether this pin is the active annotation target | enabled and disabled | not selected | product | experimental Lab | closed boolean |
+| dimmed state | dimmed, not dimmed | whether another pin is selected; lowers prominence without disabling activation | non-selected pins | not dimmed | product | experimental Lab | closed boolean; selected paint wins when both are true |
+| resolved state | resolved, unresolved | whether the represented thread set is considered resolved | every marker | unresolved | product | experimental Lab | closed boolean |
+| disabled state | disabled, enabled | whether the marker can activate | every marker | enabled | product | experimental Lab | closed boolean |
+| accessible action name | non-empty caller-authored string | names the action and supplies the marker tooltip without generating application-specific copy | every marker | required | product | experimental Lab | TypeScript requires a string; blank content remains a caller error |
+| DOM extension | supported button `BaseProps`, styling, and ref | positions the marker and wires product-owned interaction without giving the component coordinates | every marker | no additional inputs | `architecture:public-component-api` | experimental Lab | unsupported native props remain unavailable |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision. A `current` contract contains no unresolved rows.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------- | ----------------------------------------------------------- |
+| FR1 | CommentPin MUST render one button and MUST NOT accept, derive, or mutate anchor coordinates, grouping membership, thread selection, or collision layout. | product ownership boundary | product direction; pending owner approval |
+| FR2 | With one represented thread, the marker MUST render only the first participant Avatar and MUST NOT use an ordinal number as identity. | product direction | product direction; pending owner approval |
+| FR3 | With more than one represented thread, the marker MUST render its distinct participants as an AvatarGroup of at most three circles — every participant when three or fewer are distinct, otherwise the first two followed by a non-interactive `+N` AvatarGroupOverflow circle counting the rest — followed by the exact represented thread total unless FR10 applies. | product direction | product direction; pending owner approval |
+| FR4 | Participant Avatars and the overflow circle MUST use their core components' fallback and paint, MUST suppress tooltips and interaction, and MUST remain decorative descendants of the marker button. | Avatar composition and valid interaction tree | candidate implementation |
+| FR5 | `isSelected`, `isDimmed`, `isResolved`, and `isDisabled` MUST remain independent caller-controlled states. Selected presentation MUST draw a solid 2px accent outline outside the pin as a box-shadow ring over a transparent border, with no accent fill and no layout shift, MUST preserve the resting medium elevation and Avatar legibility, MUST remain distinct from the shared focus outline positioned farther outside, MUST retain a visible forced-colors fallback, and MUST win over dimming; dimmed presentation MUST lower non-selected pins' prominence without disabling activation; resolved presentation MUST reduce prominence without hiding the pin. | migration use cases and visual direction | candidate implementation; rendered visual review pending |
+| FR6 | The marker root MUST combine `xstyle`, `className`, and `style`, forward neutral button DOM/event props and its ref, and keep component-owned type, label, selected semantics, disabled state, target, and reflected states authoritative. | public component API architecture | candidate implementation |
+| FR7 | Hover paint MUST be guarded by hover capability, touch press feedback MUST use the shared press model, and keyboard focus MUST use the shared focus-visible treatment. | interaction-modality architecture | candidate implementation |
+| FR8 | The root MUST keep a speech-bubble silhouette with a fixed 4px logical bottom-start corner and full-radius logical start-start, start-end, and end-end corners in every visual state, in LTR and RTL. The 4px corner MUST NOT follow a theme radius override. | product visual direction and logical-layout requirement | candidate implementation; rendered visual review pending |
+| FR9 | The root's transform origin and documented absolute-placement convention MUST use the logical bottom-start corner. A host maps its anchor point to that corner by translating the pin upward by its full height and MUST NOT center the pin over the point. | product placement direction | candidate implementation; rendered placement review pending |
+| FR10 | When `unreadCount` resolves above zero, the marker MUST show that number in an accent badge in place of the thread total, on single and grouped markers alike; the badge MUST keep a visible forced-colors treatment and MUST remain decorative. | product direction | product direction; rendered visual review pending |
+
+### Allowed variation
+
+- **AV1 — Participant identity.** Names and image sources vary; Avatar owns
+ image loading, fallback initials, and anonymous fallback.
+- **AV2 — Product placement.** Callers position the root over content or in a
+ content margin through layout composition and supported styling inputs. An
+ absolute anchor coordinate maps to the logical bottom-start corner rather
+ than the pin's center.
+- **AV3 — Thread grouping.** Callers may use any clustering policy and
+ participant ordering while the marker's visual transformation remains fixed.
+- **AV4 — Theme output.** Themes may repaint the admitted root target and its
+ reflected states without changing behavior or descendant Avatar ownership.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ------------------------ | --------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
+| Single | first participant Avatar; no visible count unless unread | identity, selected/dimmed/resolved/disabled state, placement |
+| Grouped, one identity | one Avatar plus total thread count | count and states |
+| Grouped, two or three | every distinct participant Avatar plus total thread count | ordered identities, count, and states |
+| Grouped, more than three | first two distinct Avatars, a `+N` overflow circle, and total thread count | ordered identities, overflow count, and states |
+| Unread | accent badge with the unread count replaces the total on single and grouped markers | unread count and other states |
+| Selected | active accent treatment preserves Avatar and count legibility and wins over dimming | theme paint |
+| Dimmed | lower opacity identifies a non-selected sibling without disabling activation | resolved and disabled may also apply |
+| Resolved | lower-prominence treatment preserves activation and identity | selected, dimmed, and disabled may also apply |
+| Disabled | native disabled button does not activate and is removed from the sequential focus order | selected/resolved representation remains visible |
+
+### Transformation and precedence order
+
+- **ORD1 — Count normalization.** Validate `threadCount`; an invalid value
+ resolves to one, then a value above one selects grouped presentation.
+ Validate `unreadCount` next; an invalid value is ignored and a value above
+ the resolved total is capped to it.
+- **ORD2 — Participants.** Preserve caller order and remove duplicate IDs. A
+ single marker takes the first participant; a grouped marker shows every
+ distinct participant when three or fewer remain, otherwise the first two plus
+ an overflow count of the rest.
+- **ORD3 — Count display.** A resolved unread count above zero replaces the
+ thread total; otherwise a grouped marker shows the total.
+- **ORD4 — Paint.** Base surface, resolved treatment, dimmed treatment, selected
+ treatment, then disabled treatment compose in that order. Selected identity
+ remains fully prominent, and disabled interaction always wins.
+
+### Performance and resources
+
+- **PR1 — Bounded anatomy.** Rendering work is bounded to at most three
+ participant circles (Avatars plus overflow indicator) and one count element
+ regardless of the number of represented threads or supplied participants.
+- **PR2 — Shared interaction resources.** Touch feedback uses the shared
+ document-level press controller and adds no marker-local listener, observer,
+ timer, or state.
+
+Current measurements belong in the audit record; this subsection owns only
+durable constraints and their verification target.
+
+## Accessibility contract
+
+- **AR1 — Action.** The root is one native `button type="button"` named by the
+ required `label`; `isDisabled` uses native disabled behavior.
+- **AR2 — Selection.** `isSelected` is exposed through `aria-pressed`, one solid
+ 2px accent outline outside the pin, and a forced-colors Highlight treatment;
+ the outline hugs the pin while the shared focus-visible outline sits farther
+ outside, so the two states remain distinguishable.
+ Hosts clear the selection when the selected pin is activated again.
+- **AR3 — Decorative descendants.** Participant Avatars, the overflow circle,
+ the visible thread total, and the unread badge are hidden from assistive
+ technology because the caller-authored button label owns the complete action
+ name.
+- **AR4 — Tooltip.** The action label is available visually on pointer hover and
+ keyboard focus; activation remains the primary touch behavior.
+- **AR5 — State naming.** Callers include resolved, grouped, or unread context
+ in `label` when it changes the action's meaning; the component does not mint
+ application-specific or locale-sensitive copy.
+- **AR6 — Dimmed siblings.** `isDimmed` changes presentation only. It MUST NOT
+ set disabled or aria-disabled because a non-selected pin remains an available
+ target for switching selection.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------------------- | ------------------ |
+| Marker surface | Compact floating surface distinguishes the action from underlying content | candidate implementation pending visual review | prominent anchor | FR1, FR5, FR7 |
+| Representative avatars | Human identity remains the primary recognition cue; groups cap at three circles | human-selected product direction | primary content | FR2–FR4 |
+| Overflow indicator | A `+N` circle summarizes participants beyond the first two without growing the pin past three circles | human-selected product direction | supporting content | FR3, FR4, AR3 |
+| Group count | Count communicates quantity without becoming ordinal identity | human-selected product direction | supporting content | FR3, AR3 |
+| Unread badge | Accent badge keeps unread activity visible and outranks the thread total | human-selected product direction | supporting state signal | FR10, AR3 |
+| Selected/dimmed/resolved states | Selected draws one solid 2px accent outline outside the pin with no fill, distinct from the farther-out focus outline; non-selected siblings dim without disabling; resolved lowers prominence | human-selected product direction | supporting state signal | FR5, AR2, AR6 |
+| Speech-bubble corner | Logical bottom-start stays fixed at 4px and mirrors in RTL; the other three logical corners stay fully rounded | human-selected product direction | silhouette cue | FR8 |
+| Placement origin | Absolute host coordinates map to logical bottom-start, never the center | human-selected product direction | spatial anchor | FR9 |
+
+### Design decisions
+
+<!-- design-decisions:v1 -->
+
+| ID | Decision | Intent or reason | Applies to | Allowed variation |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------ | ----------------------------------------------------------------------------------------------- |
+| DD1 | Participant Avatars, not ordinal numbers, identify comment pins. | Ordinal identity becomes hard to scan and manage as annotation volume grows. | single and grouped markers | identity data and Avatar fallback may vary |
+| DD2 | A grouped marker shows at most three participant circles — two Avatars plus a `+N` overflow when more than three people participate — and separately shows the thread total. | Identity and quantity answer different questions; capping the facepile keeps grouped pins compact and scannable as participation grows. | grouped markers | caller chooses participant order and grouping policy |
+| DD3 | Selected paint is one solid 2px accent outline outside the pin, drawn as a box-shadow ring over a transparent border; it preserves the pin's medium elevation and adds no accent fill; the shared focus outline sits farther outside. | A single 2px outline reads as selection rather than input chrome, shifts no layout, preserves the Avatar area, and remains distinct from keyboard focus. | selected and selected-plus-focused states | theme accent and elevation tokens may vary; the outline width, placement, and separation do not |
+| DD4 | The logical bottom-start corner is a fixed 4px logical longhand; the other three logical corners use the full-radius token. | A theme may enlarge `--radius-inner`, so a literal keeps the speech-bubble cue exactly 4px, and explicit logical longhands avoid shorthand cascade collisions and mirror in RTL by construction. | every pin and visual state | the three rounded corners follow the theme; the 4px anchor corner does not vary |
+| DD5 | Absolute anchor coordinates map to the pin's logical bottom-start corner, not its center. | The speech-bubble corner stays attached to the annotated point while the body grows toward block-start and inline-end. | pins positioned over content or in margins | host coordinates and transforms may vary; the anchor corner does not |
+| DD6 | When a pin is selected, sibling pins use controlled dimming and remain enabled. | The active target gains visual focus without preventing a viewer from switching directly to another pin. | sets of pins with one active target | host chooses which siblings belong to the focused set; selected always wins over dimming |
+| DD7 | Unread threads show their count in an accent badge that replaces the thread total. | Unread activity is the actionable signal, so it outranks quantity whenever present, including on single-thread pins. | single and grouped markers | theme accent may vary; the replacement precedence does not |
+
+### Theming anatomy
+
+<!-- anatomy-theming:v1 -->
+
+```json
+{
+ "Marker surface": {"target": "comment-pin"},
+ "Representative avatars": {
+ "delegatesTo": {"owner": "component:Avatar", "target": "avatar"}
+ },
+ "Overflow indicator": {
+ "delegatesTo": {
+ "owner": "component:AvatarGroup",
+ "target": "avatar-group-overflow"
+ }
+ },
+ "Group count": {"inherits": "comment-pin"},
+ "Unread badge": {"inherits": "comment-pin"}
+}
+```
+
+## Family and system relationships
+
+- `architecture:public-component-api` owns DOM reachability, prop semantics,
+ styling composition, handler forwarding, and React 19 refs.
+- `architecture:component-theming-surface` owns the one root painting target,
+ reflected states, and delegated Avatar ownership.
+- `architecture:interaction-modality` owns hover capability, touch press, and
+ focus-visible behavior.
+- `architecture:component-test-sufficiency` owns representative-state and
+ mutation-sensitive regression evidence.
+- `architecture:theme-tokens` owns the semantic color, radius, spacing,
+ typography, motion, and shadow vocabulary used by the baseline paint.
+- `spec:AST-002` owns admission of the public Lab surface and invalid-input
+ behavior.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ---------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
+| FR1–FR4, FR10, PR1, AR1, AR3 | `CommentPin.test.tsx` | single, grouped within three, grouped overflow, unread single and grouped, invalid unread, duplicate identities, empty participants | extra anatomy, more than three circles, a wrong overflow count, an unread count hidden behind the total, ordinal identity, lost count, or interactive/avatar semantics fail focused assertions | `audit:CommentPin/behavior` |
+| FR5, FR8, FR9, AR2, AR5, AR6 | focused tests plus Storybook state matrix, placement example, and docsite showcase | selected, selected+focused, dimmed, forced colors, resolved, disabled, LTR/RTL silhouette and placement | missing state reflection, disabled dimmed siblings, merged selection/focus cues, or centered/non-mirroring placement fails semantic/source assertions or rendered review | `audit:CommentPin/states` |
+| FR6 | focused passthrough, ref, stable-target, and state-reflection tests | custom DOM/style inputs and every state | dropped inputs/ref or overwritten component-owned semantics fail focused assertions | `audit:CommentPin/api-theming` |
+| FR7, PR2, AR4 | focus, hover-capability source inspection, tooltip test, build scan | pointer, keyboard, touch model | unguarded hover, missing focus treatment, or local press machinery fails source/test/build checks | `audit:CommentPin/interaction` |
+| Documentation and surface | component docs, block metadata, root export, Storybook, and knowledge check | public examples and component discovery | missing or stale discoverability, syntax, boundaries, or relationships fail repository checks | `audit:CommentPin/docs` |
+
+## Decision log
+
+None. This record remains draft; its candidate requirements and local design
+intent await component-owner and visual review.
+
+## Open questions
+
+- **OQ1 — Does the selected/resolved state treatment preserve enough contrast on
+ representative images and every theme while remaining distinct over both
+ image content and page margins?** (`human-design`)
+
+## Content boundary
+
+This file does not duplicate consumer prop tables/examples, current audit
+results, implementation steps, product grouping algorithms, coordinate systems,
+or family/system rules. It links to their owners.
diff --git a/packages/lab/src/CommentPin/CommentPin.test.tsx b/packages/lab/src/CommentPin/CommentPin.test.tsx
new file mode 100644
index 0000000000..817777af24
--- /dev/null
+++ b/packages/lab/src/CommentPin/CommentPin.test.tsx
@@ -0,0 +1,350 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {CommentPin} from './CommentPin';
+
+const ADA = {id: 'ada', name: 'Ada Lovelace'};
+const LIN = {id: 'lin', name: 'Lin Chen'};
+const MIRA = {id: 'mira', name: 'Mira Patel'};
+const NOAH = {id: 'noah', name: 'Noah Williams'};
+const SAM = {id: 'sam', name: 'Sam Rivera'};
+
+describe('CommentPin', () => {
+ it('renders one labelled button and one representative for a single thread', () => {
+ const {container} = render(
+ <CommentPin label="Open annotation from Ada" participants={[ADA]} />,
+ );
+
+ expect(
+ screen.getByRole('button', {name: 'Open annotation from Ada'}),
+ ).toHaveAttribute('aria-pressed', 'false');
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(1);
+ expect(screen.queryByText('1')).not.toBeInTheDocument();
+ });
+
+ it('shows up to three distinct participants and the exact total for a group', () => {
+ const {container} = render(
+ <CommentPin
+ label="Open 12 grouped annotations"
+ participants={[ADA, ADA, LIN, MIRA]}
+ threadCount={12}
+ />,
+ );
+
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(3);
+ expect(
+ container.querySelector('.astryx-avatar-group-overflow'),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText('12')).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', {name: 'Open 12 grouped annotations'}),
+ ).toHaveAttribute('data-grouped', 'grouped');
+ });
+
+ it('caps a group at three circles with a +N overflow beyond three people', () => {
+ const {container} = render(
+ <CommentPin
+ label="Open 6 grouped annotations from Ada, Lin, and 3 others"
+ participants={[ADA, LIN, MIRA, NOAH, SAM]}
+ threadCount={6}
+ />,
+ );
+
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(2);
+ const overflow = container.querySelector('.astryx-avatar-group-overflow');
+ expect(overflow).toHaveTextContent('+3');
+ expect(overflow?.closest('[aria-hidden="true"]')).not.toBeNull();
+ expect(screen.getByText('6')).toBeInTheDocument();
+ });
+
+ it('shows the unread count in an accent badge in place of the total', () => {
+ const {container} = render(
+ <CommentPin
+ label="Open 4 grouped annotations, 2 unread"
+ participants={[ADA, LIN]}
+ threadCount={4}
+ unreadCount={2}
+ />,
+ );
+
+ const pin = screen.getByRole('button', {
+ name: 'Open 4 grouped annotations, 2 unread',
+ });
+ expect(pin).toHaveAttribute('data-unread', 'unread');
+ expect(screen.getByText('2')).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.queryByText('4')).not.toBeInTheDocument();
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(2);
+ });
+
+ it('shows an unread badge on a single-thread pin', () => {
+ render(
+ <CommentPin
+ label="Open unread annotation from Ada"
+ participants={[ADA]}
+ unreadCount={1}
+ />,
+ );
+
+ const pin = screen.getByRole('button', {
+ name: 'Open unread annotation from Ada',
+ });
+ expect(pin).toHaveAttribute('data-unread', 'unread');
+ expect(pin).not.toHaveAttribute('data-grouped');
+ expect(screen.getByText('1')).toBeInTheDocument();
+ });
+
+ it.each([
+ [-1, null],
+ [1.5, null],
+ [Number.NaN, null],
+ [9, '3'],
+ ])(
+ 'normalizes unreadCount %s and warns in development',
+ async (unreadCount, expectedBadge) => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {container, unmount} = render(
+ <CommentPin
+ label="Open annotations"
+ participants={[ADA, LIN]}
+ threadCount={3}
+ unreadCount={unreadCount}
+ />,
+ );
+
+ const pin = container.querySelector('.astryx-comment-pin');
+ if (expectedBadge == null) {
+ expect(pin).not.toHaveAttribute('data-unread');
+ expect(screen.getByText('3')).toBeInTheDocument();
+ } else {
+ expect(pin).toHaveAttribute('data-unread', 'unread');
+ expect(screen.getByText(expectedBadge)).toBeInTheDocument();
+ }
+ await waitFor(() =>
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining('unreadCount` must be a finite non-negative'),
+ ),
+ );
+ unmount();
+ warning.mockRestore();
+ },
+ );
+
+ it('does not expose visible Avatar or count semantics separately from the button', () => {
+ const {container} = render(
+ <CommentPin
+ label="Open 4 annotations from Ada and Lin"
+ participants={[ADA, LIN]}
+ threadCount={4}
+ />,
+ );
+
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+ expect(screen.queryByRole('group')).not.toBeInTheDocument();
+ expect(
+ container
+ .querySelector('.astryx-avatar')
+ ?.closest('[aria-hidden="true"]'),
+ ).toHaveAttribute('aria-hidden', 'true');
+ expect(screen.getByText('4')).toHaveAttribute('aria-hidden', 'true');
+ });
+
+ it('keeps a single marker to one representative even when more are supplied', () => {
+ const {container} = render(
+ <CommentPin label="Open annotation" participants={[ADA, LIN, MIRA]} />,
+ );
+
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(1);
+ expect(container.querySelector('.astryx-comment-pin')).not.toHaveAttribute(
+ 'data-grouped',
+ );
+ });
+
+ it('reflects selected, resolved, and disabled state on the owning target', () => {
+ render(
+ <CommentPin
+ label="Resolved selected annotation"
+ participants={[ADA]}
+ isSelected
+ isResolved
+ isDisabled
+ />,
+ );
+
+ const marker = screen.getByRole('button', {
+ name: 'Resolved selected annotation',
+ });
+ expect(marker).toHaveAttribute('aria-pressed', 'true');
+ expect(marker).toBeDisabled();
+ expect(marker).toHaveAttribute('data-selected', 'selected');
+ expect(marker).toHaveAttribute('data-resolved', 'resolved');
+ expect(marker).toHaveAttribute('data-disabled', 'disabled');
+ });
+
+ it('dims non-selected pins without disabling selection changes', () => {
+ const onClick = vi.fn();
+ render(
+ <CommentPin
+ label="Open another annotation"
+ participants={[LIN]}
+ isDimmed
+ onClick={onClick}
+ />,
+ );
+
+ const pin = screen.getByRole('button', {name: 'Open another annotation'});
+ expect(pin).toHaveAttribute('data-dimmed', 'dimmed');
+ expect(pin).not.toBeDisabled();
+ fireEvent.click(pin);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('calls the forwarded click handler when enabled', () => {
+ const onClick = vi.fn();
+ render(
+ <CommentPin
+ label="Open annotation"
+ participants={[ADA]}
+ onClick={onClick}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open annotation'}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('activates through the native button keyboard contract', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <CommentPin
+ label="Open annotation"
+ participants={[ADA]}
+ onClick={onClick}
+ />,
+ );
+
+ const pin = screen.getByRole('button', {name: 'Open annotation'});
+ pin.focus();
+ await user.keyboard('{Enter}');
+ await user.keyboard(' ');
+
+ expect(onClick).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not call the click handler when disabled', () => {
+ const onClick = vi.fn();
+ render(
+ <CommentPin
+ label="Pending annotation"
+ participants={[ADA]}
+ isDisabled
+ onClick={onClick}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Pending annotation'}));
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('forwards the ref and neutral button props', () => {
+ const ref = {current: null as HTMLButtonElement | null};
+ render(
+ <CommentPin
+ ref={ref}
+ label="Open annotation"
+ participants={[ADA]}
+ data-cluster-id="cluster-1"
+ aria-controls="thread-panel"
+ />,
+ );
+
+ expect(ref.current).toBeInstanceOf(HTMLButtonElement);
+ expect(ref.current).toHaveAttribute('type', 'button');
+ expect(ref.current).toHaveAttribute('data-cluster-id', 'cluster-1');
+ expect(ref.current).toHaveAttribute('aria-controls', 'thread-panel');
+ });
+
+ it('combines the stable target with a caller class and style', () => {
+ render(
+ <CommentPin
+ label="Open annotation"
+ participants={[ADA]}
+ className="host-position"
+ style={{insetInlineStart: 24}}
+ />,
+ );
+
+ const marker = screen.getByRole('button', {name: 'Open annotation'});
+ expect(marker.className).toContain('astryx-comment-pin');
+ expect(marker.className).toContain('host-position');
+ expect(marker).toHaveStyle({insetInlineStart: '24px'});
+ });
+
+ it('falls back to a single anonymous Avatar and warns for no representatives', async () => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {container} = render(
+ <CommentPin
+ label="Open annotation"
+ participants={[] as unknown as [typeof ADA]}
+ />,
+ );
+
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(1);
+ await waitFor(() =>
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining('participants` should contain at least one'),
+ ),
+ );
+ warning.mockRestore();
+ });
+
+ it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])(
+ 'falls back to a single-thread marker for invalid threadCount %s',
+ async threadCount => {
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {container, unmount} = render(
+ <CommentPin
+ label="Open annotation"
+ participants={[ADA, LIN]}
+ threadCount={threadCount}
+ />,
+ );
+
+ expect(container.querySelectorAll('.astryx-avatar')).toHaveLength(1);
+ expect(
+ container.querySelector('.astryx-comment-pin'),
+ ).not.toHaveAttribute('data-grouped');
+ await waitFor(() =>
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining(
+ 'threadCount` must be a finite positive integer',
+ ),
+ ),
+ );
+ unmount();
+ warning.mockRestore();
+ },
+ );
+
+ it('shows its action label as a visual tooltip on hover', async () => {
+ const showPopover = vi.spyOn(HTMLElement.prototype, 'showPopover');
+ render(
+ <CommentPin label="Open annotation from Ada" participants={[ADA]} />,
+ );
+
+ const marker = screen.getByRole('button', {
+ name: 'Open annotation from Ada',
+ });
+ fireEvent.pointerEnter(marker, {pointerType: 'mouse'});
+ fireEvent.mouseEnter(marker);
+
+ await waitFor(() => expect(showPopover).toHaveBeenCalled());
+ expect(screen.getByRole('tooltip', {hidden: true})).toHaveTextContent(
+ 'Open annotation from Ada',
+ );
+ showPopover.mockRestore();
+ });
+});
diff --git a/packages/lab/src/CommentPin/CommentPin.tsx b/packages/lab/src/CommentPin/CommentPin.tsx
new file mode 100644
index 0000000000..9861895c78
--- /dev/null
+++ b/packages/lab/src/CommentPin/CommentPin.tsx
@@ -0,0 +1,484 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CommentPin.tsx
+ * @input Ordered participants (grouped pins show at most three circles),
+ * total and unread represented thread counts, controlled
+ * selected/dimmed/resolved/disabled state, and button DOM props
+ * @output Exports the avatar-first CommentPin button and its public types
+ * @position Lab collaboration primitive for annotation anchors over content or
+ * in content margins; callers own grouping, coordinates, and opened content
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/lab/src/CommentPin/CommentPin.doc.mjs
+ * - /packages/lab/src/CommentPin/CommentPin.spec.md
+ * - /packages/lab/src/CommentPin/CommentPin.test.tsx
+ * - /packages/lab/src/CommentPin/index.ts
+ * - /apps/storybook/stories/CommentPin.stories.tsx
+ * - /packages/lab/blocks/CommentPinShowcase.tsx
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '@astryxdesign/core';
+import {Avatar} from '@astryxdesign/core/Avatar';
+import {AvatarGroup, AvatarGroupOverflow} from '@astryxdesign/core/AvatarGroup';
+import {
+ useDevWarning,
+ useMergedRefs,
+ usePressFeedback,
+} from '@astryxdesign/core/hooks';
+import {
+ borderVars,
+ colorVars,
+ fontWeightVars,
+ radiusVars,
+ shadowVars,
+ sizeVars,
+ spacingVars,
+ typeScaleVars,
+ typographyVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {useTooltip} from '@astryxdesign/core/Tooltip';
+import {
+ focusOutlineProps,
+ interactionOverlayStyles,
+ mergeProps,
+ themeProps,
+} from '@astryxdesign/core/utils';
+
+/** Identity data for one representative shown inside a CommentPin. */
+export interface CommentPinParticipant {
+ /** Stable identity used to remove duplicate representatives. */
+ id: string;
+ /** Display name used by Avatar for image fallback initials. */
+ name: string;
+ /** Optional image source passed to Avatar. */
+ avatarSrc?: string;
+}
+
+export interface CommentPinProps extends Omit<
+ BaseProps<HTMLButtonElement>,
+ 'children'
+> {
+ /** Ref forwarded to the marker button. */
+ ref?: React.Ref<HTMLButtonElement>;
+ /**
+ * Accessible action name and visual hover/focus tooltip.
+ * Include grouped, unread, or resolved context when it changes the action's
+ * meaning.
+ */
+ label: string;
+ /**
+ * Ordered participants, lead first. A single marker shows the first. A
+ * grouped marker shows distinct IDs as an AvatarGroup of at most three
+ * circles: every participant when three or fewer are distinct, otherwise the
+ * first two plus a `+N` overflow circle. Pass every distinct participant so
+ * the overflow count is accurate.
+ */
+ participants: readonly [CommentPinParticipant, ...CommentPinParticipant[]];
+ /**
+ * Total number of threads represented by this marker. Values above one use
+ * the grouped presentation and show the exact total.
+ * @default 1
+ */
+ threadCount?: number;
+ /**
+ * Number of represented threads with unread activity. When above zero, an
+ * accent badge shows this number in place of the thread total, on single
+ * and grouped pins alike. Values above `threadCount` are capped.
+ * @default 0
+ */
+ unreadCount?: number;
+ /** Whether this pin is the currently selected annotation target. */
+ isSelected?: boolean;
+ /**
+ * Whether another pin is selected in the host. Dims this pin without
+ * disabling it, so it remains available to switch selection.
+ */
+ isDimmed?: boolean;
+ /** Whether every thread represented by this pin is resolved. */
+ isResolved?: boolean;
+ /** Whether activation is unavailable. */
+ isDisabled?: boolean;
+}
+
+const styles = stylex.create({
+ root: {
+ appearance: 'none',
+ boxSizing: 'border-box',
+ position: 'relative',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ verticalAlign: 'middle',
+ transformOrigin: {
+ default: 'left bottom',
+ ':is([dir="rtl"] *)': 'right bottom',
+ },
+ minWidth: sizeVars['--size-element-sm'],
+ height: sizeVars['--size-element-sm'],
+ margin: 0,
+ padding: spacingVars['--spacing-0-5'],
+ borderWidth: borderVars['--border-width'],
+ borderStyle: 'solid',
+ borderColor: 'transparent',
+ // Speech-bubble silhouette: three fully rounded logical corners and a
+ // fixed 4px logical bottom-start corner. The literal is intentional:
+ // themes may enlarge `--radius-inner`, which would soften the anchor cue.
+ // Logical longhands mirror the corner in RTL by construction.
+ borderStartStartRadius: radiusVars['--radius-full'],
+ borderStartEndRadius: radiusVars['--radius-full'],
+ borderEndEndRadius: radiusVars['--radius-full'],
+ borderEndStartRadius: '4px',
+ backgroundColor: colorVars['--color-background-popover'],
+ backgroundImage: 'none',
+ boxShadow: shadowVars['--shadow-med'],
+ color: colorVars['--color-text-secondary'],
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ whiteSpace: 'nowrap',
+ userSelect: 'none',
+ },
+ withCount: {
+ justifyContent: 'flex-start',
+ gap: spacingVars['--spacing-1'],
+ paddingInlineStart: spacingVars['--spacing-0-5'],
+ paddingInlineEnd: spacingVars['--spacing-2'],
+ },
+ selected: {
+ // Native buttons keep ButtonFace/ButtonText under forced colors unless the
+ // selected state opts out of UA remapping; author both sides together.
+ forcedColorAdjust: 'none',
+ opacity: 1,
+ // The border stays transparent so the selection reads as exactly one 2px
+ // accent outline: the box-shadow ring below, drawn outside the pin.
+ borderColor: {
+ default: 'transparent',
+ '@media (forced-colors: active)': 'Highlight',
+ },
+ backgroundColor: {
+ default: colorVars['--color-background-popover'],
+ '@media (forced-colors: active)': 'Highlight',
+ },
+ // A solid 2px accent outline outside the pin, layered with its resting
+ // medium elevation. A box-shadow ring shifts no layout, follows the
+ // speech-bubble corners, and leaves the shared focus outline (offset
+ // farther out) as a separate cue.
+ boxShadow: {
+ default: `0 0 0 2px ${colorVars['--color-accent']}, ${shadowVars['--shadow-med']}`,
+ '@media (forced-colors: active)': 'none',
+ },
+ color: {
+ default: colorVars['--color-text-secondary'],
+ '@media (forced-colors: active)': 'HighlightText',
+ },
+ },
+ resolved: {
+ // This state authors Canvas colors in forced-colors mode, so opt the native
+ // button out of ButtonFace/ButtonText remapping and author both sides.
+ forcedColorAdjust: 'none',
+ borderColor: {
+ default: 'transparent',
+ '@media (forced-colors: active)': 'CanvasText',
+ },
+ backgroundColor: {
+ default: colorVars['--color-background-muted'],
+ '@media (forced-colors: active)': 'Canvas',
+ },
+ boxShadow: 'none',
+ color: {
+ default: colorVars['--color-text-secondary'],
+ '@media (forced-colors: active)': 'CanvasText',
+ },
+ opacity: {
+ default: 0.72,
+ '@media (forced-colors: active)': 1,
+ },
+ },
+ dimmed: {
+ opacity: {
+ default: 0.4,
+ '@media (forced-colors: active)': 1,
+ },
+ },
+ disabled: {
+ cursor: 'default',
+ opacity: {
+ default: 0.45,
+ '@media (forced-colors: active)': 1,
+ },
+ },
+ avatarRail: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ flexShrink: 0,
+ },
+ // AvatarGroupOverflow pads its count for multi-digit pills; inside this
+ // compact pin a short `+N` must stay a circle the size of its sibling
+ // Avatars, while longer counts still grow from the shared minimum width.
+ overflowCircle: {
+ paddingInline: 0,
+ },
+ count: {
+ display: 'inline-block',
+ minWidth: spacingVars['--spacing-3'],
+ color: 'inherit',
+ fontVariantNumeric: 'tabular-nums',
+ textAlign: 'center',
+ },
+ unreadBadge: {
+ // Native buttons remap colors under forced colors; author the full pair.
+ forcedColorAdjust: 'none',
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ boxSizing: 'border-box',
+ minWidth: spacingVars['--spacing-5'],
+ height: spacingVars['--spacing-5'],
+ paddingInline: spacingVars['--spacing-1'],
+ borderRadius: radiusVars['--radius-full'],
+ backgroundColor: {
+ default: colorVars['--color-accent'],
+ '@media (forced-colors: active)': 'Highlight',
+ },
+ color: {
+ default: colorVars['--color-on-accent'],
+ '@media (forced-colors: active)': 'HighlightText',
+ },
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: 1,
+ },
+});
+
+function takeDistinctParticipants(
+ participants: readonly CommentPinParticipant[],
+ limit: number,
+): CommentPinParticipant[] {
+ const result: CommentPinParticipant[] = [];
+ const seen = new Set<string>();
+
+ for (const participant of participants) {
+ if (seen.has(participant.id)) {
+ continue;
+ }
+ seen.add(participant.id);
+ result.push(participant);
+ if (result.length === limit) {
+ break;
+ }
+ }
+
+ return result;
+}
+
+function isValidThreadCount(threadCount: number): boolean {
+ return (
+ Number.isFinite(threadCount) &&
+ Number.isInteger(threadCount) &&
+ threadCount >= 1
+ );
+}
+
+function isValidUnreadCount(unreadCount: number): boolean {
+ return (
+ Number.isFinite(unreadCount) &&
+ Number.isInteger(unreadCount) &&
+ unreadCount >= 0
+ );
+}
+
+/** Grouped pins never show more than this many circles, overflow included. */
+const MAX_GROUP_CIRCLES = 3;
+
+/**
+ * Avatar-first annotation anchor for one thread or a caller-defined group.
+ *
+ * The caller owns grouping, representative selection, coordinates, collision
+ * handling, and the content opened by activation. Absolute placement maps the
+ * host anchor to the pin's logical bottom-start corner. The pin only owns its
+ * compact button surface and controlled visual states.
+ *
+ * @example
+ * ```
+ * <CommentPin
+ * label="Open annotation from Ada"
+ * participants={[{id: 'ada', name: 'Ada Lovelace'}]}
+ * onClick={() => openThread('thread-1')}
+ * />
+ * ```
+ *
+ * @example
+ * ```
+ * <CommentPin
+ * label="Open 6 grouped annotations from Ada, Lin, and 3 others, 2 unread"
+ * participants={[ada, lin, mira, noah, sam]}
+ * threadCount={6}
+ * unreadCount={2}
+ * isSelected
+ * onClick={() => openCluster('cluster-1')}
+ * />
+ * ```
+ */
+export function CommentPin({
+ label,
+ participants,
+ threadCount = 1,
+ unreadCount = 0,
+ isSelected = false,
+ isDimmed = false,
+ isResolved = false,
+ isDisabled = false,
+ ref,
+ xstyle,
+ className,
+ style,
+ ...rest
+}: CommentPinProps): React.ReactNode {
+ const validThreadCount = isValidThreadCount(threadCount);
+ const resolvedThreadCount = validThreadCount ? threadCount : 1;
+ const isGrouped = resolvedThreadCount > 1;
+ const validUnreadCount = isValidUnreadCount(unreadCount);
+ const resolvedUnreadCount = validUnreadCount
+ ? Math.min(unreadCount, resolvedThreadCount)
+ : 0;
+ const hasUnread = resolvedUnreadCount > 0;
+
+ // Grouped pins cap at MAX_GROUP_CIRCLES circles: every distinct participant
+ // when they fit, otherwise one fewer Avatar plus a `+N` overflow circle.
+ const distinctParticipants = takeDistinctParticipants(
+ participants,
+ isGrouped ? Number.POSITIVE_INFINITY : 1,
+ );
+ const hasOverflow =
+ isGrouped && distinctParticipants.length > MAX_GROUP_CIRCLES;
+ const visibleParticipants = hasOverflow
+ ? distinctParticipants.slice(0, MAX_GROUP_CIRCLES - 1)
+ : distinctParticipants;
+ const overflowCount =
+ distinctParticipants.length - visibleParticipants.length;
+
+ useDevWarning(
+ 'CommentPin',
+ '`participants` should contain at least one participant. Pass the lead participant for a single thread or every distinct participant for a group.',
+ participants.length === 0,
+ );
+ useDevWarning(
+ 'CommentPin',
+ '`threadCount` must be a finite positive integer. Invalid values fall back to 1.',
+ !validThreadCount,
+ );
+ useDevWarning(
+ 'CommentPin',
+ '`unreadCount` must be a finite non-negative integer no greater than `threadCount`. Invalid values are ignored and larger values are capped.',
+ !validUnreadCount || unreadCount > resolvedThreadCount,
+ );
+ useDevWarning(
+ 'CommentPin',
+ '`label` must be a non-empty accessible action name.',
+ label.trim() === '',
+ );
+
+ const pressFeedback = usePressFeedback();
+ const hasTooltip = !isDisabled && label.trim() !== '';
+ const tooltip = useTooltip({
+ placement: 'above',
+ isEnabled: hasTooltip,
+ });
+ const mergedRef = useMergedRefs(ref, hasTooltip ? tooltip.ref : undefined);
+
+ const avatarParticipants =
+ visibleParticipants.length > 0
+ ? visibleParticipants
+ : [{id: '__anonymous__', name: '', avatarSrc: undefined}];
+
+ const marker = (
+ <button
+ {...rest}
+ {...pressFeedback}
+ ref={mergedRef}
+ type="button"
+ aria-label={label}
+ aria-pressed={isSelected}
+ disabled={isDisabled}
+ {...mergeProps(
+ themeProps('comment-pin', {
+ grouped: isGrouped ? 'grouped' : null,
+ unread: hasUnread ? 'unread' : null,
+ selected: isSelected ? 'selected' : null,
+ dimmed: isDimmed ? 'dimmed' : null,
+ resolved: isResolved ? 'resolved' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ }),
+ focusOutlineProps.focusVisible(
+ styles.root,
+ interactionOverlayStyles.backgroundImage,
+ (isGrouped || hasUnread) && styles.withCount,
+ isResolved && !isSelected && styles.resolved,
+ isDimmed && !isSelected && styles.dimmed,
+ isSelected && styles.selected,
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ <span aria-hidden="true" {...stylex.props(styles.avatarRail)}>
+ {isGrouped ? (
+ <AvatarGroup size="xsm">
+ {avatarParticipants.map(participant => (
+ <Avatar
+ key={participant.id}
+ name={participant.name}
+ src={participant.avatarSrc}
+ tooltip={false}
+ />
+ ))}
+ {overflowCount > 0 ? (
+ <AvatarGroupOverflow
+ count={overflowCount}
+ xstyle={styles.overflowCircle}
+ />
+ ) : null}
+ </AvatarGroup>
+ ) : (
+ avatarParticipants.map(participant => (
+ <Avatar
+ key={participant.id}
+ name={participant.name}
+ src={participant.avatarSrc}
+ size="xsm"
+ tooltip={false}
+ />
+ ))
+ )}
+ </span>
+ {hasUnread ? (
+ <span aria-hidden="true" {...stylex.props(styles.unreadBadge)}>
+ {resolvedUnreadCount}
+ </span>
+ ) : isGrouped ? (
+ <span aria-hidden="true" {...stylex.props(styles.count)}>
+ {resolvedThreadCount}
+ </span>
+ ) : null}
+ </button>
+ );
+
+ return (
+ <>
+ {marker}
+ {hasTooltip ? tooltip.renderTooltip(label) : null}
+ </>
+ );
+}
+
+CommentPin.displayName = 'CommentPin';
diff --git a/packages/lab/src/CommentPin/index.ts b/packages/lab/src/CommentPin/index.ts
new file mode 100644
index 0000000000..fb0ce9193b
--- /dev/null
+++ b/packages/lab/src/CommentPin/index.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input CommentPin implementation and public types
+ * @output CommentPin module exports
+ * @position Public Lab subpath; re-exported by packages/lab/src/index.ts
+ */
+
+export {CommentPin} from './CommentPin';
+export type {CommentPinParticipant, CommentPinProps} from './CommentPin';
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 1ea9ccd089..d5610c41f1 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -33,6 +33,13 @@ export {
type EmojiCategory,
} from './EmojiPicker';
+// CommentPin — avatar-first anchor for one or grouped annotation threads
+export {
+ CommentPin,
+ type CommentPinParticipant,
+ type CommentPinProps,
+} from './CommentPin';
+
// TransferList — controlled dual-panel collection input
export {
TransferList,