Skip to content

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

TypeScript

feat(Item): add XDSItem component (#2259)

Andrey Goder2cebc3e3a61b
diff --git a/apps/storybook/stories/Item.stories.tsx b/apps/storybook/stories/Item.stories.tsx
new file mode 100644
index 0000000000..d480f6ebe0
--- /dev/null
+++ b/apps/storybook/stories/Item.stories.tsx
@@ -0,0 +1,252 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSItem} from '@xds/core/Item';
+import {XDSAvatar} from '@xds/core/Avatar';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSIcon} from '@xds/core/Icon';
+import {XDSText} from '@xds/core/Text';
+import {XDSStack} from '@xds/core/Layout';
+
+const storyStyles = stylex.create({
+ iconCircle: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: 40,
+ height: 40,
+ borderRadius: '50%',
+ backgroundColor: 'var(--color-neutral)',
+ },
+});
+import {
+ UserIcon,
+ Cog6ToothIcon,
+ DocumentIcon,
+ PencilSquareIcon,
+ BellIcon,
+ ChatBubbleLeftIcon,
+ MagnifyingGlassIcon,
+} from '@heroicons/react/24/outline';
+
+const meta: Meta<typeof XDSItem> = {
+ title: 'Core/Item',
+ component: XDSItem,
+ tags: ['autodocs'],
+ argTypes: {
+ align: {control: 'select', options: ['center', 'start']},
+ density: {control: 'select', options: ['default', 'compact']},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSItem>;
+
+/** Basic item with all slots populated. */
+export const Default: Story = {
+ render: () => (
+ <XDSItem
+ media={<XDSIcon icon={UserIcon} size="sm" />}
+ label="Alice Johnson"
+ description="Software Engineer"
+ trailing={<XDSBadge label="Admin" />}
+ />
+ ),
+};
+
+/** Contact list with avatars and roles. */
+export const ContactList: Story = {
+ render: () => (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSAvatar name="Alice Johnson" size={40} />}
+ label="Alice Johnson"
+ description="Engineering Lead"
+ trailing={<XDSBadge label="Admin" />}
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSAvatar name="Bob Smith" size={40} />}
+ label="Bob Smith"
+ description="Product Designer"
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSAvatar name="Carol Williams" size={40} />}
+ label="Carol Williams"
+ description="Data Scientist"
+ trailing={<XDSText color="secondary">Away</XDSText>}
+ onClick={() => {}}
+ />
+ </XDSStack>
+ ),
+};
+
+/** Notification inbox with timestamps and truncation. */
+export const Notifications: Story = {
+ render: () => (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSAvatar name="Alice" size={40} />}
+ label={
+ <>
+ <b>Alice</b> commented on your PR
+ </>
+ }
+ description="Looks good, one nit on the error handling..."
+ trailing={<XDSText color="secondary">2h ago</XDSText>}
+ descriptionLines={1}
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={
+ <div {...stylex.props(storyStyles.iconCircle)}>
+ <XDSIcon icon={BellIcon} size="sm" />
+ </div>
+ }
+ label="Build completed successfully"
+ description="Pipeline #4521 — all 42 tests passed"
+ trailing={<XDSText color="secondary">5h ago</XDSText>}
+ descriptionLines={1}
+ onClick={() => {}}
+ />
+ </XDSStack>
+ ),
+};
+
+/** Compact menu items with icons. */
+export const CompactMenu: Story = {
+ render: () => (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSIcon icon={PencilSquareIcon} size="sm" />}
+ label="Edit"
+ density="compact"
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={Cog6ToothIcon} size="sm" />}
+ label="Settings"
+ description="Manage your preferences"
+ density="compact"
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={ChatBubbleLeftIcon} size="sm" />}
+ label="Messages"
+ density="compact"
+ trailing={<XDSBadge label="12" />}
+ onClick={() => {}}
+ />
+ </XDSStack>
+ ),
+};
+
+/** File browser with selection state. */
+export const FileBrowser: Story = {
+ render: function FileBrowserStory() {
+ const [selected, setSelected] = useState<Set<string>>(new Set(['doc1']));
+ const toggle = (id: string) =>
+ setSelected(prev => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+
+ return (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSIcon icon={DocumentIcon} size="sm" />}
+ label="design-spec.pdf"
+ description="Modified 2 hours ago"
+ trailing={<XDSText color="secondary">2.4 MB</XDSText>}
+ isSelected={selected.has('doc1')}
+ onClick={() => toggle('doc1')}
+ />
+ <XDSItem
+ media={<XDSIcon icon={DocumentIcon} size="sm" />}
+ label="architecture-diagram.png"
+ description="Modified yesterday"
+ trailing={<XDSText color="secondary">1.2 MB</XDSText>}
+ isSelected={selected.has('doc2')}
+ onClick={() => toggle('doc2')}
+ />
+ <XDSItem
+ media={<XDSIcon icon={DocumentIcon} size="sm" />}
+ label="meeting-notes.md"
+ description="Modified 3 days ago"
+ trailing={<XDSText color="secondary">48 KB</XDSText>}
+ isSelected={selected.has('doc3')}
+ onClick={() => toggle('doc3')}
+ />
+ </XDSStack>
+ );
+ },
+};
+
+/** Search results with highlighted terms and links. */
+export const SearchResults: Story = {
+ render: () => (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSIcon icon={MagnifyingGlassIcon} size="sm" />}
+ label={
+ <>
+ XDS <b>Button</b> Component
+ </>
+ }
+ description="Primary interactive element for triggering actions..."
+ descriptionLines={1}
+ href="/docs/button"
+ />
+ <XDSItem
+ media={<XDSIcon icon={MagnifyingGlassIcon} size="sm" />}
+ label={
+ <>
+ XDS <b>Button</b>Group
+ </>
+ }
+ description="Groups related buttons into a single connected control..."
+ descriptionLines={1}
+ href="/docs/button-group"
+ />
+ </XDSStack>
+ ),
+};
+
+/** Disabled items. */
+export const Disabled: Story = {
+ render: () => (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSIcon icon={UserIcon} size="sm" />}
+ label="Active item"
+ description="This item is interactive"
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={UserIcon} size="sm" />}
+ label="Disabled item"
+ description="This item cannot be interacted with"
+ onClick={() => {}}
+ isDisabled
+ />
+ </XDSStack>
+ ),
+};
+
+/** Top-aligned layout for multi-line content. */
+export const AlignStart: Story = {
+ render: () => (
+ <XDSItem
+ align="start"
+ media={<XDSAvatar name="Alice" size={40} />}
+ label="Alice Johnson"
+ description="This is a longer description that wraps across multiple lines to demonstrate the align=start behavior, which positions the media and trailing content at the top rather than vertically centering them."
+ trailing={<XDSText color="secondary">Just now</XDSText>}
+ />
+ ),
+};
diff --git a/packages/cli/templates/blocks/components/Item/ItemShowcase.doc.mjs b/packages/cli/templates/blocks/components/Item/ItemShowcase.doc.mjs
new file mode 100644
index 0000000000..a5382fa27a
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Item/ItemShowcase.doc.mjs
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Item',
+ name: 'Item',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ isShowcase: true,
+ componentsUsed: ['Item', 'Avatar', 'Badge', 'Icon', 'Text', 'Layout'],
+};
diff --git a/packages/cli/templates/blocks/components/Item/ItemShowcase.tsx b/packages/cli/templates/blocks/components/Item/ItemShowcase.tsx
new file mode 100644
index 0000000000..de07ca6614
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Item/ItemShowcase.tsx
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {XDSItem} from '@xds/core/Item';
+import {XDSAvatar} from '@xds/core/Avatar';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSIcon} from '@xds/core/Icon';
+import {XDSText} from '@xds/core/Text';
+import {XDSStack} from '@xds/core/Layout';
+import {UserIcon, DocumentIcon, BellIcon} from '@heroicons/react/24/outline';
+
+export default function ItemShowcase() {
+ return (
+ <XDSStack gap={0}>
+ <XDSItem
+ media={<XDSAvatar name="Alice Johnson" size={40} />}
+ label="Alice Johnson"
+ description="Engineering Lead"
+ trailing={<XDSBadge label="Admin" />}
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={BellIcon} size="sm" />}
+ label="Build completed successfully"
+ description="Pipeline #4521 — all 42 tests passed"
+ trailing={<XDSText color="secondary">5h ago</XDSText>}
+ descriptionLines={1}
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={DocumentIcon} size="sm" />}
+ label="design-spec.pdf"
+ description="Modified 2 hours ago"
+ trailing={<XDSText color="secondary">2.4 MB</XDSText>}
+ isSelected
+ onClick={() => {}}
+ />
+ <XDSItem
+ media={<XDSIcon icon={UserIcon} size="sm" />}
+ label="Compact menu item"
+ density="compact"
+ onClick={() => {}}
+ />
+ </XDSStack>
+ );
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index c49ab4d8f2..d0959d9e04 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -307,6 +307,12 @@
"import": "./dist/InputGroup/index.mjs",
"require": "./dist/InputGroup/index.js"
},
+ "./Item": {
+ "source": "./src/Item/index.ts",
+ "types": "./dist/Item/index.d.ts",
+ "import": "./dist/Item/index.mjs",
+ "require": "./dist/Item/index.js"
+ },
"./Kbd": {
"source": "./src/Kbd/index.ts",
"types": "./dist/Kbd/index.d.ts",
diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
index 0643e8b4de..770c82cc8b 100644
--- a/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/XDSDropdownMenuItem.tsx
@@ -10,6 +10,10 @@
* Interactive menu item with role="menuitem". Keyboard navigation
* is handled by useListFocus on the parent menu container.
*
+ * Composes XDSItem for the shared media + label + description + trailing layout.
+ * Passes role="menuitem" so XDSItem puts onClick on the root div instead of
+ * creating an invisible button (keyboard access is provided by the parent menu).
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
* - /packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx
@@ -22,24 +26,22 @@ import {useCallback, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {renderIconSlot, type XDSIconType} from '../Icon';
-import {XDSText} from '../Text';
+import {XDSItem} from '../Item';
import {
colorVars,
spacingVars,
typographyVars,
typeScaleVars,
} from '../theme/tokens.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {xdsClassName} from '../utils';
import {useXDSDropdownMenuContext} from './XDSDropdownMenuContext';
-const styles = stylex.create({
+const menuItemStyles = stylex.create({
root: {
boxSizing: 'border-box',
- display: 'flex',
- alignItems: 'center',
- gap: spacingVars['--spacing-2'],
width: '100%',
- padding: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-2'],
borderRadius: `max(0px, calc(var(--_dropdown-menu-radius, ${spacingVars['--spacing-2']}) - var(--_dropdown-menu-padding, ${spacingVars['--spacing-1']})))`,
fontFamily: typographyVars['--font-family-body'],
fontSize: typeScaleVars['--text-label-size'],
@@ -54,12 +56,6 @@ const styles = stylex.create({
textAlign: 'left',
outline: 'none',
},
- content: {
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minWidth: 0,
- },
disabled: {
opacity: 0.5,
cursor: 'not-allowed',
@@ -144,39 +140,33 @@ export function XDSDropdownMenuItem({
}, [isDisabled, onClick, ctx]);
return (
- <div
+ <XDSItem
role="menuitem"
tabIndex={isDisabled ? undefined : -1}
- aria-disabled={isDisabled || undefined}
+ media={
+ icon
+ ? renderIconSlot(icon, {size: 'sm', color: 'secondary'})
+ : undefined
+ }
+ label={label}
+ description={description}
+ trailing={children}
onClick={handleClick}
- {...mergeProps(
+ isDisabled={isDisabled}
+ xstyle={[
+ menuItemStyles.root,
+ itemSizeStyles[menuSize],
+ isDisabled && menuItemStyles.disabled,
+ xstyle,
+ ]}
+ className={[
xdsClassName('dropdown-menu-item', {size: menuSize}),
- stylex.props(
- styles.root,
- itemSizeStyles[menuSize],
- isDisabled && styles.disabled,
- xstyle,
- ),
className,
- style,
- )}>
- {icon && renderIconSlot(icon, {size: 'sm', color: 'secondary'})}
- <span {...stylex.props(styles.content)}>
- {typeof label === 'string' ? (
- <XDSText type="body" maxLines={1}>
- {label}
- </XDSText>
- ) : (
- label
- )}
- {description && (
- <XDSText type="supporting" maxLines={1}>
- {description}
- </XDSText>
- )}
- </span>
- {children}
- </div>
+ ]
+ .filter(Boolean)
+ .join(' ')}
+ style={style}
+ />
);
}
diff --git a/packages/core/src/Item/Item.doc.mjs b/packages/core/src/Item/Item.doc.mjs
new file mode 100644
index 0000000000..2d66fcf0c6
--- /dev/null
+++ b/packages/core/src/Item/Item.doc.mjs
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'Item',
+ group: 'Item',
+ keywords: ["item","list-item","media-object","row","cell","entity","contact","notification","preview"],
+ playground: {
+ defaults: {
+ label: 'Item label',
+ description: 'Supporting text',
+ },
+ },
+ theming: {
+ targets: [
+ {className: 'xds-item', visualProps: ['density', 'align']},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSItem',
+ description: 'A universal item primitive that unifies the "media + label + description + trailing content" layout pattern. Use as a building block for list items, menu items, contact rows, notifications, and more.',
+ props: [
+ {name: 'label', type: 'ReactNode', description: 'Primary text identifying this item. Accepts string (auto-truncated) or ReactNode (for rich content).', required: true},
+ {name: 'media', type: 'ReactNode', description: 'Leading visual — avatar, icon, image, or any ReactNode.', slotElements: [{__element: 'XDSAvatar', props: {size: 'sm'}}, {__element: 'XDSIcon', props: {icon: 'user', size: 'sm'}}]},
+ {name: 'description', type: 'ReactNode', description: 'Secondary text — subtitle, description, or supporting info.'},
+ {name: 'trailing', type: 'ReactNode', description: 'Trailing content — badges, metadata, timestamps, action buttons. Positioned at the end, flex-shrink: 0.', slotElements: [{__element: 'XDSBadge', props: {label: 3}}, {__element: 'XDSText', props: {color: 'secondary'}, children: '2h ago'}]},
+ {name: 'as', type: "'div' | 'li' | 'span'", description: 'HTML element to render as the root.', default: "'div'"},
+ {name: 'startAdornment', type: 'ReactNode', description: 'Content rendered before the media slot as a direct flex child, without a wrapper element.'},
+ {name: 'align', type: "'center' | 'start'", description: 'Vertical alignment of media and trailing slots.', default: "'center'"},
+ {name: 'density', type: "'default' | 'compact'", description: 'Spacing density. "default" uses 8px block padding, "compact" uses 4px.', default: "'default'"},
+ {name: 'labelLines', type: 'number', description: 'Max lines before label truncates with ellipsis.'},
+ {name: 'descriptionLines', type: 'number', description: 'Max lines before description truncates with ellipsis.'},
+ {name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler. Makes the item clickable with button semantics.'},
+ {name: 'href', type: 'string', description: 'Link URL. Makes the item a link via an invisible anchor element.'},
+ {name: 'target', type: "'_blank' | '_self'", description: 'Link target. Only used with href.'},
+ {name: 'isHighlighted', type: 'boolean', description: 'Highlighted state (hover/keyboard focus appearance).', default: 'false'},
+ {name: 'isSelected', type: 'boolean', description: 'Selected state.', default: 'false'},
+ {name: 'isDisabled', type: 'boolean', description: 'Disabled state.', default: 'false'},
+ {name: 'ref', type: 'React.Ref<HTMLDivElement>', description: 'Ref forwarded to the root element.'},
+ {name: 'xstyle', type: 'StyleXStyles', description: 'StyleX styles for layout customization. Must be a stylex.create() value.'},
+ {name: 'data-testid', type: 'string', description: 'Test selector for automated testing frameworks.'},
+ ],
+ },
+ ],
+ usage: {
+ description:
+ 'A single, flexible item primitive that unifies the "media + label + description + trailing content" pattern across XDS. Use it wherever you need a structured row — dropdown menus, selectors, contact lists, notifications, file browsers, and activity feeds.',
+ bestPractices: [
+ {guidance: true, description: 'Use named slots (media, label, description, trailing) for the common layout. These cover the 80% case.'},
+ {guidance: true, description: 'Use density="compact" for menus and dense lists, "default" for standalone items and spacious layouts.'},
+ {guidance: true, description: 'Set labelLines and descriptionLines to control truncation when content length varies.'},
+ {guidance: true, description: 'Use align="start" when media or trailing content is taller than a single line of text.'},
+ {guidance: false, description: "Don't nest interactive elements (buttons, links) inside an interactive XDSItem — it creates confusing focus and click targets."},
+ {guidance: false, description: "Don't use XDSItem for navigation between views — use proper navigation components instead."},
+ {guidance: false, description: "Don't add read/unread or inbox-specific behavior directly — compose a thin wrapper like XDSPreviewItem instead."},
+ ],
+ anatomy: [
+ {name: 'Media', required: false, description: 'Leading visual — avatar, icon, image, or status indicator.'},
+ {name: 'Label', required: true, description: 'Primary text identifying the item.'},
+ {name: 'Description', required: false, description: 'Secondary supporting text below the label.'},
+ {name: 'Trailing', required: false, description: 'End-aligned content — badges, timestamps, or action buttons.'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsZh = {
+ components: [
+ {
+ name: 'XDSItem',
+ description: '通用项目原语,统一 "媒体 + 标签 + 描述 + 尾部内容" 布局模式。用作列表项、菜单项、联系人行、通知等的构建块。',
+ propDescriptions: {
+ label: '标识此项目的主要文本。接受字符串(自动截断)或 ReactNode(用于富内容)。',
+ media: '前导视觉 — 头像、图标、图片或任何 ReactNode。',
+ description: '次要文本 — 副标题、描述或辅助信息。',
+ trailing: '尾部内容 — 徽章、元数据、时间戳、操作按钮。定位在末端。',
+ as: '根元素的 HTML 元素。',
+ startAdornment: '在媒体插槽之前渲染的内容,作为直接 flex 子元素,无包装元素。',
+ align: '媒体和尾部插槽的垂直对齐方式。',
+ density: '间距密度。"default" 使用 8px 块内距,"compact" 使用 4px。',
+ labelLines: '标签截断前的最大行数。',
+ descriptionLines: '描述截断前的最大行数。',
+ onClick: '点击处理函数。使项目可点击,具有按钮语义。',
+ href: '链接 URL。通过不可见锚点元素使项目成为链接。',
+ target: '链接目标。仅与 href 一起使用。',
+ isHighlighted: '高亮状态(悬停/键盘焦点外观)。',
+ isSelected: '选中状态。',
+ isDisabled: '禁用状态。',
+ ref: '转发到根元素的引用。',
+ xstyle: 'StyleX 样式,用于布局自定义。必须是 stylex.create() 的值。',
+ 'data-testid': '自动化测试的选择器。',
+ },
+ },
+ ],
+ usage: {
+ description:
+ '通用项目原语,统一 XDS 中 "媒体 + 标签 + 描述 + 尾部内容" 的布局模式。适用于下拉菜单、选择器、联系人列表、通知、文件浏览器和活动流等场景。',
+ bestPractices: [
+ {guidance: true, description: '使用命名插槽(media、label、description、trailing)处理常见布局。'},
+ {guidance: true, description: '菜单和密集列表使用 density="compact",独立项目使用 "default"。'},
+ {guidance: true, description: '设置 labelLines 和 descriptionLines 控制内容长度不定时的截断。'},
+ {guidance: true, description: '当媒体或尾部内容高于单行文本时使用 align="start"。'},
+ {guidance: false, description: '不要在交互式 XDSItem 内嵌套交互元素(按钮、链接)。'},
+ {guidance: false, description: '不要使用 XDSItem 进行视图间导航 — 使用适当的导航组件。'},
+ {guidance: false, description: '不要直接添加已读/未读行为 — 组合一个薄包装器如 XDSPreviewItem。'},
+ ],
+ anatomy: [
+ {name: '媒体', required: false, description: '前导视觉 — 头像、图标、图片或状态指示器。'},
+ {name: '标签', required: true, description: '标识项目的主要文本。'},
+ {name: '描述', required: false, description: '标签下方的次要辅助文本。'},
+ {name: '尾部', required: false, description: '末端对齐内容 — 徽章、时间戳或操作按钮。'},
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsDense = {
+ description: 'universal item primitive w/ media+label+description+trailing layout. building block for list items, menu items, contacts, notifications',
+ usage: {
+ description:
+ 'Flexible item primitive unifying the "media + label + description + trailing" pattern. Use for structured rows in menus, lists, contacts, notifications, file browsers.',
+ bestPractices: [
+ {guidance: true, description: 'Named slots (media, label, description, trailing) for the 80% case.'},
+ {guidance: true, description: 'density="compact" for menus/dense lists, "default" for spacious layouts.'},
+ {guidance: true, description: 'labelLines/descriptionLines for truncation control.'},
+ {guidance: true, description: 'align="start" when media/trailing is taller than one text line.'},
+ {guidance: false, description: "Don't nest interactive elements inside interactive XDSItem."},
+ {guidance: false, description: "Don't use for view navigation — use nav components."},
+ {guidance: false, description: "Don't add inbox-specific behavior — compose a wrapper."},
+ ],
+ },
+ components: [
+ {
+ name: 'XDSItem',
+ description: 'universal item primitive w/ media+label+description+trailing layout',
+ propDescriptions: {
+ label: 'Primary text. String auto-truncates; ReactNode for rich content.',
+ media: 'Leading visual — avatar, icon, image, ReactNode.',
+ description: 'Secondary text below label.',
+ trailing: 'End-aligned content — badges, timestamps, actions.',
+ as: 'Root HTML element.',
+ startAdornment: 'Content before media slot as direct flex child, no wrapper.',
+ align: 'Vertical alignment of media/trailing slots.',
+ density: 'Spacing: "default" (8px) or "compact" (4px).',
+ labelLines: 'Max label lines before truncation.',
+ descriptionLines: 'Max description lines before truncation.',
+ onClick: 'Click handler; enables button semantics.',
+ href: 'Link URL; enables anchor semantics.',
+ target: 'Link target, only with href.',
+ isHighlighted: 'Highlighted state.',
+ isSelected: 'Selected state.',
+ isDisabled: 'Disabled state.',
+ xstyle: 'StyleX layout styles; must be stylex.create() value.',
+ 'data-testid': 'Test selector.',
+ },
+ },
+ ],
+};
diff --git a/packages/core/src/Item/XDSItem.test.tsx b/packages/core/src/Item/XDSItem.test.tsx
new file mode 100644
index 0000000000..ea931ecd11
--- /dev/null
+++ b/packages/core/src/Item/XDSItem.test.tsx
@@ -0,0 +1,343 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file XDSItem.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSItem component
+ * @output Unit tests for XDSItem
+ * @position Testing; validates XDSItem component implementation
+ *
+ * SYNC: When XDSItem component changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSItem} from './XDSItem';
+
+describe('XDSItem', () => {
+ // ===========================================================================
+ // Basic rendering
+ // ===========================================================================
+
+ it('renders label text', () => {
+ render(<XDSItem label="Contact Name" />);
+ expect(screen.getByText('Contact Name')).toBeInTheDocument();
+ });
+
+ it('renders label and description', () => {
+ render(<XDSItem label="Settings" description="Manage your preferences" />);
+ expect(screen.getByText('Settings')).toBeInTheDocument();
+ expect(screen.getByText('Manage your preferences')).toBeInTheDocument();
+ });
+
+ it('renders media content', () => {
+ render(
+ <XDSItem label="Item" media={<span data-testid="avatar">A</span>} />,
+ );
+ expect(screen.getByTestId('avatar')).toBeInTheDocument();
+ });
+
+ it('renders trailing content', () => {
+ render(
+ <XDSItem label="Item" trailing={<span data-testid="badge">3</span>} />,
+ );
+ expect(screen.getByTestId('badge')).toBeInTheDocument();
+ });
+
+ it('renders all slots together', () => {
+ render(
+ <XDSItem
+ media={<span data-testid="media">M</span>}
+ label="Label"
+ description="Description"
+ trailing={<span data-testid="trailing">T</span>}
+ />,
+ );
+ expect(screen.getByTestId('media')).toBeInTheDocument();
+ expect(screen.getByText('Label')).toBeInTheDocument();
+ expect(screen.getByText('Description')).toBeInTheDocument();
+ expect(screen.getByTestId('trailing')).toBeInTheDocument();
+ });
+
+ it('supports data-testid', () => {
+ render(<XDSItem label="Item" data-testid="my-item" />);
+ expect(screen.getByTestId('my-item')).toBeInTheDocument();
+ });
+
+ it('renders as a div element', () => {
+ const {container} = render(<XDSItem label="Item" />);
+ expect(container.firstChild?.nodeName).toBe('DIV');
+ });
+
+ // ===========================================================================
+ // Ref forwarding
+ // ===========================================================================
+
+ it('forwards ref to the root element', () => {
+ let refValue: HTMLElement | null = null;
+ render(
+ <XDSItem
+ label="Item"
+ ref={el => {
+ refValue = el;
+ }}
+ />,
+ );
+ expect(refValue).toBeInstanceOf(HTMLDivElement);
+ });
+
+ // ===========================================================================
+ // Interactive — onClick (invisible button pattern)
+ // ===========================================================================
+
+ it('renders an invisible button when onClick is provided', () => {
+ const onClick = vi.fn();
+ const {container} = render(<XDSItem label="Clickable" onClick={onClick} />);
+ const button = container.querySelector('button');
+ expect(button).toBeInTheDocument();
+ expect(button?.textContent).toContain('Clickable');
+ });
+
+ it('fires onClick when invisible button is clicked', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(<XDSItem label="Clickable" onClick={onClick} />);
+ await user.click(screen.getByRole('button'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('fires onClick when container area is clicked', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(
+ <XDSItem
+ label="Clickable"
+ onClick={onClick}
+ data-testid="item"
+ media={<span data-testid="media">M</span>}
+ />,
+ );
+ await user.click(screen.getByTestId('media'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not fire item onClick when trailing interactive element is clicked', async () => {
+ const user = userEvent.setup();
+ const itemClick = vi.fn();
+ const buttonClick = vi.fn();
+ render(
+ <XDSItem
+ label="Item"
+ onClick={itemClick}
+ trailing={
+ <button type="button" onClick={buttonClick}>
+ Action
+ </button>
+ }
+ />,
+ );
+ await user.click(screen.getByText('Action'));
+ expect(buttonClick).toHaveBeenCalledTimes(1);
+ expect(itemClick).not.toHaveBeenCalled();
+ });
+
+ it('invisible button is focusable via keyboard', async () => {
+ const user = userEvent.setup();
+ render(<XDSItem label="Focusable" onClick={() => {}} />);
+ await user.tab();
+ expect(screen.getByRole('button')).toHaveFocus();
+ });
+
+ it('invisible button can be activated via keyboard', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(<XDSItem label="Pressable" onClick={onClick} />);
+ await user.tab();
+ await user.keyboard('{Enter}');
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not render nested buttons — only one invisible button', () => {
+ const {container} = render(<XDSItem label="Item" onClick={() => {}} />);
+ const buttons = container.querySelectorAll('div button');
+ expect(buttons).toHaveLength(1);
+ });
+
+ // ===========================================================================
+ // Interactive — href (invisible anchor pattern)
+ // ===========================================================================
+
+ it('renders an invisible anchor when href is provided', () => {
+ const {container} = render(<XDSItem label="Link" href="/docs" />);
+ const anchor = container.querySelector('a');
+ expect(anchor).toBeInTheDocument();
+ expect(anchor).toHaveAttribute('href', '/docs');
+ expect(anchor?.textContent).toContain('Link');
+ });
+
+ it('sets target on anchor when provided', () => {
+ const {container} = render(
+ <XDSItem label="External" href="https://example.com" target="_blank" />,
+ );
+ const anchor = container.querySelector('a');
+ expect(anchor).toHaveAttribute('target', '_blank');
+ });
+
+ it('does not render button or anchor for static items', () => {
+ const {container} = render(<XDSItem label="Static" />);
+ expect(container.querySelector('button')).not.toBeInTheDocument();
+ expect(container.querySelector('a')).not.toBeInTheDocument();
+ });
+
+ // ===========================================================================
+ // Disabled state
+ // ===========================================================================
+
+ it('applies aria-disabled when isDisabled', () => {
+ render(<XDSItem label="Disabled" isDisabled data-testid="item" />);
+ expect(screen.getByTestId('item')).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it('disables the invisible button when isDisabled', () => {
+ const {container} = render(
+ <XDSItem label="Disabled" onClick={() => {}} isDisabled />,
+ );
+ const button = container.querySelector('button');
+ expect(button).toBeDisabled();
+ });
+
+ it('does not fire onClick when disabled item is clicked', async () => {
+ const onClick = vi.fn();
+ render(
+ <XDSItem
+ label="Disabled"
+ onClick={onClick}
+ isDisabled
+ data-testid="item"
+ />,
+ );
+ const item = screen.getByTestId('item');
+ item.dispatchEvent(new MouseEvent('click', {bubbles: true}));
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('does not set aria-disabled when not disabled', () => {
+ render(<XDSItem label="Item" data-testid="item" />);
+ expect(screen.getByTestId('item')).not.toHaveAttribute('aria-disabled');
+ });
+
+ // ===========================================================================
+ // Selected state
+ // ===========================================================================
+
+ it('applies aria-selected when isSelected', () => {
+ render(<XDSItem label="Selected" isSelected data-testid="item" />);
+ expect(screen.getByTestId('item')).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('does not apply aria-selected when not selected', () => {
+ render(<XDSItem label="Not Selected" data-testid="item" />);
+ expect(screen.getByTestId('item')).not.toHaveAttribute('aria-selected');
+ });
+
+ // ===========================================================================
+ // Highlighted state
+ // ===========================================================================
+
+ it('renders with isHighlighted without errors', () => {
+ render(<XDSItem label="Highlighted" isHighlighted data-testid="item" />);
+ expect(screen.getByTestId('item')).toBeInTheDocument();
+ });
+
+ // ===========================================================================
+ // Media and trailing slot positions
+ // ===========================================================================
+
+ it('media and trailing are siblings to invisible button', () => {
+ const {container} = render(
+ <XDSItem
+ label="Item"
+ onClick={() => {}}
+ media={<span data-testid="media">M</span>}
+ trailing={<span data-testid="trailing">T</span>}
+ />,
+ );
+ const button = container.querySelector('button');
+ const root = container.firstElementChild;
+ expect(root?.querySelector('[data-testid="media"]')).toBeInTheDocument();
+ expect(root?.querySelector('[data-testid="trailing"]')).toBeInTheDocument();
+ expect(
+ button?.querySelector('[data-testid="media"]'),
+ ).not.toBeInTheDocument();
+ expect(
+ button?.querySelector('[data-testid="trailing"]'),
+ ).not.toBeInTheDocument();
+ });
+
+ // ===========================================================================
+ // Density variants
+ // ===========================================================================
+
+ it('renders with default density', () => {
+ render(<XDSItem label="Item" data-testid="item" />);
+ expect(screen.getByTestId('item')).toBeInTheDocument();
+ });
+
+ it('renders with compact density', () => {
+ render(<XDSItem label="Item" density="compact" data-testid="item" />);
+ expect(screen.getByTestId('item')).toBeInTheDocument();
+ });
+
+ // ===========================================================================
+ // Alignment
+ // ===========================================================================
+
+ it('renders with center alignment by default', () => {
+ render(<XDSItem label="Item" data-testid="item" />);
+ expect(screen.getByTestId('item')).toBeInTheDocument();
+ });
+
+ it('renders with start alignment', () => {
+ render(<XDSItem label="Item" align="start" data-testid="item" />);
+ expect(screen.getByTestId('item')).toBeInTheDocument();
+ });
+
+ // ===========================================================================
+ // Description rendering
+ // ===========================================================================
+
+ it('does not render description when not provided', () => {
+ render(<XDSItem label="Label Only" />);
+ expect(screen.getByText('Label Only')).toBeInTheDocument();
+ expect(screen.queryByText('undefined')).not.toBeInTheDocument();
+ });
+
+ it('accepts ReactNode as description', () => {
+ render(
+ <XDSItem
+ label="Item"
+ description={
+ <div>
+ <span>Rich</span> <span>description</span>
+ </div>
+ }
+ />,
+ );
+ expect(screen.getByText('Rich')).toBeInTheDocument();
+ expect(screen.getByText('description')).toBeInTheDocument();
+ });
+
+ it('accepts ReactNode as label', () => {
+ render(
+ <XDSItem
+ label={
+ <span>
+ <b>Alice</b> commented
+ </span>
+ }
+ />,
+ );
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ expect(screen.getByText(/commented/)).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/Item/XDSItem.tsx b/packages/core/src/Item/XDSItem.tsx
new file mode 100644
index 0000000000..526e968bc3
--- /dev/null
+++ b/packages/core/src/Item/XDSItem.tsx
@@ -0,0 +1,483 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file XDSItem.tsx
+ * @input Uses React, ReactNode, StyleXStyles, theme tokens
+ * @output Exports XDSItem component, XDSItemProps type
+ * @position Core layout primitive; consumed by index.ts, tested by XDSItem.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Item/Item.doc.mjs
+ * - /packages/core/src/Item/XDSItem.test.tsx
+ * - /packages/core/src/Item/index.ts
+ * - /apps/storybook/stories/Item.stories.tsx
+ * - /packages/cli/templates/blocks/components/Item/ (showcase blocks)
+ */
+
+import type {ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+ durationVars,
+ easeVars,
+ typeScaleVars,
+} from '../theme/tokens.stylex';
+import type {XDSBaseProps} from '../XDSBaseProps';
+import {xdsClassName, mergeProps} from '../utils';
+import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export type XDSItemAlign = 'center' | 'start';
+export type XDSItemDensity = 'default' | 'compact';
+
+export interface XDSItemProps extends XDSBaseProps<HTMLElement> {
+ /** Ref forwarded to the root element. */
+ ref?: React.Ref<HTMLElement>;
+
+ /**
+ * HTML element to render as the root.
+ * @default 'div'
+ */
+ as?: 'div' | 'li' | 'span';
+
+ /**
+ * Content rendered as a direct flex child before the media slot,
+ * without a wrapper element. Use for list markers or other content
+ * that needs its own flex alignment (e.g. alignSelf: 'baseline').
+ */
+ startAdornment?: ReactNode;
+
+ /**
+ * Leading visual — avatar, icon, image, or any ReactNode.
+ */
+ media?: ReactNode;
+
+ /**
+ * Primary text identifying this item. Required.
+ * Accepts string (auto-styled) or ReactNode (for rich content).
+ */
+ label: ReactNode;
+
+ /**
+ * Secondary text — subtitle, description, or supporting info.
+ */
+ description?: ReactNode;
+
+ /**
+ * Trailing content — badges, metadata, timestamps, action buttons.
+ * Positioned at the end, flex-shrink: 0.
+ */
+ trailing?: ReactNode;
+
+ /**
+ * Vertical alignment of the media and trailing slots.
+ * @default 'center'
+ */
+ align?: XDSItemAlign;
+
+ /**
+ * Density: "default" (8px padding) or "compact" (4px block padding).
+ * @default 'default'
+ */
+ density?: XDSItemDensity;
+
+ /**
+ * Max lines before label truncates. When set, overflow is hidden
+ * and text-overflow: ellipsis is applied.
+ */
+ labelLines?: number;
+
+ /**
+ * Max lines before description truncates. When set, overflow is hidden
+ * and text-overflow: ellipsis is applied.
+ */
+ descriptionLines?: number;
+
+ /**
+ * Click handler. Makes the item clickable with button semantics.
+ */
+ onClick?: (event: React.MouseEvent) => void;
+
+ /**
+ * Link URL. Makes the item a link via an invisible anchor element.
+ */
+ href?: string;
+
+ /**
+ * Link target (e.g., '_blank'). Only used with href.
+ */
+ target?: '_blank' | '_self';
+
+ /**
+ * Highlighted state (hover/keyboard focus appearance).
+ * @default false
+ */
+ isHighlighted?: boolean;
+
+ /**
+ * Selected state.
+ * @default false
+ */
+ isSelected?: boolean;
+
+ /**
+ * Disabled state.
+ * @default false
+ */
+ isDisabled?: boolean;
+
+ /**
+ * Test ID for testing frameworks.
+ */
+ 'data-testid'?: string;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ root: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-2'],
+ position: 'relative',
+ boxSizing: 'border-box',
+ textAlign: 'start',
+ borderRadius: radiusVars['--radius-element'],
+ },
+ alignStart: {
+ alignItems: 'flex-start',
+ },
+ interactive: {
+ cursor: 'pointer',
+ transitionProperty: 'background-color',
+ transitionDuration: durationVars['--duration-fast-min'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': {
+ '@media (hover: hover)': colorVars['--color-overlay-hover'],
+ },
+ ':active': colorVars['--color-overlay-pressed'],
+ },
+ },
+ focusVisibleOutline: {
+ outline: {
+ default: 'none',
+ ':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':has(:focus-visible)': '2px',
+ },
+ },
+ highlighted: {
+ backgroundColor: colorVars['--color-overlay-hover'],
+ },
+ selected: {
+ backgroundColor: colorVars['--color-accent-muted'],
+ },
+ disabled: {
+ cursor: 'not-allowed',
+ pointerEvents: 'none' as const,
+ },
+ disabledContent: {
+ opacity: 0.5,
+ },
+ invisibleButton: {
+ all: 'unset',
+ cursor: 'inherit',
+ font: 'inherit',
+ color: 'inherit',
+ display: 'flex',
+ flexDirection: 'column',
+ flex: 1,
+ minWidth: 0,
+ textAlign: 'start',
+ outline: 'none',
+ },
+ invisibleAnchor: {
+ all: 'unset',
+ cursor: 'inherit',
+ font: 'inherit',
+ color: 'inherit',
+ display: 'flex',
+ flexDirection: 'column',
+ flex: 1,
+ minWidth: 0,
+ textAlign: 'start',
+ textDecoration: 'none',
+ outline: 'none',
+ },
+ content: {
+ display: 'flex',
+ flexDirection: 'column',
+ flex: 1,
+ minWidth: 0,
+ textAlign: 'start',
+ },
+ label: {
+ color: colorVars['--color-text-primary'],
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ },
+ labelSingleTruncate: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ labelMultiTruncate: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical' as const,
+ },
+ description: {
+ color: colorVars['--color-text-secondary'],
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ },
+ descriptionSingleTruncate: {
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ descriptionMultiTruncate: {
+ overflow: 'hidden',
+ display: '-webkit-box',
+ WebkitBoxOrient: 'vertical' as const,
+ },
+ media: {
+ flex: '0 0 auto',
+ display: 'flex',
+ },
+ trailing: {
+ flex: '0 0 auto',
+ display: 'flex',
+ marginInlineStart: 'auto',
+ },
+});
+
+const dynamicStyles = stylex.create({
+ lineClamp: (lines: number) => ({
+ WebkitLineClamp: lines,
+ }),
+});
+
+const densityStyles = stylex.create({
+ default: {
+ paddingBlock: spacingVars['--spacing-2'],
+ },
+ compact: {
+ paddingBlock: spacingVars['--spacing-1'],
+ },
+});
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * A universal item primitive that unifies the "media + label + description +
+ * trailing content" layout pattern. Use as a building block for list items,
+ * menu items, contact rows, notification items, and more.
+ *
+ * @example
+ * ```
+ * <XDSItem
+ * media={<XDSAvatar src={user.avatar} size="sm" />}
+ * label={user.name}
+ * description={user.role}
+ * trailing={<XDSBadge>Admin</XDSBadge>}
+ * onClick={() => navigate(`/users/${user.id}`)}
+ * />
+ * ```
+ */
+export function XDSItem({
+ as: Component = 'div',
+ startAdornment,
+ media,
+ label,
+ description,
+ trailing,
+ align = 'center',
+ density = 'default',
+ labelLines,
+ descriptionLines,
+ onClick,
+ href,
+ target,
+ isHighlighted = false,
+ isSelected = false,
+ isDisabled = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ role,
+ ...restProps
+}: XDSItemProps) {
+ const LinkComponent = useXDSLinkComponent();
+ const isInteractive = onClick != null || href != null;
+ // When a semantic role is provided (e.g. "menuitem"), a parent component
+ // handles keyboard access. Skip the invisible button/anchor and put
+ // onClick directly on the root element instead.
+ const hasParentRole = role != null;
+
+ const isStringLabel = typeof label === 'string';
+ const isStringDescription = typeof description === 'string';
+
+ const labelTruncateStyle =
+ labelLines != null
+ ? labelLines === 1
+ ? styles.labelSingleTruncate
+ : styles.labelMultiTruncate
+ : isStringLabel
+ ? styles.labelSingleTruncate
+ : null;
+
+ const descriptionTruncateStyle =
+ descriptionLines != null
+ ? descriptionLines === 1
+ ? styles.descriptionSingleTruncate
+ : styles.descriptionMultiTruncate
+ : isStringDescription
+ ? styles.descriptionSingleTruncate
+ : null;
+
+ const labelAndDescription = (
+ <>
+ <span
+ {...stylex.props(
+ styles.label,
+ labelTruncateStyle,
+ labelLines != null &&
+ labelLines > 1 &&
+ dynamicStyles.lineClamp(labelLines),
+ )}>
+ {label}
+ </span>
+ {description != null && (
+ <span
+ {...stylex.props(
+ styles.description,
+ descriptionTruncateStyle,
+ descriptionLines != null &&
+ descriptionLines > 1 &&
+ dynamicStyles.lineClamp(descriptionLines),
+ )}>
+ {description}
+ </span>
+ )}
+ </>
+ );
+
+ const handleContainerClick = (e: React.MouseEvent) => {
+ if (isDisabled) {return;}
+ const target = e.target as HTMLElement;
+ if (target.closest('button, a, input, select, textarea')) {return;}
+ onClick?.(e);
+ };
+
+ const innerContent = (
+ <>
+ {startAdornment}
+ {media != null && <span {...stylex.props(styles.media)}>{media}</span>}
+
+ {hasParentRole ? (
+ <span
+ {...stylex.props(
+ styles.content,
+ isDisabled && styles.disabledContent,
+ )}>
+ {labelAndDescription}
+ </span>
+ ) : href != null ? (
+ <LinkComponent
+ href={href}
+ target={target}
+ aria-disabled={isDisabled || undefined}
+ tabIndex={isDisabled ? -1 : undefined}
+ {...stylex.props(
+ styles.invisibleAnchor,
+ isDisabled && styles.disabledContent,
+ )}>
+ {labelAndDescription}
+ </LinkComponent>
+ ) : onClick != null ? (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={isDisabled}
+ {...stylex.props(
+ styles.invisibleButton,
+ isDisabled && styles.disabledContent,
+ )}>
+ {labelAndDescription}
+ </button>
+ ) : (
+ <span
+ {...stylex.props(
+ styles.content,
+ isDisabled && styles.disabledContent,
+ )}>
+ {labelAndDescription}
+ </span>
+ )}
+
+ {trailing != null && (
+ <span
+ {...stylex.props(
+ styles.trailing,
+ isDisabled && styles.disabledContent,
+ )}>
+ {trailing}
+ </span>
+ )}
+ </>
+ );
+
+ return (
+ <Component
+ ref={ref as React.Ref<never>}
+ aria-selected={isSelected || undefined}
+ aria-disabled={isDisabled || undefined}
+ {...restProps}
+ {...mergeProps(
+ xdsClassName('item', {density, align}),
+ stylex.props(
+ styles.root,
+ densityStyles[density],
+ align === 'start' && styles.alignStart,
+ isInteractive && styles.interactive,
+ isInteractive && styles.focusVisibleOutline,
+ isHighlighted && styles.highlighted,
+ isSelected && styles.selected,
+ isDisabled && !hasParentRole && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ role={role}
+ onClick={
+ hasParentRole
+ ? onClick
+ : isInteractive
+ ? handleContainerClick
+ : undefined
+ }>
+ {innerContent}
+ </Component>
+ );
+}
+
+XDSItem.displayName = 'XDSItem';
diff --git a/packages/core/src/Item/index.ts b/packages/core/src/Item/index.ts
new file mode 100644
index 0000000000..477859fef5
--- /dev/null
+++ b/packages/core/src/Item/index.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input Imports from XDSItem.tsx
+ * @output Exports XDSItem component and types
+ * @position Component entry point; re-exported by /packages/core/src/index.ts
+ */
+
+export {XDSItem} from './XDSItem';
+export type {XDSItemProps, XDSItemAlign, XDSItemDensity} from './XDSItem';
diff --git a/packages/core/src/List/XDSList.test.tsx b/packages/core/src/List/XDSList.test.tsx
index d1146521a2..52b1badb0b 100644
--- a/packages/core/src/List/XDSList.test.tsx
+++ b/packages/core/src/List/XDSList.test.tsx
@@ -438,8 +438,8 @@ describe('XDSList', () => {
<XDSListItem label="Disabled" isDisabled />
</XDSList>,
);
- const li = container.querySelector('li');
- expect(li).toHaveAttribute('aria-disabled', 'true');
+ const item = container.querySelector('.xds-item');
+ expect(item).toHaveAttribute('aria-disabled', 'true');
});
it('disables the invisible button when isDisabled', () => {
@@ -476,8 +476,8 @@ describe('XDSList', () => {
<XDSListItem label="Selected" isSelected onClick={() => {}} />
</XDSList>,
);
- const li = container.querySelector('li');
- expect(li).toHaveAttribute('aria-selected', 'true');
+ const item = container.querySelector('.xds-item');
+ expect(item).toHaveAttribute('aria-selected', 'true');
});
it('does not apply aria-selected when not selected', () => {
diff --git a/packages/core/src/List/XDSListItem.tsx b/packages/core/src/List/XDSListItem.tsx
index ca2d052b3a..9be4f8963c 100644
--- a/packages/core/src/List/XDSListItem.tsx
+++ b/packages/core/src/List/XDSListItem.tsx
@@ -8,6 +8,9 @@
* @output Exports XDSListItem component, XDSListItemProps type
* @position Core implementation; consumed by XDSList, index.ts, tested by XDSList.test.tsx
*
+ * Composes XDSItem for the shared media + label + description + trailing layout
+ * and the invisible button/anchor interactive pattern.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/List/List.doc.mjs
* - /packages/core/src/List/XDSList.test.tsx
@@ -20,17 +23,14 @@ import {use, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
- radiusVars,
spacingVars,
- durationVars,
- easeVars,
typeScaleVars,
borderVars,
} from '../theme/tokens.stylex';
import type {XDSBaseProps} from '../XDSBaseProps';
import {XDSListContext} from './XDSListContext';
-import {xdsClassName, mergeProps} from '../utils';
-import {useXDSLinkComponent} from '../Link/useXDSLinkComponent';
+import {xdsClassName} from '../utils';
+import {XDSItem} from '../Item';
// =============================================================================
// Types
@@ -103,28 +103,9 @@ export interface XDSListItemProps extends XDSBaseProps<HTMLLIElement> {
// =============================================================================
const styles = stylex.create({
- // <li> is always a flex container — markers are rendered as custom
- // components rather than native list-style (avoids cross-browser issues
- // with display:list-item + list-style-position:inside on mobile Safari).
- item: {
- display: 'flex',
- alignItems: 'center',
- gap: spacingVars['--spacing-2'],
- paddingInline: spacingVars['--spacing-2'],
- position: 'relative',
- boxSizing: 'border-box',
- textAlign: 'start',
- },
- // When markers are active, bump the CSS counter
withCounter: {
counterIncrement: 'xds-list',
},
- withRadius: {
- borderRadius: radiusVars['--radius-element'],
- },
- noRadius: {
- borderRadius: 0,
- },
withDivider: {
borderBlockEndWidth: borderVars['--border-width'],
borderBlockEndStyle: 'solid',
@@ -133,120 +114,6 @@ const styles = stylex.create({
borderBlockEnd: 'none',
},
},
- interactive: {
- cursor: 'pointer',
- transitionProperty: 'background-color',
- transitionDuration: durationVars['--duration-fast-min'],
- transitionTimingFunction: easeVars['--ease-standard'],
- backgroundColor: {
- default: 'transparent',
- ':hover': {
- '@media (hover: hover)': colorVars['--color-overlay-hover'],
- },
- ':active': colorVars['--color-overlay-pressed'],
- },
- },
- focusVisibleOutline: {
- outline: {
- default: 'none',
- ':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':has(:focus-visible)': '2px',
- },
- },
- disabled: {
- cursor: 'not-allowed',
- pointerEvents: 'none' as const,
- },
- disabledContent: {
- opacity: 0.5,
- },
- selected: {
- backgroundColor: colorVars['--color-accent-muted'],
- },
- invisibleButton: {
- all: 'unset',
- cursor: 'inherit',
- font: 'inherit',
- color: 'inherit',
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minWidth: 0,
- textAlign: 'start',
- // Suppress inner focus ring — the parent <li> handles it via :has(:focus-visible)
- outline: 'none',
- },
- invisibleAnchor: {
- all: 'unset',
- cursor: 'inherit',
- font: 'inherit',
- color: 'inherit',
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minWidth: 0,
- textAlign: 'start',
- textDecoration: 'none',
- // Suppress inner focus ring — the parent <li> handles it via :has(:focus-visible)
- outline: 'none',
- },
- content: {
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minWidth: 0,
- textAlign: 'start',
- },
- label: {
- color: colorVars['--color-text-primary'],
- },
- labelTruncate: {
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- },
- description: {
- color: colorVars['--color-text-secondary'],
- overflow: 'hidden',
- minWidth: 0,
- },
- descriptionString: {
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- },
- startContent: {
- flexShrink: 0,
- display: 'flex',
- alignItems: 'center',
- },
- endContent: {
- flexShrink: 0,
- display: 'flex',
- alignItems: 'center',
- marginInlineStart: 'auto',
- },
-});
-
-const densityStyles = stylex.create({
- compact: {
- paddingBlock: spacingVars['--spacing-1'],
- fontSize: typeScaleVars['--text-body-size'],
- lineHeight: typeScaleVars['--text-body-leading'],
- },
- balanced: {
- paddingBlock: spacingVars['--spacing-2'],
- fontSize: typeScaleVars['--text-body-size'],
- lineHeight: typeScaleVars['--text-body-leading'],
- },
- spacious: {
- paddingBlock: spacingVars['--spacing-3'],
- paddingInline: spacingVars['--spacing-3'],
- fontSize: typeScaleVars['--text-body-size'],
- lineHeight: typeScaleVars['--text-body-leading'],
- },
});
// =============================================================================
@@ -265,8 +132,6 @@ const markerStyles = stylex.create({
justifyContent: 'center',
flexShrink: 0,
width: spacingVars['--spacing-4'],
- // Vertically center the dot/circle with the first line of text:
- // shift down by (lineHeight - dotSize) / 2
marginTop: `calc((1em * ${typeScaleVars['--text-body-leading']} - ${MARKER_DOT_SIZE}px) / 2)`,
},
dot: {
@@ -297,18 +162,9 @@ const markerStyles = stylex.create({
},
});
-const descriptionSizeStyles = stylex.create({
- compact: {
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
- },
- balanced: {
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
- },
- spacious: {
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
+const embeddedStyles = stylex.create({
+ noRadius: {
+ borderRadius: 0,
},
});
@@ -347,97 +203,10 @@ export function XDSListItem({
...restProps
}: XDSListItemProps) {
const ctx = use(XDSListContext);
- const LinkComponent = useXDSLinkComponent();
const density = ctx?.density ?? 'balanced';
const hasDividers = ctx?.hasDividers ?? false;
const listStyle = ctx?.listStyle ?? 'none';
const hasMarkers = listStyle !== 'none';
- const isInteractive = onClick != null || href != null;
-
- const isStringLabel = typeof label === 'string';
- const isStringDescription = typeof description === 'string';
-
- const labelAndDescription = (
- <>
- <span
- {...stylex.props(styles.label, isStringLabel && styles.labelTruncate)}>
- {label}
- </span>
- {description != null && (
- <span
- {...stylex.props(
- styles.description,
- isStringDescription && styles.descriptionString,
- descriptionSizeStyles[density],
- )}>
- {description}
- </span>
- )}
- </>
- );
-
- const handleContainerClick = (e: React.MouseEvent) => {
- if (isDisabled) {
- return;
- }
- const target = e.target as HTMLElement;
- // Don't fire onClick if click originated from an interactive child
- if (target.closest('button, a, input, select, textarea')) {
- return;
- }
- onClick?.(e);
- };
-
- const innerContent = (
- <>
- {startContent != null && (
- <span {...stylex.props(styles.startContent)}>{startContent}</span>
- )}
-
- {href != null ? (
- <LinkComponent
- href={href}
- target={target}
- aria-disabled={isDisabled || undefined}
- tabIndex={isDisabled ? -1 : undefined}
- {...stylex.props(
- styles.invisibleAnchor,
- isDisabled && styles.disabledContent,
- )}>
- {labelAndDescription}
- </LinkComponent>
- ) : onClick != null ? (
- <button
- type="button"
- onClick={onClick}
- disabled={isDisabled}
- {...stylex.props(
- styles.invisibleButton,
- isDisabled && styles.disabledContent,
- )}>
- {labelAndDescription}
- </button>
- ) : (
- <span
- {...stylex.props(
- styles.content,
- isDisabled && styles.disabledContent,
- )}>
- {labelAndDescription}
- </span>
- )}
-
- {endContent != null && (
- <span
- {...stylex.props(
- styles.endContent,
- isDisabled && styles.disabledContent,
- )}>
- {endContent}
- </span>
- )}
- </>
- );
const marker =
listStyle === 'disc' ? (
@@ -452,33 +221,35 @@ export function XDSListItem({
<span {...stylex.props(markerStyles.number)} />
) : null;
+ const itemDensity = density === 'compact' ? 'compact' : 'default';
+
return (
- <li
+ <XDSItem
+ as="li"
ref={ref}
- aria-selected={isSelected || undefined}
- aria-disabled={isDisabled || undefined}
+ startAdornment={marker}
+ media={startContent}
+ label={label}
+ description={description}
+ trailing={endContent}
+ onClick={onClick}
+ href={href}
+ target={target as '_blank' | '_self'}
+ isDisabled={isDisabled}
+ isSelected={isSelected}
+ density={itemDensity}
+ xstyle={[
+ hasMarkers && styles.withCounter,
+ hasDividers && styles.withDivider,
+ hasDividers && embeddedStyles.noRadius,
+ xstyle,
+ ]}
+ className={[xdsClassName('list-item'), className]
+ .filter(Boolean)
+ .join(' ')}
+ style={style}
{...restProps}
- {...mergeProps(
- xdsClassName('list-item'),
- stylex.props(
- styles.item,
- hasMarkers && styles.withCounter,
- densityStyles[density],
- hasDividers ? styles.noRadius : styles.withRadius,
- hasDividers && styles.withDivider,
- isInteractive && styles.interactive,
- isInteractive && styles.focusVisibleOutline,
- isDisabled && styles.disabled,
- isSelected && styles.selected,
- xstyle,
- ),
- className,
- style,
- )}
- onClick={isInteractive ? handleContainerClick : undefined}>
- {marker}
- {innerContent}
- </li>
+ />
);
}
diff --git a/packages/core/src/RadioList/XDSRadioListItem.tsx b/packages/core/src/RadioList/XDSRadioListItem.tsx
index 908966bd5b..1913bd2a8a 100644
--- a/packages/core/src/RadioList/XDSRadioListItem.tsx
+++ b/packages/core/src/RadioList/XDSRadioListItem.tsx
@@ -8,6 +8,8 @@
* @output Exports XDSRadioListItem component, XDSRadioListItemProps
* @position Core implementation; consumed by index.ts, tested by XDSRadioList.test.tsx
*
+ * Composes XDSItem for the shared media + label + description + trailing layout.
+ *
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/RadioList/RadioList.doc.mjs
* - /packages/core/src/RadioList/XDSRadioList.test.tsx
@@ -24,14 +26,12 @@ import {
spacingVars,
durationVars,
easeVars,
- typographyVars,
- fontWeightVars,
- typeScaleVars,
borderVars,
} from '../theme/tokens.stylex';
import {XDSRadioListContext} from './XDSRadioList';
import {xdsClassName, mergeProps} from '../utils';
import {radioScope} from './radio.markers.stylex';
+import {XDSItem} from '../Item';
const styles = stylex.create({
container: {
@@ -120,43 +120,12 @@ const styles = stylex.create({
borderRadius: '50%',
backgroundColor: colorVars['--color-on-accent'],
},
- labelWrapper: {
- display: 'flex',
- flexDirection: 'column',
- gap: spacingVars['--spacing-0-5'],
- },
- label: {
- fontFamily: typographyVars['--font-family-body'],
- fontSize: typeScaleVars['--text-label-size'],
- lineHeight: typeScaleVars['--text-label-leading'],
- fontWeight: fontWeightVars['--font-weight-medium'],
- color: colorVars['--color-text-primary'],
- cursor: 'pointer',
- },
labelDisabled: {
color: colorVars['--color-text-disabled'],
cursor: 'not-allowed',
},
- description: {
- fontFamily: typographyVars['--font-family-body'],
- fontSize: typeScaleVars['--text-supporting-size'],
- lineHeight: typeScaleVars['--text-supporting-leading'],
- color: colorVars['--color-text-secondary'],
- },
- startContent: {
- display: 'flex',
- alignItems: 'center',
- flexShrink: 0,
- },
- endContent: {
- display: 'flex',
- alignItems: 'center',
- flexShrink: 0,
- marginInlineStart: 'auto',
- },
});
-// Size styles matching CheckboxInput dimensions
const wrapperSizeStyles = stylex.create({
sm: {
width: 20,
@@ -190,6 +159,16 @@ const dotSizeStyles = stylex.create({
},
});
+const embeddedStyles = stylex.create({
+ root: {
+ paddingBlock: 0,
+ paddingInline: 0,
+ borderRadius: 0,
+ flex: 1,
+ minWidth: 0,
+ },
+});
+
export interface XDSRadioListItemProps extends XDSBaseProps<HTMLDivElement> {
/**
* Label text for the radio item.
@@ -251,79 +230,91 @@ export function XDSRadioListItem({
const isChecked = context.value === value;
const size = context.size;
- return (
+ const radioCircle = (
<div
- data-testid={dataTestId}
- {...mergeProps(
- xdsClassName('radio-list-item'),
- stylex.props(styles.container, !isDisabled && radioScope),
+ {...stylex.props(
+ styles.radioWrapper,
+ wrapperSizeStyles[size],
+ !isDisabled && styles.radioWrapperFocus,
)}>
- <div
+ <input
+ id={id}
+ type="radio"
+ name={context.name}
+ value={value}
+ checked={isChecked}
+ disabled={isDisabled}
+ required={context.isRequired}
+ onChange={() => context.onChange(value)}
+ aria-describedby={description ? descriptionID : undefined}
{...stylex.props(
- styles.radioWrapper,
+ styles.input,
wrapperSizeStyles[size],
- !isDisabled && styles.radioWrapperFocus,
+ isDisabled && styles.inputDisabled,
+ )}
+ />
+ <div
+ aria-hidden="true"
+ {...mergeProps(
+ xdsClassName('radio', {
+ size,
+ checked: isChecked ? 'checked' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ }),
+ stylex.props(
+ styles.radio,
+ radioSizeStyles[size],
+ isChecked ? styles.radioChecked : styles.radioUnchecked,
+ isDisabled && styles.radioDisabled,
+ isDisabled && !isChecked && styles.radioDisabledUnchecked,
+ ),
)}>
- <input
- id={id}
- type="radio"
- name={context.name}
- value={value}
- checked={isChecked}
- disabled={isDisabled}
- required={context.isRequired}
- onChange={() => context.onChange(value)}
- aria-describedby={description ? descriptionID : undefined}
- {...stylex.props(
- styles.input,
- wrapperSizeStyles[size],
- isDisabled && styles.inputDisabled,
- )}
- />
- <div
- aria-hidden="true"
- {...mergeProps(
- xdsClassName('radio', {
- size,
- checked: isChecked ? 'checked' : null,
- disabled: isDisabled ? 'disabled' : null,
- }),
- stylex.props(
- styles.radio,
- radioSizeStyles[size],
- isChecked ? styles.radioChecked : styles.radioUnchecked,
- isDisabled && styles.radioDisabled,
- isDisabled && !isChecked && styles.radioDisabledUnchecked,
- ),
- )}>
- {isChecked && (
- <div
- {...mergeProps(
- xdsClassName('radio-dot', {size}),
- stylex.props(styles.innerDot, dotSizeStyles[size]),
- )}
- />
- )}
- </div>
- </div>
- {startContent != null && (
- <div {...stylex.props(styles.startContent)}>{startContent}</div>
- )}
- <div {...stylex.props(styles.labelWrapper)}>
- <label
- htmlFor={id}
- {...stylex.props(styles.label, isDisabled && styles.labelDisabled)}>
- {label}
- </label>
- {description != null && (
- <span id={descriptionID} {...stylex.props(styles.description)}>
- {description}
- </span>
+ {isChecked && (
+ <div
+ {...mergeProps(
+ xdsClassName('radio-dot', {size}),
+ stylex.props(styles.innerDot, dotSizeStyles[size]),
+ )}
+ />
)}
</div>
- {endContent != null && (
- <div {...stylex.props(styles.endContent)}>{endContent}</div>
- )}
+ </div>
+ );
+
+ const mediaContent =
+ startContent != null ? (
+ <>
+ {radioCircle}
+ {startContent}
+ </>
+ ) : (
+ radioCircle
+ );
+
+ return (
+ <div
+ data-testid={dataTestId}
+ {...mergeProps(
+ xdsClassName('radio-list-item'),
+ stylex.props(styles.container, !isDisabled && radioScope),
+ )}>
+ <XDSItem
+ media={mediaContent}
+ label={
+ <label
+ htmlFor={id}
+ {...stylex.props(isDisabled && styles.labelDisabled)}>
+ {label}
+ </label>
+ }
+ description={
+ description != null ? (
+ <span id={descriptionID}>{description}</span>
+ ) : undefined
+ }
+ trailing={endContent}
+ xstyle={embeddedStyles.root}
+ />
</div>
);
}
diff --git a/packages/core/src/Selector/XDSSelectorOption.tsx b/packages/core/src/Selector/XDSSelectorOption.tsx
index 845b58cf1d..4f33ffed97 100644
--- a/packages/core/src/Selector/XDSSelectorOption.tsx
+++ b/packages/core/src/Selector/XDSSelectorOption.tsx
@@ -4,29 +4,22 @@
* @file XDSSelectorOption.tsx
* @output Exports XDSSelectorOption component for custom option rendering
* @position Sub-component; used by XDSSelector and consumers for custom options
+ *
+ * Composes XDSItem for the shared media + label + description + trailing layout.
*/
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {renderIconSlot, type XDSIconType} from '../Icon';
-import {XDSText} from '../Text';
-import {spacingVars} from '../theme/tokens.stylex';
-import {xdsClassName, mergeProps} from '../utils';
+import {XDSItem} from '../Item';
+import {xdsClassName} from '../utils';
-const styles = stylex.create({
+const embeddedStyles = stylex.create({
root: {
- display: 'flex',
- alignItems: 'center',
- gap: spacingVars['--spacing-2'],
- flex: 1,
- minWidth: 0,
- },
- content: {
- display: 'flex',
- flexDirection: 'column',
- flex: 1,
- minWidth: 0,
+ paddingBlock: 0,
+ paddingInline: 0,
+ borderRadius: 0,
},
});
@@ -107,30 +100,21 @@ export function XDSSelectorOption({
style,
}: XDSSelectorOptionProps) {
return (
- <span
- {...mergeProps(
- xdsClassName('selector-option'),
- stylex.props(styles.root, xstyle),
- className,
- style,
- )}>
- {icon && renderIconSlot(icon, {size: 'sm', color: 'secondary'})}
- <span {...stylex.props(styles.content)}>
- {typeof label === 'string' ? (
- <XDSText type="body" maxLines={1}>
- {label}
- </XDSText>
- ) : (
- label
- )}
- {description && (
- <XDSText type="supporting" maxLines={1}>
- {description}
- </XDSText>
- )}
- </span>
- {children}
- </span>
+ <XDSItem
+ media={
+ icon
+ ? renderIconSlot(icon, {size: 'sm', color: 'secondary'})
+ : undefined
+ }
+ label={label}
+ description={description}
+ trailing={children}
+ xstyle={[embeddedStyles.root, xstyle]}
+ className={[xdsClassName('selector-option'), className]
+ .filter(Boolean)
+ .join(' ')}
+ style={style}
+ />
);
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index bd7251f1b4..59dd0ea3b5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -67,6 +67,7 @@ export * from './Selector';
export * from './MultiSelector';
export * from './Icon';
export * from './InputGroup';
+export * from './Item';
export * from './Text';
export * from './TextInput';
export * from './TabList';