An open source design system that's fully customizable and agent ready
TypeScript
feat(Collapsible): add XDSCollapsible primitive and XDSCollapsibleGroup (#263)
Cindy Zhang096ecafa925a
diff --git a/apps/storybook/stories/Collapsible.stories.tsx b/apps/storybook/stories/Collapsible.stories.tsxnew file mode 100644index 0000000000..25cf8d44d1--- /dev/null+++ b/apps/storybook/stories/Collapsible.stories.tsx@@ -0,0 +1,223 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {XDSCollapsible, XDSCollapsibleGroup} from '@xds/core/CollapsibleGroup';+import {XDSCard} from '@xds/core/Card';+import {XDSVStack} from '@xds/core/Layout';+import {+ colorVars,+ spacingVars,+ typographyVars,+} from '@xds/core/theme/tokens.stylex';++const styles = stylex.create({+ pageWrapper: {+ backgroundColor: colorVars['--color-wash'],+ padding: spacingVars['--spacing-6'],+ },+ text: {+ fontFamily: typographyVars['--font-body'],+ color: colorVars['--color-text-primary'],+ margin: 0,+ },+ textSecondary: {+ color: colorVars['--color-text-secondary'],+ fontSize: 14,+ fontFamily: typographyVars['--font-body'],+ margin: 0,+ },+});++const meta: Meta<typeof XDSCollapsibleGroup> = {+ title: 'Components/XDSCollapsible',+ component: XDSCollapsibleGroup,+ tags: ['autodocs'],+ decorators: [+ Story => (+ <div {...stylex.props(styles.pageWrapper)}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj<typeof XDSCollapsibleGroup>;++export const SingleMode: Story = {+ name: 'Single Mode (default)',+ render: () => (+ <XDSCollapsibleGroup type="single" defaultValue="general">+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="General Settings" value="general">+ <p {...stylex.props(styles.text)}>+ Configure your general preferences including language, timezone,+ and display options.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Privacy Settings" value="privacy">+ <p {...stylex.props(styles.text)}>+ Manage who can see your profile, activity, and personal+ information.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Notification Settings" value="notifications">+ <p {...stylex.props(styles.text)}>+ Choose which notifications you receive and how they are delivered.+ </p>+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+ </XDSCollapsibleGroup>+ ),+};++export const MultipleMode: Story = {+ name: 'Multiple Mode',+ render: () => (+ <XDSCollapsibleGroup type="multiple" defaultValue={['faq1', 'faq3']}>+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="What is XDS?" value="faq1">+ <p {...stylex.props(styles.text)}>+ XDS is a design system for building internal tools and products.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="How do I install it?" value="faq2">+ <p {...stylex.props(styles.text)}>+ Run <code>npm install @xds/core</code> to get started.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Is it open source?" value="faq3">+ <p {...stylex.props(styles.text)}>+ Yes! XDS is open source and available on GitHub.+ </p>+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+ </XDSCollapsibleGroup>+ ),+};++export const Controlled: Story = {+ name: 'Controlled',+ render: function ControlledStory() {+ const [open, setOpen] = useState<string | string[]>('section1');+ return (+ <div>+ <p {...stylex.props(styles.textSecondary)}>+ Currently open: <strong>{String(open) || '(none)'}</strong>+ </p>+ <XDSCollapsibleGroup type="single" value={open} onValueChange={setOpen}>+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="Section 1" value="section1">+ <p {...stylex.props(styles.text)}>Content for section 1.</p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Section 2" value="section2">+ <p {...stylex.props(styles.text)}>Content for section 2.</p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Section 3" value="section3">+ <p {...stylex.props(styles.text)}>Content for section 3.</p>+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+ </XDSCollapsibleGroup>+ </div>+ );+ },+};++export const StandaloneCollapsible: Story = {+ name: 'Standalone Collapsible',+ render: () => (+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="Starts open (default)">+ <p {...stylex.props(styles.text)}>+ This collapsible manages its own state. Click the trigger to toggle.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Starts collapsed" initialIsOpen={false}>+ <p {...stylex.props(styles.text)}>+ This collapsible starts collapsed. Click to reveal.+ </p>+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+ ),+};++export const WithoutCard: Story = {+ name: 'Without Card (standalone)',+ render: () => (+ <XDSVStack gap="space2">+ <XDSCollapsible trigger="Show more details">+ <p {...stylex.props(styles.text)}>+ XDSCollapsible works anywhere — it doesn't require a card wrapper.+ </p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Another section" initialIsOpen={false}>+ <p {...stylex.props(styles.text)}>This section starts collapsed.</p>+ </XDSCollapsible>+ </XDSVStack>+ ),+};++export const FAQ: Story = {+ name: 'FAQ Page',+ render: () => (+ <XDSCollapsibleGroup type="single">+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="How do I reset my password?" value="q1">+ <p {...stylex.props(styles.text)}>+ Go to Settings → Security → Change Password. You'll receive a+ confirmation email.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Can I change my username?" value="q2">+ <p {...stylex.props(styles.text)}>+ Usernames can be changed once every 30 days from your profile+ settings.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="How do I delete my account?" value="q3">+ <p {...stylex.props(styles.text)}>+ Account deletion is permanent. Go to Settings → Account → Delete+ Account. Your data will be removed within 30 days.+ </p>+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible+ trigger="What payment methods are accepted?"+ value="q4">+ <p {...stylex.props(styles.text)}>+ We accept Visa, Mastercard, American Express, and PayPal.+ </p>+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+ </XDSCollapsibleGroup>+ ),+};diff --git a/packages/cli/src/commands/component.mjs b/packages/cli/src/commands/component.mjsindex 86c1cc0fc7..0e17458204 100644--- a/packages/cli/src/commands/component.mjs+++ b/packages/cli/src/commands/component.mjs@@ -19,6 +19,7 @@ const DIR_TO_CATEGORY = {// LayoutAspectRatio: 'Layout',Center: 'Layout',+ CollapsibleGroup: 'Layout',Grid: 'Layout',Layout: 'Layout',Stack: 'Layout',@@ -76,7 +77,8 @@ export function discoverComponents(coreDir) {results.push(...collectXDSFiles(path.join(dirPath, entry.name)));} else if (/^XDS[A-Z]\w+\.tsx$/.test(entry.name) &&- !entry.name.includes('.test.')+ !entry.name.includes('.test.') &&+ !entry.name.includes('Context.')) {results.push(entry.name);}diff --git a/packages/core/package.json b/packages/core/package.jsonindex acfc7fea79..f2b6320c4b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -40,6 +40,11 @@"import": "./dist/Card/index.mjs","require": "./dist/Card/index.js"},+ "./CollapsibleGroup": {+ "types": "./dist/CollapsibleGroup/index.d.ts",+ "import": "./dist/CollapsibleGroup/index.mjs",+ "require": "./dist/CollapsibleGroup/index.js"+ },"./Calendar": {"types": "./dist/Calendar/index.d.ts","import": "./dist/Calendar/index.mjs",diff --git a/packages/core/src/Card/README.md b/packages/core/src/Card/README.mdindex 042a0ea6fd..a8981275c8 100644--- a/packages/core/src/Card/README.md+++ b/packages/core/src/Card/README.md@@ -17,6 +17,7 @@ import {XDSCard} from '@xds/core/Card';## Usage```tsx+// Basic card with layout<XDSCard width={400} height={300}><XDSLayoutheader={<XDSLayoutHeader hasDivider>Title</XDSLayoutHeader>}@@ -24,6 +25,34 @@ import {XDSCard} from '@xds/core/Card';footer={<XDSLayoutFooter hasDivider>Actions</XDSLayoutFooter>}/></XDSCard>++// Simple content+<XDSCard>+ <p>Card content with default padding</p>+</XDSCard>++// Collapsible card — compose XDSCollapsible inside+<XDSCard>+ <XDSCollapsible trigger="Details">+ <p>This content can be collapsed</p>+ </XDSCollapsible>+</XDSCard>++// Accordion of cards+<XDSCollapsibleGroup type="single" defaultValue="general">+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="General" value="general">+ <GeneralSettings />+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Advanced" value="advanced">+ <AdvancedSettings />+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+</XDSCollapsibleGroup>```## Props@@ -34,16 +63,9 @@ import {XDSCard} from '@xds/core/Card';| `height` | `SizeValue` | — | Height (number = pixels, string = as-is) || `maxWidth` | `SizeValue` | — | Maximum width || `minHeight` | `SizeValue` | — | Minimum height |-| `children` | `ReactNode` | — | Content (typically XDSLayout) |+| `children` | `ReactNode` | — | Content to render inside the card || `isFullBleed` | `boolean` | `false` | Removes internal padding for edge-to-edge content |-## Types--```tsx-// Size value type - accepts numbers (pixels) or strings (CSS values)-type SizeValue = number | string;-```-## Theming```tsxdiff --git a/packages/core/src/CollapsibleGroup/README.md b/packages/core/src/CollapsibleGroup/README.mdnew file mode 100644index 0000000000..fad399e92e--- /dev/null+++ b/packages/core/src/CollapsibleGroup/README.md@@ -0,0 +1,135 @@+# /packages/core/src/Collapsible++Collapsible content primitive and group coordination.++<!-- SYNC: When files in this directory change, update this document. -->++## Overview++XDSCollapsible is a primitive that makes any content collapsible — a trigger toggles visibility of the content area. It handles state management, accessibility (aria-expanded, keyboard activation), and a chevron indicator.++XDSCollapsibleGroup coordinates multiple XDSCollapsible instances so only one (or multiple) can be open at a time. It renders no wrapper DOM.++## Import++```tsx+import {XDSCollapsible, XDSCollapsibleGroup} from '@xds/core/CollapsibleGroup';+```++## Usage++### Standalone collapsible++```tsx+// Inside a card+<XDSCard>+ <XDSCollapsible trigger="Details">+ <p>This content can be collapsed</p>+ </XDSCollapsible>+</XDSCard>++// Starts collapsed+<XDSCard>+ <XDSCollapsible trigger="Advanced" initialIsOpen={false}>+ <p>Hidden by default</p>+ </XDSCollapsible>+</XDSCard>++// Controlled+<XDSCard>+ <XDSCollapsible trigger="Settings" isOpen={open} onOpenChange={setOpen}>+ <p>Controlled externally</p>+ </XDSCollapsible>+</XDSCard>++// Without a card — works anywhere+<XDSCollapsible trigger="Show more">+ <p>Expandable content</p>+</XDSCollapsible>+```++### Coordinated group (accordion pattern)++```tsx+// Single mode — only one open at a time (FAQ, settings panels)+<XDSCollapsibleGroup type="single" defaultValue="general">+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="General Settings" value="general">+ <GeneralContent />+ </XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Advanced Settings" value="advanced">+ <AdvancedContent />+ </XDSCollapsible>+ </XDSCard>+ </XDSVStack>+</XDSCollapsibleGroup>++// Multiple mode — any number open+<XDSCollapsibleGroup type="multiple" defaultValue={["s1", "s2"]}>+ <XDSVStack gap="space2">+ <XDSCard>+ <XDSCollapsible trigger="Section 1" value="s1">...</XDSCollapsible>+ </XDSCard>+ <XDSCard>+ <XDSCollapsible trigger="Section 2" value="s2">...</XDSCollapsible>+ </XDSCard>+ </XDSVStack>+</XDSCollapsibleGroup>+```++### With Layout (structured header)++```tsx+<XDSCard>+ <XDSCollapsible trigger="Report Details" value="report">+ <XDSLayout+ content={<XDSLayoutContent>Report body</XDSLayoutContent>}+ footer={<XDSLayoutFooter hasDivider>Actions</XDSLayoutFooter>}+ />+ </XDSCollapsible>+</XDSCard>+```++## Props++### XDSCollapsible++| Prop | Type | Default | Description |+| --------------- | --------------------------- | ------- | -------------------------------------------------- |+| `trigger` | `ReactNode` | — | Content shown in the trigger area (always visible) |+| `children` | `ReactNode` | — | Content that collapses/expands |+| `initialIsOpen` | `boolean` | `true` | Initial open state (uncontrolled) |+| `isOpen` | `boolean` | — | Controlled open state |+| `onOpenChange` | `(isOpen: boolean) => void` | — | Callback when open state changes |+| `value` | `string` | — | Identifier for group coordination |++### XDSCollapsibleGroup++| Prop | Type | Default | Description |+| --------------- | ------------------------------------- | ---------- | -------------------------------------- |+| `type` | `"single" \| "multiple"` | `"single"` | Whether one or many items can be open |+| `defaultValue` | `string \| string[]` | — | Default open item(s) — uncontrolled |+| `value` | `string \| string[]` | — | Controlled open item(s) |+| `onValueChange` | `(value: string \| string[]) => void` | — | Callback when open items change |+| `children` | `ReactNode` | — | XDSCollapsible instances to coordinate |++## How It Works++1. XDSCollapsible manages its own open/close state by default+2. When inside an XDSCollapsibleGroup with a `value` prop, it defers to the group+3. XDSCollapsibleGroup provides context with `isOpen(value)` and `toggle(value)` methods+4. The trigger renders as a button with `aria-expanded` and a chevron indicator++## Files++| File | Role | Purpose |+| -------------------------------- | --------- | ------------------------------- |+| `index.ts` | Entry | Exports components, hook, types |+| `XDSCollapsibleGroup.tsx` | Component | Collapsible group provider |+| `XDSCollapsibleGroupContext.tsx` | Context | React context definition |+| `useXDSCollapsible.ts` | Hook | Collapsible state management |+| `XDSCollapsibleGroup.test.tsx` | Tests | Unit tests |+| `README.md` | Docs | This documentation |diff --git a/packages/core/src/CollapsibleGroup/XDSCollapsible.tsx b/packages/core/src/CollapsibleGroup/XDSCollapsible.tsxnew file mode 100644index 0000000000..7eea603efa--- /dev/null+++ b/packages/core/src/CollapsibleGroup/XDSCollapsible.tsx@@ -0,0 +1,208 @@+/**+ * @file XDSCollapsible.tsx+ * @input Uses React, StyleX, useXDSCollapsible hook, useXDSIcon, theme tokens+ * @output Exports XDSCollapsible component and XDSCollapsibleProps+ * @position Collapsible content primitive — trigger toggles visibility of children+ *+ * XDSCollapsible is a standalone primitive that makes any content collapsible.+ * It renders a trigger area (always visible) and a content area that toggles.+ * Handles state management, accessibility (aria-expanded), and chevron indicator.+ *+ * Works standalone or coordinated by XDSCollapsibleGroup via the `value` prop.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/CollapsibleGroup/index.ts (exports)+ * - /packages/core/src/CollapsibleGroup/README.md+ * - /apps/storybook/stories/CollapsibleGroup.stories.tsx+ */++'use client';++import {forwardRef, type ReactNode} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ typographyVars,+ fontWeightVars,+ spacingVars,+} from '../theme/tokens.stylex';+import {useXDSCollapsible} from './useXDSCollapsible';+import {useXDSIcon} from '../Icon/IconRegistry';++const styles = stylex.create({+ // Trigger button — full width, flex row, no browser button styling+ trigger: {+ all: 'unset',+ boxSizing: 'border-box',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ width: '100%',+ cursor: 'pointer',+ fontFamily: typographyVars['--font-body'],+ fontSize: 16,+ fontWeight: fontWeightVars['--font-weight-semibold'],+ color: colorVars['--color-text-primary'],+ textAlign: 'start',+ paddingBlock: spacingVars['--spacing-1'],+ },+ // Chevron indicator+ chevron: {+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexShrink: 0,+ transition: 'transform 150ms ease',+ color: colorVars['--color-icon-secondary'],+ },+ chevronOpen: {+ transform: 'rotate(0deg)',+ },+ chevronClosed: {+ transform: 'rotate(-90deg)',+ },+ // Content area+ contentHidden: {+ display: 'none',+ },+ content: {+ paddingBlockStart: spacingVars['--spacing-1'],+ },+});++export interface XDSCollapsibleProps {+ /**+ * Content shown in the trigger area (always visible).+ * Rendered inside a button with aria-expanded and a chevron indicator.+ */+ trigger: ReactNode;++ /**+ * Content that collapses/expands when the trigger is clicked.+ */+ children?: ReactNode;++ /**+ * Initial open state for uncontrolled usage.+ * @default true+ */+ initialIsOpen?: boolean;++ /**+ * Controlled open state. When provided, the component is fully controlled.+ */+ isOpen?: boolean;++ /**+ * Callback when the open state changes.+ */+ onOpenChange?: (isOpen: boolean) => void;++ /**+ * Unique identifier for this collapsible within an XDSCollapsibleGroup.+ * Required when using inside a group for coordination.+ */+ value?: string;++ /**+ * Test ID for the collapsible element.+ */+ 'data-testid'?: string;+}++/**+ * A primitive that makes any content collapsible.+ *+ * Renders a trigger area (always visible) with a chevron indicator,+ * and a content area that toggles visibility on click.+ * Handles its own state by default, or defers to XDSCollapsibleGroup+ * when a `value` prop is provided and a group is present.+ *+ * @compositionHint Use inside XDSCard for elevated collapsible sections.+ * Wrap multiple instances in XDSCollapsibleGroup for accordion behavior.+ *+ * @example+ * ```tsx+ * // Standalone+ * <XDSCollapsible trigger="Details">+ * <p>Collapsible content</p>+ * </XDSCollapsible>+ *+ * // Inside a card+ * <XDSCard>+ * <XDSCollapsible trigger="Settings">+ * <SettingsForm />+ * </XDSCollapsible>+ * </XDSCard>+ *+ * // Accordion (coordinated group)+ * <XDSCollapsibleGroup type="single" defaultValue="general">+ * <XDSVStack gap="space2">+ * <XDSCard>+ * <XDSCollapsible trigger="General" value="general">+ * <GeneralSettings />+ * </XDSCollapsible>+ * </XDSCard>+ * <XDSCard>+ * <XDSCollapsible trigger="Advanced" value="advanced">+ * <AdvancedSettings />+ * </XDSCollapsible>+ * </XDSCard>+ * </XDSVStack>+ * </XDSCollapsibleGroup>+ * ```+ */+export const XDSCollapsible = forwardRef<HTMLDivElement, XDSCollapsibleProps>(+ function XDSCollapsible(+ {+ trigger,+ children,+ initialIsOpen,+ isOpen: controlledIsOpen,+ onOpenChange,+ value,+ ...props+ },+ ref,+ ) {+ // Build the config for the hook+ const collapsibleConfig =+ controlledIsOpen !== undefined+ ? {isOpen: controlledIsOpen, onOpenChange}+ : {initialIsOpen: initialIsOpen ?? true, onOpenChange};++ const {isOpen, toggle} = useXDSCollapsible({+ isCollapsible: collapsibleConfig,+ value,+ });++ const chevronIcon = useXDSIcon('chevronDown');++ return (+ <div ref={ref} {...props}>+ <button+ type="button"+ onClick={toggle}+ aria-expanded={isOpen}+ {...stylex.props(styles.trigger)}>+ <span>{trigger}</span>+ <span+ {...stylex.props(+ styles.chevron,+ isOpen ? styles.chevronOpen : styles.chevronClosed,+ )}>+ {chevronIcon}+ </span>+ </button>+ <div+ {...(isOpen+ ? stylex.props(styles.content)+ : stylex.props(styles.content, styles.contentHidden))}>+ {children}+ </div>+ </div>+ );+ },+);++XDSCollapsible.displayName = 'XDSCollapsible';diff --git a/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.test.tsx b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.test.tsxnew file mode 100644index 0000000000..898f4ff49a--- /dev/null+++ b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.test.tsx@@ -0,0 +1,404 @@+/**+ * @file XDSCollapsibleGroup.test.tsx+ * @input Uses vitest, @testing-library/react, XDSCollapsible, XDSCollapsibleGroup+ * @output Unit tests for XDSCollapsible and XDSCollapsibleGroup+ * @position Testing; validates collapsible primitive and group coordination+ *+ * SYNC: When XDSCollapsible.tsx or XDSCollapsibleGroup.tsx changes, update tests+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSCollapsible} from './XDSCollapsible';+import {XDSCollapsibleGroup} from './XDSCollapsibleGroup';++// =============================================================================+// XDSCollapsible — standalone behavior+// =============================================================================++describe('XDSCollapsible', () => {+ it('renders trigger and children', () => {+ render(+ <XDSCollapsible trigger="My Trigger">+ <p>Content</p>+ </XDSCollapsible>,+ );+ expect(screen.getByText('My Trigger')).toBeInTheDocument();+ expect(screen.getByText('Content')).toBeInTheDocument();+ });++ it('starts open by default', () => {+ render(+ <XDSCollapsible trigger="Details">+ <p>Visible content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Details/});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Visible content')).toBeVisible();+ });++ it('toggles content on click', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsible trigger="Details">+ <p>Collapsible content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Details/});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Collapsible content')).toBeVisible();++ // Click to collapse+ await user.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.getByText('Collapsible content')).not.toBeVisible();++ // Click to expand+ await user.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Collapsible content')).toBeVisible();+ });++ it('starts collapsed when initialIsOpen is false', () => {+ render(+ <XDSCollapsible trigger="Details" initialIsOpen={false}>+ <p>Hidden content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Details/});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.getByText('Hidden content')).not.toBeVisible();+ });++ it('respects controlled isOpen/onOpenChange', async () => {+ const onOpenChange = vi.fn();+ const user = userEvent.setup();++ const {rerender} = render(+ <XDSCollapsible+ trigger="Controlled"+ isOpen={true}+ onOpenChange={onOpenChange}>+ <p>Controlled content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Controlled/});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Controlled content')).toBeVisible();++ // Click should call onOpenChange, not change internal state+ await user.click(trigger);+ expect(onOpenChange).toHaveBeenCalledWith(false);++ // Rerender with isOpen=false to actually close+ rerender(+ <XDSCollapsible+ trigger="Controlled"+ isOpen={false}+ onOpenChange={onOpenChange}>+ <p>Controlled content</p>+ </XDSCollapsible>,+ );+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.getByText('Controlled content')).not.toBeVisible();+ });++ it('renders chevron indicator', () => {+ render(+ <XDSCollapsible trigger="With Chevron">+ <p>Content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /With Chevron/});+ const svg = trigger.querySelector('svg');+ expect(svg).toBeInTheDocument();+ expect(svg).toHaveAttribute('aria-hidden');+ });++ it('activates via keyboard (Enter and Space)', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsible trigger="Keyboard">+ <p>Content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Keyboard/});+ trigger.focus();++ // Enter key+ await user.keyboard('{Enter}');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');++ // Space key+ await user.keyboard(' ');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });+});++// =============================================================================+// XDSCollapsibleGroup — coordination context+// =============================================================================++describe('XDSCollapsibleGroup', () => {+ it('renders children without wrapper DOM', () => {+ render(+ <XDSCollapsibleGroup>+ <XDSCollapsible trigger="Item 1" value="1">+ <p>Content 1</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content 1')).toBeInTheDocument();+ });++ describe('single mode', () => {+ it('only allows one item open at a time', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsibleGroup type="single" defaultValue="a">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item C" value="c">+ <p>Content C</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ // A starts open+ expect(screen.getByText('Content A')).toBeVisible();+ expect(screen.getByText('Content B')).not.toBeVisible();+ expect(screen.getByText('Content C')).not.toBeVisible();++ // Open B — A should close+ await user.click(screen.getByRole('button', {name: /Item B/}));+ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();+ expect(screen.getByText('Content C')).not.toBeVisible();++ // Open C — B should close+ await user.click(screen.getByRole('button', {name: /Item C/}));+ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).not.toBeVisible();+ expect(screen.getByText('Content C')).toBeVisible();+ });++ it('closes the open item when clicking it again', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsibleGroup type="single" defaultValue="a">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content A')).toBeVisible();+ await user.click(screen.getByRole('button', {name: /Item A/}));+ expect(screen.getByText('Content A')).not.toBeVisible();+ });+ });++ describe('multiple mode', () => {+ it('allows multiple items to be open simultaneously', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsibleGroup type="multiple" defaultValue={['a']}>+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content A')).toBeVisible();+ expect(screen.getByText('Content B')).not.toBeVisible();++ // Open B — A should stay open+ await user.click(screen.getByRole('button', {name: /Item B/}));+ expect(screen.getByText('Content A')).toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();++ // Close A — B should stay open+ await user.click(screen.getByRole('button', {name: /Item A/}));+ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();+ });+ });++ describe('controlled mode', () => {+ it('respects value and onValueChange', async () => {+ const onValueChange = vi.fn();+ const user = userEvent.setup();++ const {rerender} = render(+ <XDSCollapsibleGroup+ type="single"+ value="a"+ onValueChange={onValueChange}>+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content A')).toBeVisible();+ expect(screen.getByText('Content B')).not.toBeVisible();++ // Click B — should call onValueChange+ await user.click(screen.getByRole('button', {name: /Item B/}));+ expect(onValueChange).toHaveBeenCalledWith('b');++ // Rerender with new value+ rerender(+ <XDSCollapsibleGroup+ type="single"+ value="b"+ onValueChange={onValueChange}>+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );+ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();+ });+ });++ describe('defaultValue', () => {+ it('opens the specified item by default', () => {+ render(+ <XDSCollapsibleGroup defaultValue="b">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();+ });++ it('opens multiple items by default in multiple mode', () => {+ render(+ <XDSCollapsibleGroup type="multiple" defaultValue={['a', 'c']}>+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item C" value="c">+ <p>Content C</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByText('Content A')).toBeVisible();+ expect(screen.getByText('Content B')).not.toBeVisible();+ expect(screen.getByText('Content C')).toBeVisible();+ });+ });++ describe('standalone vs group', () => {+ it('collapsible inside group defers to group context', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsibleGroup type="single" defaultValue="a">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ // Opening B should close A (group coordinates)+ await user.click(screen.getByRole('button', {name: /Item B/}));+ expect(screen.getByText('Content A')).not.toBeVisible();+ expect(screen.getByText('Content B')).toBeVisible();+ });++ it('collapsible outside group manages its own state', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsible trigger="Standalone">+ <p>Standalone content</p>+ </XDSCollapsible>,+ );++ const trigger = screen.getByRole('button', {name: /Standalone/});+ expect(screen.getByText('Standalone content')).toBeVisible();++ await user.click(trigger);+ expect(screen.getByText('Standalone content')).not.toBeVisible();++ await user.click(trigger);+ expect(screen.getByText('Standalone content')).toBeVisible();+ });+ });++ describe('accessibility', () => {+ it('sets aria-expanded on triggers', () => {+ render(+ <XDSCollapsibleGroup type="single" defaultValue="a">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ <XDSCollapsible trigger="Item B" value="b">+ <p>Content B</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ expect(screen.getByRole('button', {name: /Item A/})).toHaveAttribute(+ 'aria-expanded',+ 'true',+ );+ expect(screen.getByRole('button', {name: /Item B/})).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ });++ it('supports keyboard activation', async () => {+ const user = userEvent.setup();+ render(+ <XDSCollapsibleGroup type="single">+ <XDSCollapsible trigger="Item A" value="a">+ <p>Content A</p>+ </XDSCollapsible>+ </XDSCollapsibleGroup>,+ );++ const trigger = screen.getByRole('button', {name: /Item A/});+ trigger.focus();+ await user.keyboard('{Enter}');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ });+ });+});diff --git a/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.tsx b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.tsxnew file mode 100644index 0000000000..bf68f58179--- /dev/null+++ b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.tsx@@ -0,0 +1,174 @@+/**+ * @file XDSCollapsibleGroup.tsx+ * @input Uses React useState, useCallback, CollapsibleGroupContext+ * @output Exports XDSCollapsibleGroup component and XDSCollapsibleGroupProps+ * @position Core collapsible group coordination provider — renders no wrapper DOM+ *+ * XDSCollapsibleGroup groups collapsible components (XDSCard, etc.) with+ * coordinated open/close behavior. It renders only `{children}` — no wrapper+ * DOM element.+ *+ * In "single" mode (default), only one item can be open at a time.+ * In "multiple" mode, any number of items can be open simultaneously.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/CollapsibleGroup/XDSCollapsibleGroupContext.tsx (context type)+ * - /packages/core/src/CollapsibleGroup/README.md+ * - /packages/core/src/CollapsibleGroup/index.ts (exports)+ * - /apps/storybook/stories/CollapsibleGroup.stories.tsx+ */++'use client';++import {useCallback, useMemo, useState, type ReactNode} from 'react';+import {CollapsibleGroupContext} from './XDSCollapsibleGroupContext';+import type {CollapsibleGroupContextValue} from './XDSCollapsibleGroupContext';++export interface XDSCollapsibleGroupProps {+ /**+ * Whether only one item can be open at a time, or multiple.+ * @default "single"+ */+ type?: 'single' | 'multiple';++ /**+ * Default open item(s) — uncontrolled mode.+ * Use a string for single mode, string[] for multiple mode.+ */+ defaultValue?: string | string[];++ /**+ * Controlled open item(s).+ * When provided, the group is fully controlled externally.+ */+ value?: string | string[];++ /**+ * Callback when the open item(s) change.+ */+ onValueChange?: (value: string | string[]) => void;++ /**+ * Children — any components that support isCollapsible + value.+ *+ * @compositionHint Wrap XDSCollapsible instances (typically inside XDSCard).+ * Each XDSCollapsible needs a `value` prop to participate in the group.+ *+ * @example+ * ```tsx+ * <XDSCollapsibleGroup type="single" defaultValue="general">+ * <XDSVStack gap="space2">+ * <XDSCard>+ * <XDSCollapsible trigger="General" value="general">+ * <p>General settings content</p>+ * </XDSCollapsible>+ * </XDSCard>+ * <XDSCard>+ * <XDSCollapsible trigger="Advanced" value="advanced">+ * <p>Advanced settings content</p>+ * </XDSCollapsible>+ * </XDSCard>+ * </XDSVStack>+ * </XDSCollapsibleGroup>+ * ```+ */+ children: ReactNode;+}++function normalizeToArray(value: string | string[] | undefined): string[] {+ if (value == null) return [];+ return Array.isArray(value) ? value : [value];+}++/**+ * Groups collapsible components with coordinated open/close behavior.+ * Renders no wrapper DOM.+ *+ * In "single" mode (default), opening one item closes the others.+ * In "multiple" mode, items toggle independently.+ *+ * @compositionHint Wrap XDSCollapsible instances to coordinate their open/close state.+ * Each XDSCollapsible needs a `value` prop to participate.+ *+ * @example+ * ```tsx+ * <XDSCollapsibleGroup type="single" defaultValue="faq1">+ * <XDSVStack gap="space2">+ * <XDSCard>+ * <XDSCollapsible trigger="What is XDS?" value="faq1">+ * XDS is a design system for building internal tools.+ * </XDSCollapsible>+ * </XDSCard>+ * <XDSCard>+ * <XDSCollapsible trigger="How do I start?" value="faq2">+ * Install the package and import components.+ * </XDSCollapsible>+ * </XDSCard>+ * </XDSVStack>+ * </XDSCollapsibleGroup>+ * ```+ */+export function XDSCollapsibleGroup({+ type = 'single',+ defaultValue,+ value: controlledValue,+ onValueChange,+ children,+}: XDSCollapsibleGroupProps) {+ const isControlled = controlledValue !== undefined;+ const [internalValue, setInternalValue] = useState<string[]>(() =>+ normalizeToArray(defaultValue),+ );++ const openValues = isControlled+ ? normalizeToArray(controlledValue)+ : internalValue;++ const isOpen = useCallback(+ (itemValue: string) => openValues.includes(itemValue),+ [openValues],+ );++ const toggle = useCallback(+ (itemValue: string) => {+ let nextValues: string[];++ if (type === 'single') {+ // In single mode, toggling an open item closes it; toggling a closed item opens it (and closes others)+ nextValues = openValues.includes(itemValue) ? [] : [itemValue];+ } else {+ // In multiple mode, toggle the item independently+ nextValues = openValues.includes(itemValue)+ ? openValues.filter(v => v !== itemValue)+ : [...openValues, itemValue];+ }++ if (!isControlled) {+ setInternalValue(nextValues);+ }++ if (onValueChange) {+ // Return the value in the same shape as the type suggests+ if (type === 'single') {+ onValueChange(nextValues[0] ?? '');+ } else {+ onValueChange(nextValues);+ }+ }+ },+ [type, openValues, isControlled, onValueChange],+ );++ const contextValue = useMemo<CollapsibleGroupContextValue>(+ () => ({isOpen, toggle}),+ [isOpen, toggle],+ );++ return (+ <CollapsibleGroupContext.Provider value={contextValue}>+ {children}+ </CollapsibleGroupContext.Provider>+ );+}++XDSCollapsibleGroup.displayName = 'XDSCollapsibleGroup';diff --git a/packages/core/src/CollapsibleGroup/XDSCollapsibleGroupContext.tsx b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroupContext.tsxnew file mode 100644index 0000000000..98f3e91b8a--- /dev/null+++ b/packages/core/src/CollapsibleGroup/XDSCollapsibleGroupContext.tsx@@ -0,0 +1,29 @@+/**+ * @file XDSCollapsibleGroupContext.tsx+ * @input Uses React createContext+ * @output Exports CollapsibleGroupContext and CollapsibleGroupContextValue type+ * @position Context definition for collapsible group coordination+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/CollapsibleGroup/XDSCollapsibleGroup.tsx (provider)+ * - /packages/core/src/CollapsibleGroup/README.md+ */++import {createContext} from 'react';++/**+ * Context value provided by XDSCollapsibleGroup to coordinate collapsible children.+ */+export interface CollapsibleGroupContextValue {+ /** Check if a given value is currently open. */+ isOpen: (value: string) => boolean;+ /** Toggle the open state of a given value. */+ toggle: (value: string) => void;+}++/**+ * Context for collapsible group coordination.+ * When present, collapsible components defer their open/close state to the group.+ */+export const CollapsibleGroupContext =+ createContext<CollapsibleGroupContextValue | null>(null);diff --git a/packages/core/src/CollapsibleGroup/index.ts b/packages/core/src/CollapsibleGroup/index.tsnew file mode 100644index 0000000000..21369d44a4--- /dev/null+++ b/packages/core/src/CollapsibleGroup/index.ts@@ -0,0 +1,21 @@+/**+ * @file index.ts+ * @input Imports XDSCollapsible, XDSCollapsibleGroup, and useXDSCollapsible+ * @output Exports components, hook, and types+ * @position Entry point for @xds/core/CollapsibleGroup module+ *+ * SYNC: When modified, update /packages/core/src/CollapsibleGroup/README.md+ */++export {XDSCollapsible} from './XDSCollapsible';+export type {XDSCollapsibleProps} from './XDSCollapsible';++export {XDSCollapsibleGroup} from './XDSCollapsibleGroup';+export type {XDSCollapsibleGroupProps} from './XDSCollapsibleGroup';++export {useXDSCollapsible} from './useXDSCollapsible';+export type {+ CollapsibleConfig,+ UseXDSCollapsibleOptions,+ UseXDSCollapsibleReturn,+} from './useXDSCollapsible';diff --git a/packages/core/src/CollapsibleGroup/useXDSCollapsible.ts b/packages/core/src/CollapsibleGroup/useXDSCollapsible.tsnew file mode 100644index 0000000000..7586546c80--- /dev/null+++ b/packages/core/src/CollapsibleGroup/useXDSCollapsible.ts@@ -0,0 +1,118 @@+/**+ * @file useXDSCollapsible.ts+ * @input Uses React useState/useContext, CollapsibleGroupContext+ * @output Exports useXDSCollapsible hook, CollapsibleConfig, UseXDSCollapsibleOptions, UseXDSCollapsibleReturn types+ * @position Reusable hook for collapsible behavior — used by XDSCard, XDSSection, etc.+ *+ * Encapsulates the full collapsible state machine:+ * - Parsing boolean | config into normalized config+ * - Checking for CollapsibleGroup context (group-controlled mode)+ * - Managing internal state for uncontrolled mode+ * - Providing a unified toggle handler+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/CollapsibleGroup/index.ts (exports)+ * - /packages/core/src/CollapsibleGroup/README.md+ *+ * NOTE: Public hooks use the `useXDS` prefix per XDS naming conventions.+ */++import {useState, useContext} from 'react';+import {CollapsibleGroupContext} from './XDSCollapsibleGroupContext';++/**+ * Configuration for collapsible behavior.+ */+export type CollapsibleConfig = {+ /** Whether the component starts open. @default true */+ initialIsOpen?: boolean;+ /** Controlled open state. */+ isOpen?: boolean;+ /** Callback when open state changes. */+ onOpenChange?: (isOpen: boolean) => void;+};++export interface UseXDSCollapsibleOptions {+ /**+ * Whether the component is collapsible.+ * - `true` — self-managed, starts open+ * - `{ initialIsOpen: false }` — self-managed, starts collapsed+ * - `{ isOpen, onOpenChange }` — controlled externally+ */+ isCollapsible?: boolean | CollapsibleConfig;+ /**+ * Unique identifier within an XDSCollapsibleGroup.+ * When present and inside a group, defers state to the group.+ */+ value?: string;+}++export interface UseXDSCollapsibleReturn {+ /** Whether collapsible behavior is enabled. */+ isEnabled: boolean;+ /** Whether the content is currently open/expanded. */+ isOpen: boolean;+ /** Toggle the open/closed state. */+ toggle: () => void;+}++/**+ * Hook that encapsulates collapsible state management.+ *+ * Supports three modes:+ * 1. **Group-controlled**: When inside a CollapsibleGroup with a `value`, defers to group.+ * 2. **Controlled**: When `isOpen` and `onOpenChange` are provided in config.+ * 3. **Uncontrolled**: Self-managed internal state with optional `initialIsOpen`.+ *+ * @example+ * ```tsx+ * const {isEnabled, isOpen, toggle} = useXDSCollapsible({+ * isCollapsible: true,+ * value: 'section-1',+ * });+ * ```+ */+export function useXDSCollapsible(+ options: UseXDSCollapsibleOptions,+): UseXDSCollapsibleReturn {+ const {isCollapsible, value} = options;++ // Check for CollapsibleGroup context+ const group = useContext(CollapsibleGroupContext);+ const isControlledByGroup = group != null && value != null;++ // Parse config: true → empty config, object → as-is, false/undefined → null+ const config: CollapsibleConfig | null =+ isCollapsible === true ? {} : isCollapsible ? isCollapsible : null;+ const isEnabled = config != null;++ // Internal state for uncontrolled mode+ const [internalIsOpen, setInternalIsOpen] = useState(() => {+ if (isControlledByGroup) return true; // group manages this+ if (config?.isOpen !== undefined) return config.isOpen;+ return config?.initialIsOpen ?? true;+ });++ // Determine open state from the appropriate source+ let isOpen: boolean;+ if (isControlledByGroup) {+ isOpen = group.isOpen(value!);+ } else if (config?.isOpen !== undefined) {+ isOpen = config.isOpen;+ } else {+ isOpen = internalIsOpen;+ }++ // Toggle handler dispatches to the appropriate controller+ const toggle = () => {+ if (isControlledByGroup) {+ group.toggle(value!);+ } else if (config?.onOpenChange) {+ config.onOpenChange(!isOpen);+ } else {+ setInternalIsOpen(prev => !prev);+ }+ };++ return {isEnabled, isOpen, toggle};+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 1b7abeb9c5..4c0942e2cd 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -8,6 +8,7 @@*/// Components+export * from './CollapsibleGroup';export * from './AppShell';export * from './AspectRatio';export * from './Avatar';