An open source design system that's fully customizable and agent ready
TypeScript
feat: add XDSClickableCard, XDSSelectableCard, and useClickableContainer (#1707)
Cindy Zhangd5cc6433da0b
diff --git a/apps/storybook/stories/ClickableCard.stories.tsx b/apps/storybook/stories/ClickableCard.stories.tsxnew file mode 100644index 0000000000..b5fc9b3ff0--- /dev/null+++ b/apps/storybook/stories/ClickableCard.stories.tsx@@ -0,0 +1,146 @@+import type {Meta, StoryObj} from '@storybook/react';+import {XDSClickableCard} from '@xds/core/ClickableCard';+import {XDSText} from '@xds/core/Text';+import {XDSButton} from '@xds/core/Button';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';++const meta: Meta<typeof XDSClickableCard> = {+ title: 'Card/XDSClickableCard',+ component: XDSClickableCard,+ tags: ['autodocs'],+ argTypes: {+ variant: {+ control: 'select',+ options: [+ 'default', 'transparent', 'muted',+ 'blue', 'cyan', 'gray', 'green', 'orange',+ 'pink', 'purple', 'red', 'teal', 'yellow',+ ],+ },+ },+ parameters: {+ docs: {+ description: {+ component:+ 'An interactive card for navigation or action targets. ' ++ 'Nested interactive elements (buttons, links) work independently — ' ++ "clicking them does NOT trigger the card's onClick or navigation. " ++ 'Uses `useClickableContainer` internally.',+ },+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSClickableCard>;++export const Navigation: Story = {+ name: 'Navigation (href)',+ render: () => (+ <XDSClickableCard label="Settings" href="/settings" width={300}>+ <XDSVStack gap={1}>+ <XDSText type="body" weight="bold">Settings</XDSText>+ <XDSText type="supporting" color="secondary">Manage your preferences</XDSText>+ </XDSVStack>+ </XDSClickableCard>+ ),+ parameters: {+ docs: {+ description: {+ story: 'Card with `href` — clicking navigates. Ctrl/Cmd+click opens new tab. Middle-click opens new tab.',+ },+ },+ },+};++export const WithOnClick: Story = {+ name: 'Action (onClick)',+ render: () => (+ <XDSClickableCard label="Open modal" onClick={() => alert('Card clicked!')} width={300}>+ <XDSVStack gap={1}>+ <XDSText type="body" weight="bold">Click me</XDSText>+ <XDSText type="supporting" color="secondary">Opens a modal</XDSText>+ </XDSVStack>+ </XDSClickableCard>+ ),+ parameters: {+ docs: {+ description: {+ story: 'Card with `onClick` — fires the handler when the card surface is clicked.',+ },+ },+ },+};++export const NestedButton: Story = {+ name: 'Nested Interactive Elements',+ render: () => (+ <XDSClickableCard label="Product card" href="/product/123" width={300}>+ <XDSVStack gap={2}>+ <XDSText type="body" weight="bold">Product Name</XDSText>+ <XDSText type="supporting" color="secondary">$29.99</XDSText>+ <XDSButton+ label="Add to cart"+ onClick={() => alert('Added to cart! (card did NOT navigate)')}+ variant="primary"+ />+ </XDSVStack>+ </XDSClickableCard>+ ),+ parameters: {+ docs: {+ description: {+ story:+ 'The key feature: nested buttons/links work independently. ' ++ 'Clicking "Add to cart" fires its own handler without triggering card navigation. ' ++ 'This is handled by `useClickableContainer` which checks `hasInteractiveAncestor` on each click.',+ },+ },+ },+};++export const Disabled: Story = {+ render: () => (+ <XDSClickableCard label="Disabled card" onClick={() => {}} isDisabled width={300}>+ <XDSVStack gap={1}>+ <XDSText type="body" weight="bold">Disabled</XDSText>+ <XDSText type="supporting" color="secondary">This card cannot be clicked</XDSText>+ </XDSVStack>+ </XDSClickableCard>+ ),+ parameters: {+ docs: {+ description: {+ story: '`isDisabled` suppresses click, hover, focus, and sets `aria-disabled`. `tabIndex` becomes -1.',+ },+ },+ },+};++export const ColorVariants: Story = {+ name: 'Color Variants',+ render: () => {+ const variants = [+ 'default', 'muted', 'transparent',+ 'blue', 'cyan', 'gray', 'green', 'orange',+ 'pink', 'purple', 'red', 'teal', 'yellow',+ ] as const;++ return (+ <XDSHStack gap={3} wrap="wrap">+ {variants.map((v) => (+ <XDSClickableCard key={v} label={v} onClick={() => alert(v)} variant={v} width={140}>+ <XDSText type="body" weight="bold">{v}</XDSText>+ </XDSClickableCard>+ ))}+ </XDSHStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story: 'All color variants — same palette as XDSCard. Color cards have transparent borders.',+ },+ },+ },+};diff --git a/apps/storybook/stories/SelectableCard.stories.tsx b/apps/storybook/stories/SelectableCard.stories.tsxnew file mode 100644index 0000000000..af5da45427--- /dev/null+++ b/apps/storybook/stories/SelectableCard.stories.tsx@@ -0,0 +1,186 @@+import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {XDSSelectableCard} from '@xds/core/SelectableCard';+import {XDSText} from '@xds/core/Text';+import {XDSHStack, XDSVStack} from '@xds/core/Layout';++const meta: Meta<typeof XDSSelectableCard> = {+ title: 'Card/XDSSelectableCard',+ component: XDSSelectableCard,+ tags: ['autodocs'],+ argTypes: {+ variant: {+ control: 'select',+ options: [+ 'default', 'transparent', 'muted',+ 'blue', 'cyan', 'gray', 'green', 'orange',+ 'pink', 'purple', 'red', 'teal', 'yellow',+ ],+ },+ },+ parameters: {+ docs: {+ description: {+ component:+ 'A card that toggles between selected and unselected states. ' ++ 'Shows an accent border when selected. Manage selection state externally — ' ++ 'single value for radio behavior, Set for multi-select.',+ },+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSSelectableCard>;++export const SingleSelect: Story = {+ name: 'Single Select (Radio)',+ render: () => {+ const [selected, setSelected] = useState<string | null>('basic');+ const plans = [+ {id: 'basic', name: 'Basic', price: '$9/mo'},+ {id: 'pro', name: 'Pro', price: '$29/mo'},+ {id: 'enterprise', name: 'Enterprise', price: '$99/mo'},+ ];++ return (+ <XDSHStack gap={3}>+ {plans.map((plan) => (+ <XDSSelectableCard+ key={plan.id}+ label={plan.name}+ isSelected={selected === plan.id}+ onChange={() => setSelected(plan.id)}+ width={200}+ >+ <XDSVStack gap={1}>+ <XDSText type="body" weight="bold">{plan.name}</XDSText>+ <XDSText type="supporting" color="secondary">{plan.price}</XDSText>+ </XDSVStack>+ </XDSSelectableCard>+ ))}+ </XDSHStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story: 'Radio-style selection: track a single selected ID in state. Clicking a card sets it as selected, deselecting the previous.',+ },+ },+ },+};++export const MultiSelect: Story = {+ name: 'Multi-Select (Checkbox)',+ render: () => {+ const [selected, setSelected] = useState(new Set(['react']));+ const filters = [+ {id: 'react', name: 'React'},+ {id: 'vue', name: 'Vue'},+ {id: 'angular', name: 'Angular'},+ {id: 'svelte', name: 'Svelte'},+ ];++ return (+ <XDSHStack gap={3}>+ {filters.map((f) => (+ <XDSSelectableCard+ key={f.id}+ label={f.name}+ isSelected={selected.has(f.id)}+ onChange={(isNow) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (isNow) {+ next.add(f.id);+ } else {+ next.delete(f.id);+ }+ return next;+ });+ }}+ width={150}+ >+ <XDSText type="body" weight="bold">{f.name}</XDSText>+ </XDSSelectableCard>+ ))}+ </XDSHStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story: 'Checkbox-style selection: track selected IDs in a Set. Multiple cards can be selected simultaneously.',+ },+ },+ },+};++export const ColorVariants: Story = {+ name: 'Color Variants',+ render: () => {+ const [selected, setSelected] = useState(new Set(['blue', 'purple']));+ const variants = [+ 'default', 'muted', 'blue', 'cyan', 'gray', 'green',+ 'orange', 'pink', 'purple', 'red', 'teal', 'yellow',+ ] as const;++ return (+ <XDSHStack gap={3} wrap="wrap">+ {variants.map((v) => (+ <XDSSelectableCard+ key={v}+ label={v}+ isSelected={selected.has(v)}+ onChange={(isNow) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (isNow) {+ next.add(v);+ } else {+ next.delete(v);+ }+ return next;+ });+ }}+ variant={v}+ width={140}+ >+ <XDSText type="body" weight="bold">{v}</XDSText>+ </XDSSelectableCard>+ ))}+ </XDSHStack>+ );+ },+ parameters: {+ docs: {+ description: {+ story: 'All color variants with selection. The accent border overlays the variant background.',+ },+ },+ },+};++export const Disabled: Story = {+ render: () => (+ <XDSHStack gap={3}>+ <XDSSelectableCard label="Enabled" isSelected={true} onChange={() => {}} width={200}>+ <XDSText type="body" weight="bold">Selected & Enabled</XDSText>+ </XDSSelectableCard>+ <XDSSelectableCard label="Disabled" isSelected={true} onChange={() => {}} isDisabled width={200}>+ <XDSText type="body" weight="bold">Selected & Disabled</XDSText>+ </XDSSelectableCard>+ <XDSSelectableCard label="Disabled unselected" isSelected={false} onChange={() => {}} isDisabled width={200}>+ <XDSText type="body" weight="bold">Unselected & Disabled</XDSText>+ </XDSSelectableCard>+ </XDSHStack>+ ),+ parameters: {+ docs: {+ description: {+ story: '`isDisabled` suppresses toggle, hover, focus. Accent border remains visible on disabled+selected cards.',+ },+ },+ },+};diff --git a/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.doc.mjs b/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.doc.mjsnew file mode 100644index 0000000000..4bde0236fa--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.doc.mjs@@ -0,0 +1,11 @@+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ name: 'ClickableCard',+ description:+ 'A clickable card that navigates on click. Nested interactive elements work independently.',+ isReady: true,+ isShowcase: true,+ aspectRatio: 1,+ componentsUsed: ['ClickableCard', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.tsx b/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.tsxnew file mode 100644index 0000000000..80babee86a--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/ClickableCardShowcase.tsx@@ -0,0 +1,19 @@+'use client';++import {XDSClickableCard} from '@xds/core/ClickableCard';+import {XDSStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';++export default function ClickableCardShowcase() {+ return (+ <XDSClickableCard label="Settings" href="/settings" width={320}>+ <XDSStack direction="vertical" gap={2}>+ <XDSHeading level={4}>Settings</XDSHeading>+ <XDSText type="body" color="secondary">+ Click anywhere on this card to navigate. Nested buttons and links work+ independently.+ </XDSText>+ </XDSStack>+ </XDSClickableCard>+ );+}diff --git a/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.doc.mjs b/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.doc.mjsnew file mode 100644index 0000000000..5f3b933cef--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.doc.mjs@@ -0,0 +1,10 @@+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ name: 'ClickableCardWithNestedButton',+ description:+ 'A product card that navigates on click but has an independent "Add to cart" button inside.',+ isReady: true,+ aspectRatio: 1,+ componentsUsed: ['ClickableCard', 'Button', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.tsx b/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.tsxnew file mode 100644index 0000000000..ef1e824ab5--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.tsx@@ -0,0 +1,22 @@+'use client';++import {XDSClickableCard} from '@xds/core/ClickableCard';+import {XDSStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSButton} from '@xds/core/Button';++export default function ClickableCardWithNestedButton() {+ return (+ <XDSClickableCard label="Product" href="/product/123" width={320}>+ <XDSStack direction="vertical" gap={3}>+ <XDSStack direction="vertical" gap={1}>+ <XDSHeading level={4}>Wireless Headphones</XDSHeading>+ <XDSText type="body" color="secondary">+ $79.99+ </XDSText>+ </XDSStack>+ <XDSButton label="Add to cart" onClick={() => {}} variant="primary" />+ </XDSStack>+ </XDSClickableCard>+ );+}diff --git a/packages/cli/templates/blocks/components/Card/SelectableCardMulti.doc.mjs b/packages/cli/templates/blocks/components/Card/SelectableCardMulti.doc.mjsnew file mode 100644index 0000000000..9f3a85af71--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/SelectableCardMulti.doc.mjs@@ -0,0 +1,10 @@+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ name: 'SelectableCardMulti',+ description:+ 'Multi-select tag picker using color variant selectable cards with color-matched selection borders.',+ isReady: true,+ aspectRatio: 2,+ componentsUsed: ['SelectableCard', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Card/SelectableCardMulti.tsx b/packages/cli/templates/blocks/components/Card/SelectableCardMulti.tsxnew file mode 100644index 0000000000..c59ce7faba--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/SelectableCardMulti.tsx@@ -0,0 +1,47 @@+'use client';++import {useState} from 'react';+import {XDSSelectableCard} from '@xds/core/SelectableCard';+import {XDSStack} from '@xds/core/Layout';+import {XDSText} from '@xds/core/Text';++const tags = [+ {id: 'react', name: 'React', variant: 'blue' as const},+ {id: 'typescript', name: 'TypeScript', variant: 'cyan' as const},+ {id: 'node', name: 'Node.js', variant: 'green' as const},+ {id: 'python', name: 'Python', variant: 'yellow' as const},+ {id: 'rust', name: 'Rust', variant: 'orange' as const},+ {id: 'go', name: 'Go', variant: 'teal' as const},+];++export default function SelectableCardMulti() {+ const [selected, setSelected] = useState(new Set(['react', 'typescript']));++ return (+ <XDSStack direction="horizontal" gap={2} wrap="wrap">+ {tags.map(tag => (+ <XDSSelectableCard+ key={tag.id}+ label={tag.name}+ isSelected={selected.has(tag.id)}+ variant={tag.variant}+ onChange={isNow => {+ setSelected(prev => {+ const next = new Set(prev);+ if (isNow) {+ next.add(tag.id);+ } else {+ next.delete(tag.id);+ }+ return next;+ });+ }}+ width={130}>+ <XDSText type="body" weight="bold">+ {tag.name}+ </XDSText>+ </XDSSelectableCard>+ ))}+ </XDSStack>+ );+}diff --git a/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs b/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.doc.mjsnew file mode 100644index 0000000000..620ea1f657--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.doc.mjs@@ -0,0 +1,11 @@+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ name: 'SelectableCard',+ description:+ 'A plan picker with single-select radio behavior. Cards show an accent border when selected.',+ isReady: true,+ isShowcase: true,+ aspectRatio: 2,+ componentsUsed: ['SelectableCard', 'Layout', 'Text'],+};diff --git a/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.tsx b/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.tsxnew file mode 100644index 0000000000..cb997d1af7--- /dev/null+++ b/packages/cli/templates/blocks/components/Card/SelectableCardShowcase.tsx@@ -0,0 +1,44 @@+'use client';++import {useState} from 'react';+import {XDSSelectableCard} from '@xds/core/SelectableCard';+import {XDSStack} from '@xds/core/Layout';+import {XDSText, XDSHeading} from '@xds/core/Text';++const plans = [+ {id: 'basic', name: 'Basic', price: '$9/mo', desc: 'For individuals'},+ {id: 'pro', name: 'Pro', price: '$29/mo', desc: 'For small teams'},+ {+ id: 'enterprise',+ name: 'Enterprise',+ price: '$99/mo',+ desc: 'For organizations',+ },+];++export default function SelectableCardShowcase() {+ const [selected, setSelected] = useState<string | null>('pro');++ return (+ <XDSStack direction="horizontal" gap={3}>+ {plans.map(plan => (+ <XDSSelectableCard+ key={plan.id}+ label={plan.name}+ isSelected={selected === plan.id}+ onChange={() => setSelected(plan.id)}+ width={180}>+ <XDSStack direction="vertical" gap={1}>+ <XDSHeading level={4}>{plan.name}</XDSHeading>+ <XDSText type="large" weight="bold">+ {plan.price}+ </XDSText>+ <XDSText type="supporting" color="secondary">+ {plan.desc}+ </XDSText>+ </XDSStack>+ </XDSSelectableCard>+ ))}+ </XDSStack>+ );+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex d2fbbc1644..a31b52bd63 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -156,6 +156,12 @@"import": "./dist/CheckboxList/index.mjs","require": "./dist/CheckboxList/index.js"},+ "./ClickableCard": {+ "source": "./src/ClickableCard/index.ts",+ "types": "./dist/ClickableCard/index.d.ts",+ "import": "./dist/ClickableCard/index.mjs",+ "require": "./dist/ClickableCard/index.js"+ },"./CodeBlock": {"source": "./src/CodeBlock/index.ts","types": "./dist/CodeBlock/index.d.ts",@@ -366,6 +372,12 @@"import": "./dist/SegmentedControl/index.mjs","require": "./dist/SegmentedControl/index.js"},+ "./SelectableCard": {+ "source": "./src/SelectableCard/index.ts",+ "types": "./dist/SelectableCard/index.d.ts",+ "import": "./dist/SelectableCard/index.mjs",+ "require": "./dist/SelectableCard/index.js"+ },"./Selector": {"source": "./src/Selector/index.ts","types": "./dist/Selector/index.d.ts",diff --git a/packages/core/src/Card/Card.doc.mjs b/packages/core/src/Card/Card.doc.mjsindex 21e4f32e2d..e092ac72fa 100644--- a/packages/core/src/Card/Card.doc.mjs+++ b/packages/core/src/Card/Card.doc.mjs@@ -2,6 +2,7 @@export const docs = {name: 'Card',+ group: 'Card',keywords: ["card","surface","panel","container","elevated","shadow","box","paper","tile","well"],usage: {description:diff --git a/packages/core/src/ClickableCard/ClickableCard.doc.mjs b/packages/core/src/ClickableCard/ClickableCard.doc.mjsnew file mode 100644index 0000000000..7b343c14ad--- /dev/null+++ b/packages/core/src/ClickableCard/ClickableCard.doc.mjs@@ -0,0 +1,34 @@+/** @type {import('../docs-types').ComponentDoc} */+export const docs = {+ name: 'ClickableCard',+ keywords: ['card', 'clickable', 'interactive', 'navigation', 'action', 'link'],+ usage: {+ description: 'An interactive card for navigation or action targets. Nested interactive elements work independently.',+ bestPractices: [+ {guidance: true, description: 'Use for cards that navigate to a detail page or trigger a single action.'},+ {guidance: true, description: 'Nest buttons or links freely inside — they handle their own events.'},+ {guidance: false, description: 'Use for toggling selection — use SelectableCard for that.'},+ ],+ anatomy: [+ {name: 'Container', required: true, description: 'Interactive div with hover/focus/active states.'},+ {name: 'Content', required: true, description: 'Children, which may include nested interactive elements.'},+ ],+ },+ props: [+ {name: 'label', type: 'string', description: 'Accessibility label.', required: true},+ {name: 'onClick', type: '(event: MouseEvent) => void', description: 'Click handler — fires on card surface only.'},+ {name: 'href', type: 'string', description: 'Navigation URL.'},+ {name: 'target', type: 'string', description: 'Link target.', default: "'_self'"},+ {name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'},+ {name: 'children', type: 'ReactNode', description: 'Card content.'},+ {name: 'padding', type: "SpacingStep", description: 'Inner padding.', default: '4'},+ {name: 'variant', type: "'default' | 'transparent' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'", description: 'Background color variant.', default: "'default'"},+ {name: 'width', type: 'SizeValue', description: 'Card width.'},+ {name: 'height', type: 'SizeValue', description: 'Card height.'},+ {name: 'maxWidth', type: 'SizeValue', description: 'Maximum card width.'},+ ],+ theming: {+ container: true,+ targets: [{className: 'xds-clickable-card', visualProps: ['variant']}],+ },+};diff --git a/packages/core/src/ClickableCard/XDSClickableCard.test.tsx b/packages/core/src/ClickableCard/XDSClickableCard.test.tsxnew file mode 100644index 0000000000..d6875d57a5--- /dev/null+++ b/packages/core/src/ClickableCard/XDSClickableCard.test.tsx@@ -0,0 +1,102 @@+import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {XDSClickableCard} from './XDSClickableCard';++describe('XDSClickableCard', () => {+ it('renders children', () => {+ render(+ <XDSClickableCard label="Test card" onClick={() => {}}>+ <span>Card content</span>+ </XDSClickableCard>,+ );+ expect(screen.getByText('Card content')).toBeInTheDocument();+ });++ it('renders a hidden button for onClick cards', () => {+ render(+ <XDSClickableCard label="Test card" onClick={() => {}}>+ <span>Content</span>+ </XDSClickableCard>,+ );+ const button = screen.getByRole('button', {name: 'Test card'});+ expect(button).toBeInTheDocument();+ });++ it('renders a hidden link for href cards', () => {+ render(+ <XDSClickableCard label="Nav card" href="/settings">+ Content+ </XDSClickableCard>,+ );+ const link = screen.getByRole('link', {name: 'Nav card'});+ expect(link).toBeInTheDocument();+ expect(link).toHaveAttribute('href', '/settings');+ });++ it('calls onClick when card surface is clicked', () => {+ const handleClick = vi.fn();+ render(+ <XDSClickableCard label="Test card" onClick={handleClick}>+ <span>Content</span>+ </XDSClickableCard>,+ );+ // Click the card surface (the text), not the hidden button+ fireEvent.click(screen.getByText('Content'));+ expect(handleClick).toHaveBeenCalledTimes(1);+ });++ it('does NOT call onClick when a nested button is clicked', () => {+ const handleCardClick = vi.fn();+ const handleButtonClick = vi.fn();+ render(+ <XDSClickableCard label="Test card" onClick={handleCardClick}>+ <button onClick={handleButtonClick}>Nested</button>+ </XDSClickableCard>,+ );+ fireEvent.click(screen.getByText('Nested'));+ expect(handleButtonClick).toHaveBeenCalledTimes(1);+ // Card's onClick should NOT fire because click was on a nested interactive+ expect(handleCardClick).not.toHaveBeenCalled();+ });++ it('hidden button has correct aria-label', () => {+ render(+ <XDSClickableCard label="Settings card" onClick={() => {}}>+ Content+ </XDSClickableCard>,+ );+ const button = screen.getByRole('button', {name: 'Settings card'});+ expect(button).toHaveAttribute('aria-label', 'Settings card');+ });++ it('hidden link passes target attribute', () => {+ render(+ <XDSClickableCard label="External" href="https://example.com" target="_blank">+ Content+ </XDSClickableCard>,+ );+ const link = screen.getByRole('link', {name: 'External'});+ expect(link).toHaveAttribute('target', '_blank');+ });++ it('disabled button is disabled', () => {+ const handleClick = vi.fn();+ render(+ <XDSClickableCard label="Disabled" onClick={handleClick} isDisabled>+ Content+ </XDSClickableCard>,+ );+ const button = screen.getByRole('button', {name: 'Disabled'});+ expect(button).toBeDisabled();+ });++ it('disabled link has aria-disabled', () => {+ render(+ <XDSClickableCard label="Disabled link" href="/settings" isDisabled>+ Content+ </XDSClickableCard>,+ );+ const link = screen.getByRole('link', {name: 'Disabled link'});+ expect(link).toHaveAttribute('aria-disabled', 'true');+ });+});diff --git a/packages/core/src/ClickableCard/XDSClickableCard.tsx b/packages/core/src/ClickableCard/XDSClickableCard.tsxnew file mode 100644index 0000000000..617ec86328--- /dev/null+++ b/packages/core/src/ClickableCard/XDSClickableCard.tsx@@ -0,0 +1,289 @@+'use client';++/**+ * @file XDSClickableCard.tsx+ * @input Uses XDSCard, useClickableContainer, StyleX+ * @output Exports XDSClickableCard component and XDSClickableCardProps+ * @position Interactive card for navigation or action targets+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/ClickableCard/ClickableCard.doc.mjs (props table, features)+ * - /packages/core/src/ClickableCard/index.ts (exports if types change)+ * - /apps/storybook/stories/ClickableCard.stories.tsx (storybook stories)+ * - /packages/cli/templates/blocks/components/Card/ClickableCardShowcase.tsx (showcase block)+ * - /packages/cli/templates/blocks/components/Card/ClickableCardWithNestedButton.tsx (block)+ *+ * Composes XDSCard for all visual styling (radius, padding, variants,+ * container tokens, theming). Adds an interactive wrapper with+ * useClickableContainer for safe nested interactive elements.+ *+ * A hidden <button> or <a> inside the card provides the accessible role,+ * label, and focus ring — the card surface itself has no role/tabIndex.+ * This gives screen readers a real interactive element to announce while+ * keeping the visual hover/active overlay on the full card.+ *+ * For static display, use XDSCard.+ * For toggle selection, use XDSSelectableCard.+ */++import {+ type ReactNode,+ type MouseEvent,+ type MutableRefObject,+ useRef,+ type Ref,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {colorVars} from '../theme/tokens.stylex';+import type {SizeValue, SpacingStep} from '../utils/types';+import {xdsClassName} from '../utils';+import {XDSCard} from '../Card/XDSCard';+import type {XDSCardVariant} from '../Card/XDSCard';+import {useClickableContainer} from '../hooks/useClickableContainer';+import type {XDSBaseProps} from '../XDSBaseProps';++// =============================================================================+// Styles — only the interactive layer, Card handles everything else+// =============================================================================++const styles = stylex.create({+ interactive: {+ position: 'relative',+ cursor: 'pointer',+ textDecoration: 'none',+ color: 'inherit',+ outlineOffset: '2px',+ },+ focusWithin: {+ ':has(:focus-visible)': {+ outline: `2px solid ${colorVars['--color-accent']}`,+ outlineOffset: '2px',+ },+ },+ // Hover overlay — guarded by @media (hover: hover) so touch devices+ // don't show a stuck hover state. Active/pressed state works everywhere.+ overlay: {+ '::after': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderRadius: 'inherit',+ pointerEvents: 'none',+ transition: 'background-color 0.15s ease',+ backgroundColor: 'transparent',+ },+ ':active::after': {+ backgroundColor: 'color-mix(in srgb, currentColor 10%, transparent)',+ },+ },+ hoverOnPointer: {+ '@media (hover: hover)': {+ ':hover::after': {+ backgroundColor: 'color-mix(in srgb, currentColor 5%, transparent)',+ },+ },+ },+ disabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ },+ srOnly: {+ position: 'absolute',+ width: '1px',+ height: '1px',+ padding: 0,+ margin: '-1px',+ overflow: 'hidden',+ clip: 'rect(0, 0, 0, 0)',+ whiteSpace: 'nowrap',+ borderWidth: 0,+ },+});++// =============================================================================+// Props+// =============================================================================++export interface XDSClickableCardProps extends XDSBaseProps {+ /** Ref forwarded to the root element. */+ ref?: Ref<HTMLDivElement>;++ /**+ * Accessibility label for the card.+ * Used as `aria-label` — provides the accessible name for screen readers.+ * When the card has visible text that serves as its label, prefer+ * passing that text here so the screen reader announcement matches.+ */+ label: string;++ /**+ * Click handler. Fires when the card surface is clicked+ * (not when nested interactive elements are clicked).+ */+ onClick?: (event: MouseEvent<HTMLElement>) => void;++ /**+ * Navigation URL. When provided, clicking the card navigates to this URL.+ * Ctrl/Cmd+click opens in a new tab.+ */+ href?: string;++ /**+ * Link target for href navigation.+ * @default '_self'+ */+ target?: string;++ /**+ * Set to true to disable the card.+ * Disabled cards remain focusable (tabIndex 0) with aria-disabled+ * so screen reader users can discover them.+ */+ isDisabled?: boolean;++ /**+ * Content to render inside the card.+ * Can include nested interactive elements (buttons, links) — they will+ * work independently from the card's click/navigation behavior.+ */+ children?: ReactNode;++ /**+ * Internal padding of the card using the spacing scale.+ * @default 4 (16px)+ */+ padding?: SpacingStep;++ /**+ * Background color variant.+ * @default 'default'+ */+ variant?: XDSCardVariant;++ /** Width of the card. */+ width?: SizeValue;++ /** Height of the card. */+ height?: SizeValue;++ /** Maximum width of the card. */+ maxWidth?: SizeValue;++}++// =============================================================================+// Component+// =============================================================================++/**+ * An interactive card that acts as a single navigation or action target.+ *+ * Composes XDSCard for visual styling and adds an interactive layer+ * with useClickableContainer. Nested interactive elements (buttons,+ * links, inputs) work independently — clicking them does NOT trigger+ * the card's onClick or navigation.+ *+ * A visually-hidden <button> or <a> inside the card provides the+ * accessible role and label. The card surface is a plain <div> —+ * no role or tabIndex on the container.+ *+ * @compositionHint Use for cards that navigate to a detail page or trigger an action.+ * For toggle selection cards, use XDSSelectableCard instead.+ * Nest XDSButton or other interactive elements freely inside — they won't conflict.+ *+ * @example+ * ```+ * <XDSClickableCard label="Settings" href="/settings">+ * <XDSText type="body" weight="bold">Settings</XDSText>+ * <XDSText type="supporting" color="secondary">Manage your preferences</XDSText>+ * </XDSClickableCard>+ * ```+ *+ * @example+ * ```+ * <XDSClickableCard label="Open modal" onClick={() => setShowModal(true)}>+ * <XDSText type="body">Click anywhere to open</XDSText>+ * <XDSButton label="Other action" onClick={handleOther} />+ * </XDSClickableCard>+ * ```+ */+export function XDSClickableCard({+ label,+ onClick: onClickProp,+ href,+ target,+ isDisabled = false,+ children,+ padding,+ variant = 'default',+ width,+ height,+ maxWidth,+ ref,+ ...props+}: XDSClickableCardProps) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const interactiveRef = useRef<HTMLElement | null>(null);++ const {onClick, onMouseUp} = useClickableContainer({+ containerRef,+ interactiveRef,+ onClick: onClickProp,+ href,+ target,+ disabled: isDisabled,+ });++ const isLink = href != null;++ return (+ <XDSCard+ ref={(node: HTMLDivElement | null) => {+ containerRef.current = node;+ if (typeof ref === 'function') ref(node);+ else if (ref != null)+ (ref as MutableRefObject<HTMLDivElement | null>).current = node;+ }}+ width={width}+ height={height}+ maxWidth={maxWidth}+ padding={padding}+ variant={variant}+ className={xdsClassName('clickable-card', {variant})}+ xstyle={[+ styles.interactive,+ styles.focusWithin,+ !isDisabled && styles.overlay,+ !isDisabled && styles.hoverOnPointer,+ isDisabled && styles.disabled,+ ] as unknown as StyleXStyles}+ onClick={!isDisabled ? onClick : undefined}+ onMouseUp={!isDisabled ? onMouseUp : undefined}+ {...props}>+ {isLink ? (+ <a+ ref={interactiveRef as React.Ref<HTMLAnchorElement>}+ href={href}+ target={target}+ aria-label={label}+ aria-disabled={isDisabled || undefined}+ tabIndex={isDisabled ? -1 : 0}+ {...stylex.props(styles.srOnly)}+ />+ ) : (+ <button+ ref={interactiveRef as React.Ref<HTMLButtonElement>}+ type="button"+ aria-label={label}+ disabled={isDisabled}+ onClick={onClickProp}+ {...stylex.props(styles.srOnly)}+ />+ )}+ {children}+ </XDSCard>+ );+}++XDSClickableCard.displayName = 'XDSClickableCard';diff --git a/packages/core/src/ClickableCard/index.ts b/packages/core/src/ClickableCard/index.tsnew file mode 100644index 0000000000..e14df58daa--- /dev/null+++ b/packages/core/src/ClickableCard/index.ts@@ -0,0 +1,2 @@+export {XDSClickableCard} from './XDSClickableCard';+export type {XDSClickableCardProps} from './XDSClickableCard';diff --git a/packages/core/src/SelectableCard/SelectableCard.doc.mjs b/packages/core/src/SelectableCard/SelectableCard.doc.mjsnew file mode 100644index 0000000000..1b56c80686--- /dev/null+++ b/packages/core/src/SelectableCard/SelectableCard.doc.mjs@@ -0,0 +1,33 @@+/** @type {import('../docs-types').ComponentDoc} */+export const docs = {+ name: 'SelectableCard',+ keywords: ['card', 'selectable', 'toggle', 'checkbox', 'radio', 'selection'],+ usage: {+ description: 'A card that toggles between selected and unselected states with an accent border. For navigation use ClickableCard.',+ bestPractices: [+ {guidance: true, description: 'Use for plan pickers, filter chips, or option grids.'},+ {guidance: true, description: 'For single-select track one ID; for multi-select use a Set.'},+ {guidance: false, description: 'Use for navigation — use ClickableCard for that.'},+ ],+ anatomy: [+ {name: 'Container', required: true, description: 'Interactive div with accent border on selection.'},+ {name: 'Content', required: true, description: 'Children rendered inside the card.'},+ ],+ },+ props: [+ {name: 'label', type: 'string', description: 'Accessibility label.', required: true},+ {name: 'isSelected', type: 'boolean', description: 'Controlled selection state.', required: true},+ {name: 'onChange', type: '(isSelected: boolean) => void', description: 'Called when toggled.', required: true},+ {name: 'isDisabled', type: 'boolean', description: 'Disables the card.', default: 'false'},+ {name: 'children', type: 'ReactNode', description: 'Card content.'},+ {name: 'padding', type: "SpacingStep", description: 'Inner padding.', default: '4'},+ {name: 'variant', type: "'default' | 'transparent' | 'muted' | 'blue' | 'cyan' | 'gray' | 'green' | 'orange' | 'pink' | 'purple' | 'red' | 'teal' | 'yellow'", description: 'Background color variant.', default: "'default'"},+ {name: 'width', type: 'SizeValue', description: 'Card width.'},+ {name: 'height', type: 'SizeValue', description: 'Card height.'},+ {name: 'maxWidth', type: 'SizeValue', description: 'Maximum card width.'},+ ],+ theming: {+ container: true,+ targets: [{className: 'xds-selectable-card', visualProps: ['selected']}],+ },+};diff --git a/packages/core/src/SelectableCard/XDSSelectableCard.test.tsx b/packages/core/src/SelectableCard/XDSSelectableCard.test.tsxnew file mode 100644index 0000000000..84a902ef10--- /dev/null+++ b/packages/core/src/SelectableCard/XDSSelectableCard.test.tsx@@ -0,0 +1,110 @@+import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {XDSSelectableCard} from './XDSSelectableCard';++describe('XDSSelectableCard', () => {+ it('renders children', () => {+ render(+ <XDSSelectableCard label="Test" isSelected={false} onChange={() => {}}>+ <span>Card content</span>+ </XDSSelectableCard>,+ );+ expect(screen.getByText('Card content')).toBeInTheDocument();+ });++ it('renders a hidden checkbox', () => {+ render(+ <XDSSelectableCard label="Test" isSelected={false} onChange={() => {}}>+ Content+ </XDSSelectableCard>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Test'});+ expect(checkbox).toBeInTheDocument();+ });++ it('checkbox reflects isSelected=true as checked', () => {+ render(+ <XDSSelectableCard label="Plan A" isSelected={true} onChange={() => {}}>+ Content+ </XDSSelectableCard>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Plan A'});+ expect(checkbox).toBeChecked();+ });++ it('checkbox reflects isSelected=false as unchecked', () => {+ render(+ <XDSSelectableCard label="Plan B" isSelected={false} onChange={() => {}}>+ Content+ </XDSSelectableCard>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Plan B'});+ expect(checkbox).not.toBeChecked();+ });++ it('calls onChange with true when card surface is clicked (unselected)', () => {+ const handleChange = vi.fn();+ render(+ <XDSSelectableCard label="Test" isSelected={false} onChange={handleChange}>+ <span>Content</span>+ </XDSSelectableCard>,+ );+ fireEvent.click(screen.getByText('Content'));+ expect(handleChange).toHaveBeenCalledWith(true);+ });++ it('calls onChange with false when card surface is clicked (selected)', () => {+ const handleChange = vi.fn();+ render(+ <XDSSelectableCard label="Test" isSelected={true} onChange={handleChange}>+ <span>Content</span>+ </XDSSelectableCard>,+ );+ fireEvent.click(screen.getByText('Content'));+ expect(handleChange).toHaveBeenCalledWith(false);+ });++ it('calls onChange when checkbox itself is clicked', () => {+ const handleChange = vi.fn();+ render(+ <XDSSelectableCard label="Test" isSelected={false} onChange={handleChange}>+ Content+ </XDSSelectableCard>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Test'});+ fireEvent.click(checkbox);+ expect(handleChange).toHaveBeenCalledWith(true);+ });++ it('disabled checkbox is disabled', () => {+ const handleChange = vi.fn();+ render(+ <XDSSelectableCard+ label="Disabled"+ isSelected={false}+ onChange={handleChange}+ isDisabled+ >+ Content+ </XDSSelectableCard>,+ );+ const checkbox = screen.getByRole('checkbox', {name: 'Disabled'});+ expect(checkbox).toBeDisabled();+ });++ it('does not call onChange when disabled card is clicked', () => {+ const handleChange = vi.fn();+ render(+ <XDSSelectableCard+ label="Disabled"+ isSelected={false}+ onChange={handleChange}+ isDisabled+ >+ <span>Content</span>+ </XDSSelectableCard>,+ );+ fireEvent.click(screen.getByText('Content'));+ expect(handleChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/SelectableCard/XDSSelectableCard.tsx b/packages/core/src/SelectableCard/XDSSelectableCard.tsxnew file mode 100644index 0000000000..2723654089--- /dev/null+++ b/packages/core/src/SelectableCard/XDSSelectableCard.tsx@@ -0,0 +1,369 @@+'use client';++/**+ * @file XDSSelectableCard.tsx+ * @input Uses XDSCard, useClickableContainer, StyleX+ * @output Exports XDSSelectableCard component and XDSSelectableCardProps+ * @position Interactive card for toggle selection+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/SelectableCard/SelectableCard.doc.mjs (props table, features)+ * - /packages/core/src/SelectableCard/index.ts (exports if types change)+ * - /apps/storybook/stories/SelectableCard.stories.tsx (storybook stories)+ * - /packages/cli/templates/blocks/components/Card/SelectableCardShowcase.tsx (showcase block)+ * - /packages/cli/templates/blocks/components/Card/SelectableCardMulti.tsx (block)+ *+ * Composes XDSCard for all visual styling. Adds selection state with+ * an inset box-shadow (zero layout jitter) and useClickableContainer+ * for safe nested interactive elements.+ *+ * A hidden <input type="checkbox"> inside the card provides the accessible+ * role, label, and checked state — the card surface itself has no role/tabIndex.+ *+ * For static display, use XDSCard.+ * For navigation or action cards, use XDSClickableCard.+ */++import {+ type ReactNode,+ type MouseEvent,+ type MutableRefObject,+ useRef,+ useCallback,+ type Ref,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {StyleXStyles} from '@stylexjs/stylex';+import {colorVars} from '../theme/tokens.stylex';+import type {SizeValue, SpacingStep} from '../utils/types';+import {xdsClassName} from '../utils';+import {XDSCard} from '../Card/XDSCard';+import type {XDSCardVariant} from '../Card/XDSCard';+import {useClickableContainer} from '../hooks/useClickableContainer';+import type {XDSBaseProps} from '../XDSBaseProps';++// =============================================================================+// Styles — selection + interaction; Card handles the rest+// =============================================================================++const styles = stylex.create({+ interactive: {+ position: 'relative',+ cursor: 'pointer',+ transition: 'box-shadow 0.15s ease, border-color 0.15s ease',+ outlineOffset: '2px',+ },+ focusWithin: {+ ':has(:focus-visible)': {+ outline: `2px solid ${colorVars['--color-accent']}`,+ outlineOffset: '2px',+ },+ },+ // Hover overlay — guarded by @media (hover: hover) so touch devices+ // don't show a stuck hover state. Active/pressed state works everywhere.+ overlay: {+ '::after': {+ content: '""',+ position: 'absolute',+ inset: 0,+ borderRadius: 'inherit',+ pointerEvents: 'none',+ transition: 'background-color 0.15s ease',+ backgroundColor: 'transparent',+ },+ ':active::after': {+ backgroundColor: 'color-mix(in srgb, currentColor 10%, transparent)',+ },+ },+ hoverOnPointer: {+ '@media (hover: hover)': {+ ':hover::after': {+ backgroundColor: 'color-mix(in srgb, currentColor 5%, transparent)',+ },+ },+ },+ disabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ },+ srOnly: {+ position: 'absolute',+ width: '1px',+ height: '1px',+ padding: 0,+ margin: '-1px',+ overflow: 'hidden',+ clip: 'rect(0, 0, 0, 0)',+ whiteSpace: 'nowrap',+ borderWidth: 0,+ },+ // Selection indicator — inset box-shadow for the thick inner ring (zero layout+ // jitter) plus borderColor change on the card's own border for a cohesive look.+ selected: {+ borderColor: colorVars['--color-accent'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-accent']}`,+ },+ selectedBlue: {+ borderColor: colorVars['--color-border-blue'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-blue']}`,+ },+ selectedCyan: {+ borderColor: colorVars['--color-border-cyan'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-cyan']}`,+ },+ selectedGray: {+ borderColor: colorVars['--color-border-gray'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-gray']}`,+ },+ selectedGreen: {+ borderColor: colorVars['--color-border-green'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-green']}`,+ },+ selectedOrange: {+ borderColor: colorVars['--color-border-orange'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-orange']}`,+ },+ selectedPink: {+ borderColor: colorVars['--color-border-pink'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-pink']}`,+ },+ selectedPurple: {+ borderColor: colorVars['--color-border-purple'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-purple']}`,+ },+ selectedRed: {+ borderColor: colorVars['--color-border-red'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-red']}`,+ },+ selectedTeal: {+ borderColor: colorVars['--color-border-teal'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-teal']}`,+ },+ selectedYellow: {+ borderColor: colorVars['--color-border-yellow'],+ boxShadow: `inset 0 0 0 2px ${colorVars['--color-border-yellow']}`,+ },+});++const selectedStyleForVariant = (variant: XDSCardVariant) => {+ switch (variant) {+ case 'blue':+ return styles.selectedBlue;+ case 'cyan':+ return styles.selectedCyan;+ case 'gray':+ return styles.selectedGray;+ case 'green':+ return styles.selectedGreen;+ case 'orange':+ return styles.selectedOrange;+ case 'pink':+ return styles.selectedPink;+ case 'purple':+ return styles.selectedPurple;+ case 'red':+ return styles.selectedRed;+ case 'teal':+ return styles.selectedTeal;+ case 'yellow':+ return styles.selectedYellow;+ default:+ return styles.selected;+ }+};++// =============================================================================+// Props+// =============================================================================++export interface XDSSelectableCardProps extends Omit<XDSBaseProps, 'onChange'> {+ /** Ref forwarded to the root element. */+ ref?: Ref<HTMLDivElement>;++ /**+ * Accessibility label for the card.+ * Used as `aria-label` — provides the accessible name for screen readers.+ */+ label: string;++ /**+ * Controlled selection state.+ * When true, the card shows an inset accent border indicating selection.+ */+ isSelected: boolean;++ /**+ * Selection change handler.+ * Called with the new selection state when the card is toggled.+ */+ onChange: (isSelected: boolean) => void;++ /**+ * Set to true to disable the card.+ * Disabled cards remain focusable (tabIndex 0) with aria-disabled+ * so screen reader users can discover them.+ */+ isDisabled?: boolean;++ /** Content to render inside the card. */+ children?: ReactNode;++ /**+ * Internal padding of the card using the spacing scale.+ * @default 4 (16px)+ */+ padding?: SpacingStep;++ /**+ * Background color variant.+ * @default 'default'+ */+ variant?: XDSCardVariant;++ /** Width of the card. */+ width?: SizeValue;++ /** Height of the card. */+ height?: SizeValue;++ /** Maximum width of the card. */+ maxWidth?: SizeValue;++}++// =============================================================================+// Component+// =============================================================================++/**+ * A card that toggles between selected and unselected states.+ *+ * Composes XDSCard for visual styling and adds selection state with+ * an inset box-shadow (zero layout jitter vs plain Card). Supports+ * hover, pressed, focus, and disabled states.+ *+ * A visually-hidden <input type="checkbox"> inside the card provides+ * the accessible role, label, and checked state. The card surface+ * is a plain <div> — no role or tabIndex on the container.+ *+ * @compositionHint Use for multi-select or single-select card groups.+ * Manage selection state externally — use a Set for multi-select+ * or a single value for radio-style selection.+ * For navigation/action cards, use XDSClickableCard instead.+ *+ * @example+ * ```+ * // Single select (radio behavior)+ * const [selected, setSelected] = useState<string | null>(null);+ *+ * {plans.map(plan => (+ * <XDSSelectableCard+ * key={plan.id}+ * label={plan.name}+ * isSelected={selected === plan.id}+ * onChange={() => setSelected(plan.id)}+ * >+ * <XDSText type="body" weight="bold">{plan.name}</XDSText>+ * </XDSSelectableCard>+ * ))}+ * ```+ *+ * @example+ * ```+ * // Multi-select (checkbox behavior)+ * const [selected, setSelected] = useState(new Set<string>());+ *+ * {filters.map(filter => (+ * <XDSSelectableCard+ * key={filter.id}+ * label={filter.name}+ * isSelected={selected.has(filter.id)}+ * onChange={(isNowSelected) => {+ * setSelected(prev => {+ * const next = new Set(prev);+ * isNowSelected ? next.add(filter.id) : next.delete(filter.id);+ * return next;+ * });+ * }}+ * >+ * <XDSText type="body">{filter.name}</XDSText>+ * </XDSSelectableCard>+ * ))}+ * ```+ */+export function XDSSelectableCard({+ label,+ isSelected,+ onChange,+ isDisabled = false,+ children,+ padding,+ variant = 'default',+ width,+ height,+ maxWidth,+ ref,+ ...props+}: XDSSelectableCardProps) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const interactiveRef = useRef<HTMLInputElement | null>(null);++ const handleClick = useCallback(+ (_event: MouseEvent<HTMLElement>) => {+ if (!isDisabled) {+ onChange(!isSelected);+ }+ },+ [isDisabled, isSelected, onChange],+ );++ const {onClick, onMouseUp} = useClickableContainer({+ containerRef,+ interactiveRef,+ onClick: handleClick,+ disabled: isDisabled,+ });++ return (+ <XDSCard+ ref={(node: HTMLDivElement | null) => {+ containerRef.current = node;+ if (typeof ref === 'function') ref(node);+ else if (ref != null)+ (ref as MutableRefObject<HTMLDivElement | null>).current = node;+ }}+ width={width}+ height={height}+ maxWidth={maxWidth}+ padding={padding}+ variant={variant}+ className={xdsClassName('selectable-card', {+ variant,+ selected: isSelected ? 'true' : 'false',+ })}+ xstyle={[+ styles.interactive,+ styles.focusWithin,+ isSelected && selectedStyleForVariant(variant),+ !isDisabled && styles.overlay,+ !isDisabled && styles.hoverOnPointer,+ isDisabled && styles.disabled,+ ] as unknown as StyleXStyles}+ onClick={!isDisabled ? onClick : undefined}+ onMouseUp={!isDisabled ? onMouseUp : undefined}+ {...props}>+ <input+ ref={interactiveRef}+ type="checkbox"+ checked={isSelected}+ aria-label={label}+ disabled={isDisabled}+ onChange={() => onChange(!isSelected)}+ {...stylex.props(styles.srOnly)}+ />+ {children}+ </XDSCard>+ );+}++XDSSelectableCard.displayName = 'XDSSelectableCard';diff --git a/packages/core/src/SelectableCard/index.ts b/packages/core/src/SelectableCard/index.tsnew file mode 100644index 0000000000..d96d640348--- /dev/null+++ b/packages/core/src/SelectableCard/index.ts@@ -0,0 +1,2 @@+export {XDSSelectableCard} from './XDSSelectableCard';+export type {XDSSelectableCardProps} from './XDSSelectableCard';diff --git a/packages/core/src/docs-types.ts b/packages/core/src/docs-types.tsindex d246120c04..2bb504638a 100644--- a/packages/core/src/docs-types.ts+++ b/packages/core/src/docs-types.ts@@ -288,6 +288,7 @@ interface BaseDoc {| 'Avatar'| 'Breadcrumbs'| 'Button'+ | 'Card'| 'Chat'| 'Checkbox'| 'Collapsible'diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex 49c8d54b01..e5b82a1f34 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -38,3 +38,9 @@ export type {} from './useXDSStreamingText';export {useImageMode} from './useImageMode';export type {ImageSampleRegion, UseImageModeOptions} from './useImageMode';++export {useClickableContainer} from './useClickableContainer';+export type {+ UseClickableContainerOptions,+ ClickableContainerResult,+} from './useClickableContainer';diff --git a/packages/core/src/hooks/useClickableContainer.ts b/packages/core/src/hooks/useClickableContainer.tsnew file mode 100644index 0000000000..f9682c5427--- /dev/null+++ b/packages/core/src/hooks/useClickableContainer.ts@@ -0,0 +1,216 @@+'use client';++/**+ * @file useClickableContainer.ts+ * @input Container ref, interactive element ref, click/href handlers+ * @output onClick and onMouseUp handlers for the container+ * @position Core hook for clickable containers that safely handle nested interactive elements+ *+ * Solves the "nested interactive elements" problem: when a card is clickable+ * but contains buttons/links, clicking those should NOT trigger the card's action.+ */++import {useCallback, useEffect, type RefObject, type MouseEvent} from 'react';++// Interactive element selectors — clicks on these (or their descendants)+// should NOT bubble to the container's click handler.+const INTERACTIVE_SELECTORS = [+ 'button',+ 'a',+ 'input',+ 'select',+ 'textarea',+ '[role="button"]',+ '[role="link"]',+ '[role="checkbox"]',+ '[role="radio"]',+ '[role="switch"]',+ '[role="tab"]',+ '[role="menuitem"]',+ '[role="option"]',+ '[role="combobox"]',+ '[role="listbox"]',+ '[role="slider"]',+ '[role="spinbutton"]',+ '[data-pressable-container]',+].join(',');++const NON_INTERACTIVE_SELECTORS = '[aria-readonly="true"]';++/**+ * Check whether an element has an interactive ancestor between it and the root.+ * If the click target is inside a nested button/link/etc., we should NOT+ * handle it at the container level.+ */+function hasInteractiveAncestor(+ el: Element,+ rootEl: Element,+): boolean {+ let current: Element | null = el;+ while (current != null && current !== rootEl && current !== document.body) {+ if (+ current.matches(INTERACTIVE_SELECTORS) &&+ !current.matches(NON_INTERACTIVE_SELECTORS)+ ) {+ return true;+ }+ current = current.parentElement;+ }+ return false;+}++/** Check if there's a text selection inside the node (don't navigate on text select) */+function hasTextSelection(node: Element): boolean {+ if (typeof document === 'undefined' || !('getSelection' in document)) {+ return false;+ }+ const selection = document.getSelection();+ if (selection == null || selection.isCollapsed) {+ return false;+ }+ return node.contains(selection.anchorNode);+}++export interface UseClickableContainerOptions {+ /** Ref to the outer container element */+ containerRef: RefObject<HTMLElement | null>;+ /** Ref to the primary interactive element inside (link, button) */+ interactiveRef?: RefObject<HTMLElement | null>;+ /** Click handler */+ onClick?: (event: MouseEvent<HTMLElement>) => void;+ /** Navigation URL — when provided, clicking the container navigates */+ href?: string;+ /** Link target */+ target?: string;+ /** Whether the container is disabled */+ disabled?: boolean;+}++export interface ClickableContainerResult {+ onClick: (event: MouseEvent<HTMLElement>) => void;+ onMouseUp: (event: MouseEvent<HTMLElement>) => void;+}++/**+ * Hook that makes a container element clickable while preserving+ * nested interactive element behavior.+ *+ * When the user clicks the container surface (not on a nested button/link),+ * the hook fires the onClick handler or navigates to href.+ * When the user clicks a nested interactive element, it does nothing —+ * the nested element handles its own event.+ *+ * @compositionHint Use inside XDSClickableCard or XDSSelectableCard.+ * For custom interactive containers, pair with a ref to the outer div.+ *+ * @example+ * ```+ * const containerRef = useRef<HTMLDivElement>(null);+ * const { onClick, onMouseUp } = useClickableContainer({+ * containerRef,+ * onClick: () => console.log('card clicked'),+ * });+ * return (+ * <div ref={containerRef} onClick={onClick} onMouseUp={onMouseUp}>+ * <p>Click anywhere on this card</p>+ * <button onClick={() => alert('button')}>Nested button</button>+ * </div>+ * );+ * ```+ */+export function useClickableContainer({+ containerRef,+ interactiveRef,+ onClick: onClickProp,+ href,+ target,+ disabled = false,+}: UseClickableContainerOptions): ClickableContainerResult {+ // Mark container as pressable for the interactive selector check+ useEffect(() => {+ const el = containerRef.current;+ if (el) {+ el.setAttribute('data-pressable-container', 'true');+ }+ }, [containerRef]);++ const onClick = useCallback(+ (event: MouseEvent<HTMLElement>) => {+ if (disabled) return;++ const containerEl = containerRef.current;+ if (!containerEl) return;++ // Don't trigger on text selection+ if (hasTextSelection(containerEl)) return;++ const eventTarget = event.target;+ if (!(eventTarget instanceof Element)) return;++ // If the click landed on or inside a nested interactive element, bail+ if (+ eventTarget !== event.currentTarget &&+ hasInteractiveAncestor(eventTarget, containerEl)+ ) {+ return;+ }++ // Fire the click handler+ onClickProp?.(event);+ if (event.defaultPrevented) return;++ // Navigate if href is provided+ if (href != null) {+ const shouldOpenNewTab =+ target === '_blank' || event.ctrlKey || event.metaKey;+ if (shouldOpenNewTab) {+ window.open(href, '_blank', 'noopener');+ } else {+ window.location.href = href;+ }+ }++ // Proxy click to the interactive ref if no explicit handler+ if (href == null && onClickProp == null && interactiveRef?.current) {+ const clickEvent = new MouseEvent('click', {+ bubbles: event.bubbles,+ cancelable: event.cancelable,+ ctrlKey: event.ctrlKey,+ metaKey: event.metaKey,+ shiftKey: event.shiftKey,+ altKey: event.altKey,+ button: event.button,+ });+ interactiveRef.current.dispatchEvent(clickEvent);+ event.stopPropagation();+ }+ },+ [containerRef, interactiveRef, onClickProp, href, target, disabled],+ );++ const onMouseUp = useCallback(+ (event: MouseEvent<HTMLElement>) => {+ if (disabled) return;++ const containerEl = containerRef.current;+ if (!containerEl) return;++ const eventTarget = event.target;+ if (!(eventTarget instanceof Element)) return;++ // Middle-click on href opens in new tab+ const isMiddleClick = event.button === 1;+ if (+ isMiddleClick &&+ href != null &&+ (eventTarget === event.currentTarget ||+ !hasInteractiveAncestor(eventTarget, containerEl))+ ) {+ window.open(href, '_blank', 'noopener');+ }+ },+ [containerRef, href, disabled],+ );++ return {onClick, onMouseUp};+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex b0efdb2fbd..8b26ed9c30 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -22,6 +22,7 @@ export * from './Breadcrumbs';export * from './Button';export * from './IconButton';export * from './Card';+export * from './ClickableCard';export * from './Carousel';export * from './Calendar';export * from './Center';@@ -49,6 +50,7 @@ export * from './FormLayout';export * from './Grid';export * from './Section';export * from './SegmentedControl';+export * from './SelectableCard';export * from './Selector';export * from './MultiSelector';export * from './Icon';diff --git a/packages/core/src/theme/derivedVarRegistry.ts b/packages/core/src/theme/derivedVarRegistry.tsindex 302c15bd61..07d58d678e 100644--- a/packages/core/src/theme/derivedVarRegistry.ts+++ b/packages/core/src/theme/derivedVarRegistry.ts@@ -33,12 +33,8 @@ export interface DerivedVarEntry {* entries share the same property.*/export const derivedVarRegistry: Record<string, DerivedVarEntry[]> = {- banner: [- {property: 'borderRadius', vars: ['--_banner-radius']},- ],- button: [- {property: 'borderRadius', vars: ['--_button-radius']},- ],+ banner: [{property: 'borderRadius', vars: ['--_banner-radius']}],+ button: [{property: 'borderRadius', vars: ['--_button-radius']}],card: [{property: 'borderRadius', vars: ['--_card-radius']},{property: 'padding', expand: 'container'},@@ -55,18 +51,10 @@ export const derivedVarRegistry: Record<string, DerivedVarEntry[]> = {{property: 'borderRadius', vars: ['--_dropdown-menu-radius']},{property: 'padding', vars: ['--_dropdown-menu-padding']},],- field: [- {property: 'borderRadius', vars: ['--_field-radius']},- ],- hovercard: [- {property: 'borderRadius', vars: ['--_hovercard-radius']},- ],- popover: [- {property: 'borderRadius', vars: ['--_popover-radius']},- ],- section: [- {property: 'padding', expand: 'container'},- ],+ field: [{property: 'borderRadius', vars: ['--_field-radius']}],+ hovercard: [{property: 'borderRadius', vars: ['--_hovercard-radius']}],+ popover: [{property: 'borderRadius', vars: ['--_popover-radius']}],+ section: [{property: 'padding', expand: 'container'}],'segmented-control': [{property: 'borderRadius', vars: ['--_segmented-control-radius']},{property: 'padding', vars: ['--_segmented-control-padding']},