Skip to content

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

TypeScript

XDSDatePicker with useXDSPopover (#66)

Cindy Zhang8f3999a1f2d0
diff --git a/.context/proposals/xds-calendar.md b/.context/proposals/xds-calendar.md
deleted file mode 100644
index d5ae1ac898..0000000000
--- a/.context/proposals/xds-calendar.md
+++ /dev/null
@@ -1,677 +0,0 @@
-# XDSCalendar Component Proposal
-
-## Status
-
-Proposed
-
-## Context
-
-We have an existing `XDSCalendar` implementation as a web component (custom element with Shadow DOM). This component needs to be adapted to conform to the XDS React + StyleX architecture before integration.
-
-The calendar will eventually be used within an `XDSDatePicker` component that combines a text input with a popover calendar.
-
-### Current Implementation (Web Component)
-
-- Custom element extending `HTMLElement`
-- Shadow DOM encapsulation
-- Raw CSS with `@layer xds` and CSS custom properties
-- Static stylesheet caching
-- Attributes: `value`, `min`, `max`
-- Month navigation with slide animations
-- 6-row grid (42 cells) for consistent height
-
-## Proposal
-
-Convert `XDSCalendar` to a React component following XDS patterns.
-
-### File Structure
-
-```
-packages/core/src/Calendar/
-├── XDSCalendar.tsx # Main component
-├── XDSCalendar.test.tsx # Unit tests
-├── README.md # Component documentation
-└── index.ts # Exports
-```
-
-### Component API
-
-#### ISO String Type System
-
-All XDS date/time components use ISO 8601 string formats for values. This provides consistency, JSON serialization, and explicit timezone handling.
-
-```typescript
-// ─── Date (timezone-naive) ───────────────────────────────────
-// Use for: calendars, birthdays, holidays, date pickers
-type ISODateString =
- `${number}${number}${number}${number}-${number}${number}-${number}${number}`;
-// Example: "2026-01-28"
-
-// ─── Time (timezone-naive) ───────────────────────────────────
-// Use for: time inputs, store hours, alarms
-type ISOTimeString = `${number}${number}:${number}${number}`;
-// Example: "14:30"
-
-// ─── DateTime (timezone-required) ────────────────────────────
-// Use for: scheduling, meetings, events
-type ISOZonedDateTimeString = string;
-// Example: "2026-01-28T14:30:00-08:00" or "2026-01-28T14:30:00Z"
-
-// ─── Ranges ──────────────────────────────────────────────────
-interface DateRange {
- start: ISODateString;
- end: ISODateString; // When awaiting end selection, equals start
-}
-
-interface DateTimeRange {
- start: ISOZonedDateTimeString;
- end: ISOZonedDateTimeString;
-}
-```
-
-**Component Value Types:**
-
-| Component | Value Type | Timezone |
-| -------------------------- | ------------------------ | -------- |
-| `XDSCalendar` | `ISODateString` | Naive |
-| `XDSTimeInput` | `ISOTimeString` | Naive |
-| `XDSDatePicker` | `ISODateString` | Naive |
-| `XDSDateTimePicker` | `ISOZonedDateTimeString` | Required |
-| `XDSCalendar mode="range"` | `DateRange` | Naive |
-
-**Why ISO strings over Date objects:**
-
-- `Date` is always a timestamp, not a calendar date
-- `new Date("2026-01-28")` parses as UTC midnight, causing off-by-one bugs in other timezones
-- ISO strings are unambiguous and JSON-serializable
-- Timezone handling is explicit, not implicit
-
-#### Calendar Props
-
-```typescript
-/** Day of week: 0 = Sunday through 6 = Saturday */
-type DayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
-
-// ─── Base Props (shared across all modes) ─────────────────────
-
-interface XDSCalendarBaseProps {
- // ─── Multi-Month ───────────────────────────────────────────
- /** Number of months to display (default: 1) */
- numberOfMonths?: 1 | 2;
-
- // ─── Date Constraints ──────────────────────────────────────
- /** Minimum selectable date in ISO format */
- min?: ISODateString;
-
- /** Maximum selectable date in ISO format */
- max?: ISODateString;
-
- /**
- * Custom date constraint functions. Date is disabled if ANY function returns false.
- * Use for complex rules like "weekdays only" or "no holidays".
- */
- dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
-
- // ─── Navigation ────────────────────────────────────────────
- /**
- * Controlled focus date (which month is visible).
- * If not provided, defaults to selected date or today.
- */
- focusDate?: ISODateString;
-
- /** Callback when visible month changes via navigation */
- onFocusDateChange?: (focusDate: ISODateString) => void;
-
- // ─── Display Options ───────────────────────────────────────
- /**
- * Show days from adjacent months (grayed out).
- * Default: true
- */
- hasOutsideDays?: boolean;
-
- /**
- * Show ISO week numbers in a side column.
- * Default: false
- */
- hasWeekNumbers?: boolean;
-
- /**
- * Use variable rows per month vs. fixed 6-row grid.
- * Default: false (fixed 6 rows for consistent height)
- */
- hasVariableRowCount?: boolean;
-
- /**
- * First day of week.
- * Default: 0 (Sunday)
- */
- weekStartsOn?: DayOfWeek;
-}
-
-// ─── Mode-specific Props (discriminated union) ────────────────
-
-interface XDSCalendarSingleProps extends XDSCalendarBaseProps {
- /** Selection mode */
- mode?: 'single';
-
- /** Selected date in ISO format (YYYY-MM-DD) */
- value?: ISODateString;
-
- /** Default value for uncontrolled mode */
- defaultValue?: ISODateString;
-
- /** Callback when date is selected */
- onChange?: (value: ISODateString, valueAsDate: Date) => void;
-}
-
-interface XDSCalendarRangeProps extends XDSCalendarBaseProps {
- /** Selection mode */
- mode: 'range';
-
- /** Selected date range */
- value?: DateRange;
-
- /** Default value for uncontrolled mode */
- defaultValue?: DateRange;
-
- /** Callback when range is selected */
- onChange?: (value: DateRange) => void;
-}
-
-export type XDSCalendarProps = XDSCalendarSingleProps | XDSCalendarRangeProps;
-
-export const XDSCalendar: React.FC<XDSCalendarProps>;
-
-// Export types for consumers
-export type {ISODateString, DayOfWeek, DateRange};
-```
-
-### Usage Examples
-
-```typescript
-// Single date selection (default mode)
-<XDSCalendar
- value="2026-01-28"
- onChange={(value, valueAsDate) => console.log(value)}
-/>
-
-// Explicit single mode
-<XDSCalendar
- mode="single"
- value="2026-01-28"
- onChange={(value, valueAsDate) => console.log(value)}
-/>
-
-// Range selection
-<XDSCalendar
- mode="range"
- value={{ start: "2026-01-28", end: "2026-02-05" }}
- onChange={(range) => console.log(range.start, range.end)}
-/>
-```
-
-### Type Safety
-
-The discriminated union ensures type safety at compile time:
-
-```typescript
-// ✓ Correct: single mode with ISODateString
-<XDSCalendar mode="single" value="2026-01-28" />
-
-// ✓ Correct: range mode with DateRange
-<XDSCalendar mode="range" value={{ start: "2026-01-28", end: "2026-02-05" }} />
-
-// ✗ Error: range mode requires DateRange, not string
-<XDSCalendar mode="range" value="2026-01-28" />
-
-// ✗ Error: single mode requires string, not DateRange
-<XDSCalendar mode="single" value={{ start: "2026-01-28", end: "2026-02-05" }} />
-```
-
-### Props Rationale
-
-**Included from internal API:**
-
-- `numberOfMonths` (as `count`) — Limited to 1 | 2 for practical layouts
-- `focusDate` / `onFocusDateChange` — Controlled navigation
-- `hasOutsideDays` (as `hasDaysOutsideOfMonth`) — Common feature
-- `hasVariableRowCount` — Height consistency option
-- `hasWeekNumbers` — Requested feature
-- `weekStartsOn` (as `weekStart`) — Locale flexibility
-
-**Simplified from internal API:**
-
-- `min` / `max` instead of only `dateRestraints` — Simple cases are common
-- Added `dateConstraints` for complex rules — Flexible when needed
-
-**Deferred to future phases:**
-
-- `rangeSelectDate` — Range picker component
-- `selectedWeekStart` / `selectedWeekEnd` — Week selection mode
-- `isPagerLimitRestrained` — Edge case, add if requested
-- `hasDuplicateSelection` — Edge case
-- `isPreviousMonthShownByDefault` — Edge case
-
-### Multi-Month Display
-
-When `numberOfMonths={2}`, the calendar displays two consecutive months side by side.
-
-**Layout Structure**:
-
-```
-┌─────────────────────────────────────────────────────┐
-│ [<] January 2026 • February 2026 [>] │ ← Single header with nav
-├─────────────────────────────────────────────────────┤
-│ Su Mo Tu We Th Fr Sa │ Su Mo Tu We Th Fr Sa │
-│ ──────────────────── │ ──────────────────── │
-│ 1 2 3 4 │ 1 │
-│ 5 6 7 8 9 10 11 │ 2 3 4 5 6 7 8 │
-│ ... │ ... │
-└─────────────────────────────────────────────────────┘
-```
-
-**Key Behaviors**:
-
-- Single set of prev/next arrows in the header
-- Navigation advances all months together (clicking next moves Jan→Feb, Feb→Mar)
-- Header displays all visible month names (e.g., "January 2026 • February 2026")
-- Each month grid is independent but shares the same selection state
-- Animations slide all months together as a unit
-
-**Implementation**:
-
-```typescript
-const XDSCalendar: React.FC<XDSCalendarProps> = ({
- numberOfMonths = 1,
- ...props
-}) => {
- const [baseMonth, setBaseMonth] = useState(() => {
- const date = new Date();
- date.setDate(1);
- return date;
- });
-
- // Generate array of months to display
- const visibleMonths = useMemo(() => {
- return Array.from({ length: numberOfMonths }, (_, i) => {
- const month = new Date(baseMonth);
- month.setMonth(baseMonth.getMonth() + i);
- return month;
- });
- }, [baseMonth, numberOfMonths]);
-
- return (
- <div {...stylex.props(styles.calendar)}>
- <div {...stylex.props(styles.header)}>
- <button onClick={() => navigateMonth(-1)}>←</button>
- <span>{formatMonthRange(visibleMonths)}</span>
- <button onClick={() => navigateMonth(1)}>→</button>
- </div>
- <div {...stylex.props(styles.monthsContainer)}>
- {visibleMonths.map((month, index) => (
- <MonthGrid
- key={month.toISOString()}
- month={month}
- isFirst={index === 0}
- isLast={index === numberOfMonths - 1}
- {...props}
- />
- ))}
- </div>
- </div>
- );
-};
-```
-
-**Styling for Multi-Month**:
-
-```typescript
-const styles = stylex.create({
- monthsContainer: {
- display: 'flex',
- gap: spacingVars['--spacing-4'],
- },
- monthGrid: {
- flex: '1 1 0',
- minWidth: '220px',
- },
-});
-```
-
-### Navigation Buttons
-
-Navigation buttons (prev/next month) should use `XDSButton` directly to ensure consistent styling:
-
-```typescript
-import { XDSButton } from '../Button';
-
-// In render:
-<div {...stylex.props(styles.header)}>
- <XDSButton
- variant="ghost"
- onClick={() => navigateMonth(-1)}
- aria-label="Previous month"
- >
- <ChevronLeftIcon />
- </XDSButton>
-
- <span {...stylex.props(styles.monthYearLabel)}>
- {formatMonthRange(visibleMonths)}
- </span>
-
- <XDSButton
- variant="ghost"
- onClick={() => navigateMonth(1)}
- aria-label="Next month"
- >
- <ChevronRightIcon />
- </XDSButton>
-</div>
-```
-
-**Benefits of using XDSButton:**
-
-- Inherits hover/active/focus states from Button
-- Consistent with theme overrides
-- Accessible focus outline handling
-- No duplicate button styling code
-
-### Key Adaptations
-
-#### 1. React State Instead of DOM Manipulation
-
-```typescript
-// Before (web component)
-this._currentMonth = new Date();
-this._updateCalendar();
-
-// After (React)
-const [currentMonth, setCurrentMonth] = useState(() => {
- const date = new Date();
- date.setDate(1);
- return date;
-});
-```
-
-#### 2. StyleX Instead of Raw CSS
-
-```typescript
-// Before (web component)
-_getStyles() {
- return `
- .xds-calendar { background: var(--color-surface); }
- .xds-calendar-day:hover { background: var(--color-hover-overlay); }
- `;
-}
-
-// After (StyleX with tokens)
-const styles = stylex.create({
- calendar: {
- backgroundColor: colorVars['--color-surface'],
- padding: spacingVars['--spacing-3'],
- minWidth: '220px',
- overflow: 'hidden',
- },
- day: {
- backgroundColor: 'transparent',
- backgroundImage: {
- default: null,
- ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
- },
- },
-});
-```
-
-#### 3. Theme Token Usage
-
-Replace hardcoded CSS variable references with StyleX token imports:
-
-| CSS Variable | StyleX Token |
-| --------------------------- | ------------------------------------- |
-| `var(--color-surface)` | `colorVars['--color-surface']` |
-| `var(--color-text-primary)` | `colorVars['--color-text-primary']` |
-| `var(--color-accent)` | `colorVars['--color-accent']` |
-| `var(--space-3)` | `spacingVars['--spacing-3']` |
-| `var(--radius-rounded)` | `radiusVars['--radius-rounded']` |
-| `var(--transition-fast)` | `transitionVars['--transition-fast']` |
-
-#### 4. Animation Strategy
-
-The original uses CSS keyframe animations for month transitions. Options:
-
-**Option A: Keep CSS Animations (Recommended)**
-
-- Define keyframes with `stylex.keyframes()`
-- Maintain the slide transition UX
-- Zero JS animation overhead
-
-```typescript
-const slideOutLeft = stylex.keyframes({
- from: {transform: 'translateX(0)', opacity: 1},
- to: {transform: 'translateX(-100%)', opacity: 0},
-});
-
-const animationStyles = stylex.create({
- slideLeft: {
- animationName: slideOutLeft,
- animationDuration: '200ms',
- animationTimingFunction: 'ease-out',
- animationFillMode: 'forwards',
- },
-});
-```
-
-**Option B: Remove Animations**
-
-- Simpler implementation
-- Instant month changes
-- Less polished UX
-
-**Recommendation**: Option A — animations are a key UX element for calendar navigation.
-
-#### 5. Controlled vs Uncontrolled
-
-Support both patterns:
-
-```typescript
-interface XDSCalendarProps {
- // Controlled
- value?: string;
- onChange?: (value: string, valueAsDate: Date) => void;
-
- // Uncontrolled
- defaultValue?: string;
-}
-```
-
-#### 6. Accessibility Enhancements
-
-Add missing ARIA attributes:
-
-```typescript
-<div
- role="grid"
- aria-label={`Calendar for ${monthYearLabel}`}
->
- <div role="row">
- {dayNames.map(day => (
- <div role="columnheader" key={day}>{day}</div>
- ))}
- </div>
- {weeks.map((week, i) => (
- <div role="row" key={i}>
- {week.map(day => (
- <button
- role="gridcell"
- aria-selected={isSelected}
- aria-disabled={isDisabled}
- tabIndex={isFocusable ? 0 : -1}
- />
- ))}
- </div>
- ))}
-</div>
-```
-
-Add keyboard navigation:
-
-- Arrow keys for date navigation
-- Enter/Space for selection
-- Home/End for first/last day of week
-- PageUp/PageDown for month navigation
-
-### Variant Support (Future)
-
-Consider theme-level customization via module augmentation:
-
-```typescript
-declare module '../theme/types' {
- interface ComponentStyles {
- calendar?: {
- // Future: size variants, color overrides
- };
- }
-}
-```
-
-For initial implementation, no variants needed — calendar is a utility component.
-
-### Testing Strategy
-
-```typescript
-describe('XDSCalendar', () => {
- // Basic rendering
- it('renders current month by default');
- it('displays correct number of days');
- it('highlights today');
- it('shows selected date');
-
- // Navigation
- it('navigates to previous month');
- it('navigates to next month');
-
- // Constraints
- it('respects min date constraint');
- it('respects max date constraint');
-
- // Events
- it('calls onChange when date selected');
-
- // Accessibility
- it('supports keyboard navigation');
- it('renders accessible grid structure');
-
- // Multi-month
- it('renders multiple months when numberOfMonths > 1');
- it('displays correct month headers for multi-month');
- it('navigation advances all months together');
- it('selection works across multiple month grids');
- it('animations apply to all months as a unit');
-});
-```
-
-### Export Configuration
-
-Add to `packages/core/package.json`:
-
-```json
-{
- "exports": {
- "./Calendar": {
- "types": "./dist/Calendar/index.d.ts",
- "import": "./dist/Calendar/index.mjs",
- "require": "./dist/Calendar/index.js"
- }
- }
-}
-```
-
-Add to `packages/core/src/index.ts`:
-
-```typescript
-export * from './Calendar';
-```
-
-### Storybook Stories
-
-Create `apps/storybook/stories/Calendar.stories.tsx`:
-
-**Single Mode:**
-
-- **Default** — Single month, single selection
-- **With Selected Date**
-- **With Min/Max Constraints**
-- **Two Months** — `numberOfMonths={2}`
-- **With Week Numbers** — `hasWeekNumbers={true}`
-- **Monday Start** — `weekStartsOn={1}`
-
-**Range Mode:**
-
-- **Range Selection** — `mode="range"`
-- **Range Two Months** — `mode="range" numberOfMonths={2}`
-
-**Interactive:**
-
-- **Navigation Demo** — Interactive navigation showcase
-- **Keyboard Navigation** — Focus management demo
-
-## Implementation Phases
-
-### Phase 1: Core Calendar
-
-1. Create file structure
-2. Convert to React component
-3. Implement StyleX styles with tokens
-4. Add basic tests
-5. Create Storybook stories
-
-### Phase 2: Accessibility
-
-1. Add ARIA attributes
-2. Implement keyboard navigation
-3. Add focus management
-4. Test with screen reader
-
-### Phase 3: DatePicker Integration
-
-1. Create `XDSDatePicker` component
-2. Integrate with `XDSField` wrapper
-3. Add popover/dropdown behavior
-4. Handle input parsing and formatting
-
-## Consequences
-
-### Benefits
-
-1. **Consistency** — Follows XDS patterns, uses theme tokens
-2. **Tree-shakeable** — React component with granular exports
-3. **Testable** — React Testing Library patterns
-4. **Themeable** — Automatically respects light/dark mode via tokens
-5. **Type-safe** — Full TypeScript support
-
-### Tradeoffs
-
-1. **Rewrite required** — Can't directly reuse web component code
-2. **Animation complexity** — StyleX keyframes require careful setup
-3. **Bundle size** — React adds overhead vs. native web component
-
-## Open Questions
-
-1. **Responsive behavior** — Should 2-month layout collapse to 1-month on narrow viewports?
-2. **Month header format** — For 2-month, show "January • February" or "January 2026 • February 2026"?
-
-### Resolved
-
-- ~~Locale support / firstDayOfWeek~~ → Added `weekStartsOn` prop with `DayOfWeek` type
-- ~~Week numbers~~ → Added `hasWeekNumbers` prop
-- ~~Max months~~ → Limited to `1 | 2` per internal pattern
-- ~~Date type~~ → Using `ISODateString` template literal type for compile-time validation
-- ~~Range selection API~~ → Using `mode` prop with discriminated union (`'single' | 'range'`)
-- ~~Partial range~~ → When awaiting end selection, `end` equals `start` (single-day range)
-
-## References
-
-- Original web component implementation (provided in conversation)
-- XDS Button implementation: `packages/core/src/Button/XDSButton.tsx`
-- XDS TextInput implementation: `packages/core/src/TextInput/XDSTextInput.tsx`
-- ARIA Date Picker pattern: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/examples/datepicker-dialog/
diff --git a/apps/storybook/stories/DatePicker.stories.tsx b/apps/storybook/stories/DatePicker.stories.tsx
new file mode 100644
index 0000000000..9f10ccd7f1
--- /dev/null
+++ b/apps/storybook/stories/DatePicker.stories.tsx
@@ -0,0 +1,238 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSDatePicker} from '@xds/core/DatePicker';
+import type {ISODateString} from '@xds/core/Calendar';
+
+const meta: Meta<typeof XDSDatePicker> = {
+ title: 'Core/XDSDatePicker',
+ component: XDSDatePicker,
+ tags: ['autodocs'],
+ argTypes: {
+ label: {
+ control: 'text',
+ description: 'Label text (required)',
+ },
+ isLabelHidden: {
+ control: 'boolean',
+ description:
+ 'Visually hide the label (still accessible to screen readers)',
+ },
+ placeholder: {
+ control: 'text',
+ description: 'Placeholder text',
+ },
+ description: {
+ control: 'text',
+ description: 'Description text displayed between the label and input',
+ },
+ isOptional: {
+ control: 'boolean',
+ description:
+ 'Whether the field is optional (mutually exclusive with isRequired)',
+ },
+ isRequired: {
+ control: 'boolean',
+ description:
+ 'Whether the field is required (mutually exclusive with isOptional)',
+ },
+ isDisabled: {
+ control: 'boolean',
+ description: 'Whether the input is disabled',
+ },
+ size: {
+ control: 'radio',
+ options: ['sm', 'md'],
+ description: 'Size of the input',
+ },
+ numberOfMonths: {
+ control: 'radio',
+ options: [1, 2],
+ description: 'Number of months to display in calendar',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSDatePicker>;
+
+export const Default: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Date',
+ placeholder: 'Select a date',
+ },
+};
+
+export const WithValue: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-01-25' as ISODateString,
+ );
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Event date',
+ },
+};
+
+export const WithDescription: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Birthday',
+ description: 'Enter your date of birth',
+ placeholder: 'Select your birthday',
+ },
+};
+
+export const WithHiddenLabel: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Date',
+ isLabelHidden: true,
+ placeholder: 'Select a date',
+ },
+};
+
+export const Optional: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Preferred date',
+ isOptional: true,
+ placeholder: 'Select a date (optional)',
+ },
+};
+
+export const Required: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Start date',
+ isRequired: true,
+ placeholder: 'Select a start date',
+ },
+};
+
+export const Disabled: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-01-25' as ISODateString,
+ );
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Locked date',
+ isDisabled: true,
+ },
+};
+
+export const SmallSize: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Date',
+ size: 'sm',
+ placeholder: 'Select a date',
+ },
+};
+
+export const WithMinMax: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Booking date',
+ min: '2026-01-15' as ISODateString,
+ max: '2026-02-15' as ISODateString,
+ description: 'Available dates: Jan 15 - Feb 15, 2026',
+ placeholder: 'Select a booking date',
+ },
+};
+
+export const TwoMonthCalendar: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(undefined);
+ return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Travel date',
+ numberOfMonths: 2,
+ placeholder: 'Select a travel date',
+ },
+};
+
+export const AllVariations: Story = {
+ render: () => {
+ const [value1, setValue1] = useState<ISODateString | undefined>(undefined);
+ const [value2, setValue2] = useState<ISODateString | undefined>(
+ '2026-01-25' as ISODateString,
+ );
+ const [value3, setValue3] = useState<ISODateString | undefined>(undefined);
+ const [value4, setValue4] = useState<ISODateString | undefined>(undefined);
+ const [value5, setValue5] = useState<ISODateString | undefined>(undefined);
+ const [value6, setValue6] = useState<ISODateString | undefined>(
+ '2026-03-10' as ISODateString,
+ );
+
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '16px',
+ maxWidth: '300px',
+ }}>
+ <XDSDatePicker
+ label="Default"
+ value={value1}
+ onChange={setValue1}
+ placeholder="Select a date"
+ />
+ <XDSDatePicker label="With value" value={value2} onChange={setValue2} />
+ <XDSDatePicker
+ label="With description"
+ description="Pick your preferred date"
+ value={value3}
+ onChange={setValue3}
+ placeholder="Select a date"
+ />
+ <XDSDatePicker
+ label="Optional field"
+ isOptional
+ value={value4}
+ onChange={setValue4}
+ placeholder="Select a date (optional)"
+ />
+ <XDSDatePicker
+ label="Required field"
+ isRequired
+ value={value5}
+ onChange={setValue5}
+ placeholder="Select a date"
+ />
+ <XDSDatePicker
+ label="Disabled"
+ isDisabled
+ value={value6}
+ onChange={setValue6}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index c042f317b8..9b59556c82 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -39,6 +39,11 @@
"import": "./dist/CheckboxInput/index.mjs",
"require": "./dist/CheckboxInput/index.js"
},
+ "./DatePicker": {
+ "types": "./dist/DatePicker/index.d.ts",
+ "import": "./dist/DatePicker/index.mjs",
+ "require": "./dist/DatePicker/index.js"
+ },
"./Field": {
"types": "./dist/Field/index.d.ts",
"import": "./dist/Field/index.mjs",
@@ -89,6 +94,11 @@
"import": "./dist/theme/index.mjs",
"require": "./dist/theme/index.js"
},
+ "./utils": {
+ "types": "./dist/utils/index.d.ts",
+ "import": "./dist/utils/index.mjs",
+ "require": "./dist/utils/index.js"
+ },
"./xds.md": "./xds.md"
},
"scripts": {
diff --git a/packages/core/src/Calendar/XDSCalendar.test.tsx b/packages/core/src/Calendar/XDSCalendar.test.tsx
index 02e91b7ce8..9622ebf95b 100644
--- a/packages/core/src/Calendar/XDSCalendar.test.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.test.tsx
@@ -12,6 +12,16 @@ import {render, screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {XDSCalendar} from './XDSCalendar';
+/**
+ * Helper to find a day button by its day number.
+ * Day buttons have aria-labels like "Thursday, January 15, 2026".
+ */
+function getDayButton(day: number, month = 'January', year = 2026) {
+ // Match the full date pattern with the day number
+ const pattern = new RegExp(`${month}\\s+${day},\\s+${year}`);
+ return screen.getByRole('gridcell', {name: pattern});
+}
+
describe('XDSCalendar', () => {
// ─── Basic Rendering ─────────────────────────────────────────
@@ -53,7 +63,7 @@ describe('XDSCalendar', () => {
it('highlights selected date', () => {
render(<XDSCalendar value="2026-01-15" focusDate="2026-01-01" />);
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ const day15 = getDayButton(15);
expect(day15).toHaveAttribute('aria-selected', 'true');
});
@@ -63,7 +73,7 @@ describe('XDSCalendar', () => {
render(<XDSCalendar onChange={handleChange} focusDate="2026-01-01" />);
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ const day15 = getDayButton(15);
await user.click(day15);
expect(handleChange).toHaveBeenCalledTimes(1);
@@ -122,22 +132,22 @@ describe('XDSCalendar', () => {
it('respects min date constraint', () => {
render(<XDSCalendar focusDate="2026-01-01" min="2026-01-10" />);
- // Find day 5 in current month (not outside day from adjacent month)
- const day5Buttons = screen.getAllByRole('gridcell', {name: '5'});
- const day5 = day5Buttons.find(btn => !btn.className.includes('Outside'));
+ // Day 5 should be disabled (before min)
+ const day5 = getDayButton(5);
expect(day5).toBeDisabled();
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ // Day 15 should be enabled (after min)
+ const day15 = getDayButton(15);
expect(day15).not.toBeDisabled();
});
it('respects max date constraint', () => {
render(<XDSCalendar focusDate="2026-01-01" max="2026-01-20" />);
- const day25 = screen.getByRole('gridcell', {name: '25'});
+ const day25 = getDayButton(25);
expect(day25).toBeDisabled();
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ const day15 = getDayButton(15);
expect(day15).not.toBeDisabled();
});
@@ -152,12 +162,8 @@ describe('XDSCalendar', () => {
<XDSCalendar focusDate="2026-01-01" dateConstraints={[isWeekday]} />,
);
- // January 4, 2026 is a Sunday
- const sundayButtons = screen.getAllByRole('gridcell', {name: '4'});
- // Find the one that's in the current month (not outside)
- const sunday = sundayButtons.find(
- btn => !btn.className.includes('Outside'),
- );
+ // January 4, 2026 is a Sunday - should be disabled
+ const sunday = getDayButton(4);
expect(sunday).toBeDisabled();
});
@@ -216,11 +222,11 @@ describe('XDSCalendar', () => {
);
// Click start date
- const day10 = screen.getByRole('gridcell', {name: '10'});
+ const day10 = getDayButton(10);
await user.click(day10);
// Click end date
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ const day15 = getDayButton(15);
await user.click(day15);
expect(handleChange).toHaveBeenCalledWith({
@@ -242,11 +248,11 @@ describe('XDSCalendar', () => {
);
// Click later date first
- const day20 = screen.getByRole('gridcell', {name: '20'});
+ const day20 = getDayButton(20);
await user.click(day20);
// Click earlier date
- const day10 = screen.getByRole('gridcell', {name: '10'});
+ const day10 = getDayButton(10);
await user.click(day10);
// Should swap to ensure start <= end
@@ -265,9 +271,9 @@ describe('XDSCalendar', () => {
/>,
);
- const day10 = screen.getByRole('gridcell', {name: '10'});
- const day12 = screen.getByRole('gridcell', {name: '12'});
- const day15 = screen.getByRole('gridcell', {name: '15'});
+ const day10 = getDayButton(10);
+ const day12 = getDayButton(12);
+ const day15 = getDayButton(15);
expect(day10).toHaveAttribute('aria-selected', 'true');
expect(day12).toHaveAttribute('aria-selected', 'true');
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index 509715d702..d428dbc3ca 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -1,6 +1,6 @@
/**
* @file XDSCalendar.tsx
- * @input Uses React useState, useMemo, useCallback, forwardRef
+ * @input Uses React useState, useMemo, useCallback, forwardRef, hooks
* @output Exports XDSCalendar component and related types
* @position Core implementation; consumed by index.ts, tested by XDSCalendar.test.tsx
*
@@ -16,18 +16,33 @@ import {
useState,
useMemo,
useCallback,
+ useEffect,
type HTMLAttributes,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {
- colorVars,
- spacingVars,
- radiusVars,
- transitionVars,
- textSizeVars,
-} from '../theme/tokens.stylex';
import {XDSButton} from '../Button';
import {ChevronLeftIcon, ChevronRightIcon} from '@heroicons/react/24/outline';
+import {useGridFocus} from '../hooks';
+import {
+ useCalendarDays,
+ useCalendarConstraints,
+ useCalendarRovingTabindex,
+ type CalendarDay,
+} from './hooks';
+import {
+ calendarStyles,
+ monthGridStyles,
+ dayCellStyles,
+ dayCellTheme,
+} from './styles';
+import {
+ dateToISO,
+ parseISO,
+ isSameDay,
+ isDateInRange,
+ getWeekNumber,
+ formatAccessibleDate,
+} from './utils';
// =============================================================================
// Types
@@ -136,572 +151,38 @@ interface XDSCalendarRangeProps extends XDSCalendarBaseProps {
export type XDSCalendarProps = XDSCalendarSingleProps | XDSCalendarRangeProps;
-// =============================================================================
-// Utility Functions
-// =============================================================================
-
-function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}` as ISODateString;
-}
-
-function parseISO(str: ISODateString): Date {
- const [year, month, day] = str.split('-').map(Number);
- return new Date(year, month - 1, day);
-}
-
-function isSameDay(a: Date, b: Date): boolean {
- return (
- a.getFullYear() === b.getFullYear() &&
- a.getMonth() === b.getMonth() &&
- a.getDate() === b.getDate()
- );
-}
-
-function isDateInRange(date: Date, start: Date, end: Date): boolean {
- const time = date.getTime();
- return time >= start.getTime() && time <= end.getTime();
-}
-
-function getWeekNumber(date: Date): number {
- const d = new Date(
- Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
- );
- const dayNum = d.getUTCDay() || 7;
- d.setUTCDate(d.getUTCDate() + 4 - dayNum);
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
- return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
-}
-
-// =============================================================================
-// Styles
-// =============================================================================
-
-const styles = stylex.create({
- calendar: {
- display: 'inline-block',
- backgroundColor: colorVars['--color-surface'],
- padding: spacingVars['--spacing-3'],
- minWidth: '220px',
- },
- header: {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- marginBottom: spacingVars['--spacing-2'],
- gap: spacingVars['--spacing-2'],
- },
- monthYearLabel: {
- flex: 1,
- textAlign: 'center',
- fontWeight: 600,
- fontSize: textSizeVars['--text-base'],
- color: colorVars['--color-text-primary'],
- },
- monthsContainer: {
- display: 'flex',
- gap: spacingVars['--spacing-4'],
- },
- monthGrid: {
- flex: '1 1 0',
- },
- weekHeader: {
- display: 'grid',
- gridTemplateColumns: 'repeat(7, 1fr)',
- marginBottom: spacingVars['--spacing-1'],
- },
- weekHeaderWithNumbers: {
- gridTemplateColumns: 'auto repeat(7, 1fr)',
- },
- dayName: {
- width: '32px',
- height: '32px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: textSizeVars['--text-xsm'],
- fontWeight: 400,
- color: colorVars['--color-text-secondary'],
- },
- weekNumberHeader: {
- width: '32px',
- },
- daysGrid: {
- display: 'grid',
- gridTemplateColumns: 'repeat(7, 1fr)',
- },
- daysGridWithNumbers: {
- gridTemplateColumns: 'auto repeat(7, 1fr)',
- },
- weekNumber: {
- width: '32px',
- height: '32px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: textSizeVars['--text-xsm'],
- color: colorVars['--color-text-secondary'],
- },
- weekRow: {
- display: 'contents',
- },
- // Cell wrapper - contains positioned background element
- dayCell: {
- position: 'relative',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- height: '32px',
- },
- // Range background element - positioned behind the day button
- dayRangeBg: {
- position: 'absolute',
- top: '2px',
- bottom: '2px',
- left: 0,
- right: 0,
- backgroundColor: colorVars['--color-accent-deemphasized'],
- },
- // Radius only (for row edges)
- dayRangeBgRadiusLeft: {
- left: '2px',
- borderTopLeftRadius: radiusVars['--radius-rounded'],
- borderBottomLeftRadius: radiusVars['--radius-rounded'],
- },
- dayRangeBgRadiusRight: {
- right: '2px',
- borderTopRightRadius: radiusVars['--radius-rounded'],
- borderBottomRightRadius: radiusVars['--radius-rounded'],
- },
- // Inset (for actual range start/end)
- dayRangeInsetLeft: {
- left: '2px',
- },
- dayRangeInsetRight: {
- right: '2px',
- },
- // Preview range background (dotted border)
- dayRangePreview: {
- position: 'absolute',
- top: '2px',
- bottom: '2px',
- left: 0,
- right: 0,
- borderTopWidth: 1,
- borderTopStyle: 'dotted',
- borderTopColor: colorVars['--color-divider-emphasized'],
- borderBottomWidth: 1,
- borderBottomStyle: 'dotted',
- borderBottomColor: colorVars['--color-divider-emphasized'],
- },
- // Radius only (for row edges)
- dayRangePreviewRadiusLeft: {
- left: '2px',
- borderTopLeftRadius: radiusVars['--radius-rounded'],
- borderBottomLeftRadius: radiusVars['--radius-rounded'],
- borderLeftWidth: 1,
- borderLeftStyle: 'dotted',
- borderLeftColor: colorVars['--color-divider-emphasized'],
- },
- dayRangePreviewRadiusRight: {
- right: '2px',
- borderTopRightRadius: radiusVars['--radius-rounded'],
- borderBottomRightRadius: radiusVars['--radius-rounded'],
- borderRightWidth: 1,
- borderRightStyle: 'dotted',
- borderRightColor: colorVars['--color-divider-emphasized'],
- },
- // Border + inset (for actual preview start/end)
- dayRangePreviewStart: {
- left: '2px',
- borderLeftWidth: 1,
- borderLeftStyle: 'dotted',
- borderLeftColor: colorVars['--color-divider-emphasized'],
- borderTopLeftRadius: radiusVars['--radius-rounded'],
- borderBottomLeftRadius: radiusVars['--radius-rounded'],
- },
- dayRangePreviewEnd: {
- right: '2px',
- borderRightWidth: 1,
- borderRightStyle: 'dotted',
- borderRightColor: colorVars['--color-divider-emphasized'],
- borderTopRightRadius: radiusVars['--radius-rounded'],
- borderBottomRightRadius: radiusVars['--radius-rounded'],
- },
- day: {
- width: '28px',
- height: '28px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- borderRadius: '50%',
- borderWidth: 0,
- borderStyle: 'none',
- backgroundColor: 'transparent',
- cursor: 'pointer',
- fontFamily: 'inherit',
- fontSize: textSizeVars['--text-sm'],
- color: colorVars['--color-text-primary'],
- padding: 0,
- position: 'relative',
- zIndex: 1,
- transitionProperty: 'background-color, color',
- transitionDuration: transitionVars['--transition-fast'],
- backgroundImage: {
- default: null,
- ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
- },
- outline: {
- default: null,
- ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- },
- dayOutside: {
- color: colorVars['--color-text-secondary'],
- opacity: 0.5,
- },
- dayToday: {
- boxShadow: `inset 0 0 0 1px ${colorVars['--color-divider-emphasized']}`,
- },
- dayTodayInRange: {
- boxShadow: `inset 0 0 0 1px ${colorVars['--color-text-primary']}`,
- },
- daySelected: {
- backgroundColor: colorVars['--color-accent'],
- color: colorVars['--color-text-on-media'],
- backgroundImage: {
- default: null,
- ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
- },
- },
- dayDisabled: {
- opacity: 0.3,
- cursor: 'not-allowed',
- backgroundImage: {
- default: null,
- ':hover': null,
- },
- },
- navIcon: {
- width: '16px',
- height: '16px',
- },
-});
-
-// =============================================================================
-// Sub-components
-// =============================================================================
-
-interface MonthGridProps {
- month: Date;
- value: ISODateString | DateRange | undefined;
- mode: 'single' | 'range';
- rangeSelectionStart: ISODateString | null;
- hoveredDate: ISODateString | null;
- min?: ISODateString;
- max?: ISODateString;
- dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
- hasOutsideDays: boolean;
- hasWeekNumbers: boolean;
- hasVariableRowCount: boolean;
- weekStartsOn: DayOfWeek;
- onDayClick: (date: Date) => void;
- onDayHover: (date: Date | null) => void;
- today: Date;
-}
-
-function MonthGrid({
- month,
- value,
- mode,
- rangeSelectionStart,
- hoveredDate,
- min,
- max,
- dateConstraints,
- hasOutsideDays,
- hasWeekNumbers,
- hasVariableRowCount,
- weekStartsOn,
- onDayClick,
- onDayHover,
- today,
-}: MonthGridProps) {
- const year = month.getFullYear();
- const monthIndex = month.getMonth();
-
- // Calculate days to display
- const firstDayOfMonth = new Date(year, monthIndex, 1);
- const lastDayOfMonth = new Date(year, monthIndex + 1, 0);
- const daysInMonth = lastDayOfMonth.getDate();
-
- // Calculate starting offset based on weekStartsOn
- let startingDayOfWeek = firstDayOfMonth.getDay() - weekStartsOn;
- if (startingDayOfWeek < 0) startingDayOfWeek += 7;
-
- // Calculate total cells
- const totalDays = daysInMonth + startingDayOfWeek;
- const totalRows = hasVariableRowCount ? Math.ceil(totalDays / 7) : 6;
- const totalCells = totalRows * 7;
-
- // Parse constraints
- const minDate = min ? parseISO(min) : null;
- const maxDate = max ? parseISO(max) : null;
-
- // Parse selection
- let selectedDate: Date | null = null;
- let rangeStart: Date | null = null;
- let rangeEnd: Date | null = null;
-
- if (mode === 'single' && value && typeof value === 'string') {
- selectedDate = parseISO(value as ISODateString);
- } else if (mode === 'range' && value && typeof value === 'object') {
- const range = value as DateRange;
- rangeStart = parseISO(range.start);
- rangeEnd = parseISO(range.end);
- }
-
- // Handle in-progress range selection
- if (rangeSelectionStart) {
- rangeStart = parseISO(rangeSelectionStart);
- rangeEnd = rangeStart; // Show as single day until end is selected
- }
-
- // Calculate preview range when hovering during range selection
- let previewStart: Date | null = null;
- let previewEnd: Date | null = null;
- if (mode === 'range' && rangeSelectionStart && hoveredDate) {
- const startDate = parseISO(rangeSelectionStart);
- const hoverDate = parseISO(hoveredDate);
- if (startDate.getTime() !== hoverDate.getTime()) {
- if (hoverDate < startDate) {
- previewStart = hoverDate;
- previewEnd = startDate;
- } else {
- previewStart = startDate;
- previewEnd = hoverDate;
- }
- }
- }
-
- // Generate day names
- const dayNames = useMemo(() => {
- const names = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
- const rotated = [];
- for (let i = 0; i < 7; i++) {
- rotated.push(names[(i + weekStartsOn) % 7]);
- }
- return rotated;
- }, [weekStartsOn]);
-
- // Generate days
- const days = useMemo(() => {
- const result: Array<{
- date: Date;
- isOutside: boolean;
- dayNumber: number;
- }> = [];
-
- for (let i = 0; i < totalCells; i++) {
- const dayOffset = i - startingDayOfWeek + 1;
- const date = new Date(year, monthIndex, dayOffset);
- const isOutside = dayOffset < 1 || dayOffset > daysInMonth;
-
- result.push({
- date,
- isOutside,
- dayNumber: date.getDate(),
- });
- }
-
- return result;
- }, [year, monthIndex, totalCells, startingDayOfWeek, daysInMonth]);
-
- // Group days into weeks for week numbers
- const weeks = useMemo(() => {
- const result: Array<typeof days> = [];
- for (let i = 0; i < days.length; i += 7) {
- result.push(days.slice(i, i + 7));
- }
- return result;
- }, [days]);
-
- const isDateDisabled = useCallback(
- (date: Date): boolean => {
- if (minDate && date < minDate) return true;
- if (maxDate && date > maxDate) return true;
- if (dateConstraints) {
- for (const constraint of dateConstraints) {
- if (!constraint(date)) return true;
- }
- }
- return false;
- },
- [minDate, maxDate, dateConstraints],
- );
-
- return (
- <div {...stylex.props(styles.monthGrid)}>
- {/* Day names header */}
- <div
- {...stylex.props(
- styles.weekHeader,
- hasWeekNumbers && styles.weekHeaderWithNumbers,
- )}>
- {hasWeekNumbers && (
- <div {...stylex.props(styles.dayName, styles.weekNumberHeader)} />
- )}
- {dayNames.map((name, i) => (
- <div key={i} {...stylex.props(styles.dayName)}>
- {name}
- </div>
- ))}
- </div>
-
- {/* Days grid */}
- <div
- role="grid"
- {...stylex.props(
- styles.daysGrid,
- hasWeekNumbers && styles.daysGridWithNumbers,
- )}>
- {weeks.map((week, weekIndex) => {
- // Find first non-outside day for week number
- const weekDate = week.find(d => !d.isOutside)?.date || week[0].date;
- const weekNum = getWeekNumber(weekDate);
-
- return (
- <div key={weekIndex} role="row" {...stylex.props(styles.weekRow)}>
- {hasWeekNumbers && (
- <div {...stylex.props(styles.weekNumber)}>{weekNum}</div>
- )}
- {week.map((day, dayIndex) => {
- const {date, isOutside, dayNumber} = day;
-
- if (isOutside && !hasOutsideDays) {
- return (
- <div key={dayIndex} {...stylex.props(styles.dayCell)} />
- );
- }
-
- const isToday = isSameDay(date, today);
- const isSelected =
- mode === 'single' &&
- selectedDate &&
- isSameDay(date, selectedDate);
- const isInRange =
- mode === 'range' &&
- rangeStart &&
- rangeEnd &&
- isDateInRange(date, rangeStart, rangeEnd);
- const isRangeStart =
- mode === 'range' && rangeStart && isSameDay(date, rangeStart);
- const isRangeEnd =
- mode === 'range' && rangeEnd && isSameDay(date, rangeEnd);
- const isDisabled = isDateDisabled(date);
-
- // Preview range calculations
- const isInPreview =
- previewStart &&
- previewEnd &&
- isDateInRange(date, previewStart, previewEnd);
- const isPreviewStart =
- previewStart && isSameDay(date, previewStart);
- const isPreviewEnd = previewEnd && isSameDay(date, previewEnd);
-
- // Determine cell background for range - show for all cells in range
- const hasRangeBackground = isInRange;
-
- // Round edges at grid boundaries or range endpoints
- const isFirstColumn = dayIndex === 0;
- const isLastColumn = dayIndex === 6;
-
- // Determine if background needs rounded edges
- const roundLeft = isRangeStart || isFirstColumn;
- const roundRight = isRangeEnd || isLastColumn;
-
- // Determine if preview needs rounded edges
- const previewRoundLeft = isPreviewStart || isFirstColumn;
- const previewRoundRight = isPreviewEnd || isLastColumn;
-
- return (
- <div key={dayIndex} {...stylex.props(styles.dayCell)}>
- {hasRangeBackground && (
- <div
- {...stylex.props(
- styles.dayRangeBg,
- roundLeft && styles.dayRangeBgRadiusLeft,
- roundRight && styles.dayRangeBgRadiusRight,
- isRangeStart && styles.dayRangeInsetLeft,
- isRangeStart &&
- roundRight &&
- styles.dayRangeInsetRight,
- isRangeEnd && styles.dayRangeInsetRight,
- isRangeStart && roundLeft && styles.dayRangeInsetLeft,
- )}
- />
- )}
- {isInPreview && (
- <div
- {...stylex.props(
- styles.dayRangePreview,
- previewRoundLeft && styles.dayRangePreviewRadiusLeft,
- previewRoundRight &&
- styles.dayRangePreviewRadiusRight,
- isPreviewStart && styles.dayRangePreviewStart,
- isPreviewStart &&
- roundRight &&
- styles.dayRangeInsetRight,
- isPreviewEnd && styles.dayRangePreviewEnd,
- isPreviewEnd && roundLeft && styles.dayRangeInsetLeft,
- )}
- />
- )}
- <button
- type="button"
- role="gridcell"
- aria-selected={isSelected || isInRange || undefined}
- aria-disabled={isDisabled || undefined}
- disabled={isDisabled}
- tabIndex={isToday && !isDisabled ? 0 : -1}
- onClick={() => !isDisabled && onDayClick(date)}
- onMouseEnter={() => !isDisabled && onDayHover(date)}
- onMouseLeave={() => onDayHover(null)}
- {...stylex.props(
- styles.day,
- isOutside && styles.dayOutside,
- isToday && !isSelected && !isInRange && styles.dayToday,
- isToday &&
- !isSelected &&
- isInRange &&
- styles.dayTodayInRange,
- (isSelected || isRangeStart || isRangeEnd) &&
- styles.daySelected,
- isDisabled && styles.dayDisabled,
- )}>
- {dayNumber}
- </button>
- </div>
- );
- })}
- </div>
- );
- })}
- </div>
- </div>
- );
-}
-
// =============================================================================
// Main Component
// =============================================================================
+/**
+ * A calendar component for selecting dates or date ranges.
+ *
+ * @example
+ * ```tsx
+ * // Single date selection
+ * <XDSCalendar
+ * value={selectedDate}
+ * onChange={(date) => setSelectedDate(date)}
+ * />
+ *
+ * // Date range selection
+ * <XDSCalendar
+ * mode="range"
+ * value={dateRange}
+ * onChange={(range) => setDateRange(range)}
+ * />
+ *
+ * // With constraints
+ * <XDSCalendar
+ * min="2026-01-01"
+ * max="2026-12-31"
+ * dateConstraints={[(date) => date.getDay() !== 0]} // No Sundays
+ * value={selectedDate}
+ * onChange={setSelectedDate}
+ * />
+ * ```
+ */
export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
(props, ref) => {
const {
@@ -737,6 +218,11 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
// Hovered date for range preview
const [hoveredDate, setHoveredDate] = useState<ISODateString | null>(null);
+ // Pending focus target after month navigation
+ const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(
+ null,
+ );
+
// Determine effective value
const effectiveValue = value !== undefined ? value : internalValue;
@@ -790,11 +276,19 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
// Navigation handlers
const navigateMonth = useCallback(
- (delta: number) => {
+ (delta: number, focusedDate?: ISODateString, offset?: number) => {
const newDate = new Date(baseMonth);
newDate.setMonth(baseMonth.getMonth() + delta);
const newISO = dateToISO(newDate);
+ // Calculate target focus date if a focused date was provided
+ if (focusedDate) {
+ const currentDate = parseISO(focusedDate);
+ const daysToMove = offset ?? 7;
+ currentDate.setDate(currentDate.getDate() + delta * daysToMove);
+ setPendingFocus(dateToISO(currentDate));
+ }
+
if (onFocusDateChange) {
onFocusDateChange(newISO);
} else {
@@ -843,29 +337,33 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
);
return (
- <div ref={ref} {...stylex.props(styles.calendar)} {...rest}>
+ <div ref={ref} {...stylex.props(calendarStyles.calendar)} {...rest}>
{/* Header with navigation */}
- <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(calendarStyles.header)}>
<XDSButton
label="Previous month"
variant="ghost"
- icon={<ChevronLeftIcon {...stylex.props(styles.navIcon)} />}
+ icon={<ChevronLeftIcon {...stylex.props(calendarStyles.navIcon)} />}
onClick={() => navigateMonth(-1)}
/>
- <span {...stylex.props(styles.monthYearLabel)}>{monthYearLabel}</span>
+ <span {...stylex.props(calendarStyles.monthYearLabel)}>
+ {monthYearLabel}
+ </span>
<XDSButton
label="Next month"
variant="ghost"
- icon={<ChevronRightIcon {...stylex.props(styles.navIcon)} />}
+ icon={
+ <ChevronRightIcon {...stylex.props(calendarStyles.navIcon)} />
+ }
onClick={() => navigateMonth(1)}
/>
</div>
{/* Month grids */}
- <div {...stylex.props(styles.monthsContainer)}>
- {visibleMonths.map((month, index) => (
+ <div {...stylex.props(calendarStyles.monthsContainer)}>
+ {visibleMonths.map(month => (
<MonthGrid
key={`${month.getFullYear()}-${month.getMonth()}`}
month={month}
@@ -883,6 +381,14 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
onDayClick={handleDayClick}
onDayHover={date => setHoveredDate(date ? dateToISO(date) : null)}
today={today}
+ onNavigatePrevious={(focusedDate, offset) =>
+ navigateMonth(-1, focusedDate, offset)
+ }
+ onNavigateNext={(focusedDate, offset) =>
+ navigateMonth(1, focusedDate, offset)
+ }
+ pendingFocus={pendingFocus}
+ onPendingFocusHandled={() => setPendingFocus(null)}
/>
))}
</div>
@@ -892,3 +398,426 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
);
XDSCalendar.displayName = 'XDSCalendar';
+
+// =============================================================================
+// MonthGrid (Private)
+// =============================================================================
+
+interface MonthGridProps {
+ month: Date;
+ value: ISODateString | DateRange | undefined;
+ mode: 'single' | 'range';
+ rangeSelectionStart: ISODateString | null;
+ hoveredDate: ISODateString | null;
+ min?: ISODateString;
+ max?: ISODateString;
+ dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+ hasOutsideDays: boolean;
+ hasWeekNumbers: boolean;
+ hasVariableRowCount: boolean;
+ weekStartsOn: DayOfWeek;
+ onDayClick: (date: Date) => void;
+ onDayHover: (date: Date | null) => void;
+ today: Date;
+ onNavigatePrevious?: (focusedDate: ISODateString, offset: number) => void;
+ onNavigateNext?: (focusedDate: ISODateString, offset: number) => void;
+ pendingFocus?: ISODateString | null;
+ onPendingFocusHandled?: () => void;
+}
+
+function MonthGrid({
+ month,
+ value,
+ mode,
+ rangeSelectionStart,
+ hoveredDate,
+ min,
+ max,
+ dateConstraints,
+ hasOutsideDays,
+ hasWeekNumbers,
+ hasVariableRowCount,
+ weekStartsOn,
+ onDayClick,
+ onDayHover,
+ today,
+ onNavigatePrevious,
+ onNavigateNext,
+ pendingFocus,
+ onPendingFocusHandled,
+}: MonthGridProps) {
+ const year = month.getFullYear();
+ const monthIndex = month.getMonth();
+
+ // Use hooks for days generation and constraints
+ const {days, weeks, dayNames} = useCalendarDays({
+ year,
+ month: monthIndex,
+ weekStartsOn,
+ hasVariableRowCount,
+ });
+
+ const {isDateDisabled} = useCalendarConstraints({
+ min,
+ max,
+ dateConstraints,
+ });
+
+ const {isTabbable} = useCalendarRovingTabindex({
+ days,
+ today,
+ year,
+ month: monthIndex,
+ isDateDisabled,
+ });
+
+ // Helper to get the focused date from the currently focused element
+ const getFocusedDate = useCallback((): ISODateString | null => {
+ const activeElement = document.activeElement as HTMLElement | null;
+ if (!activeElement) return null;
+
+ const ariaLabel = activeElement.getAttribute('aria-label');
+ if (!ariaLabel) return null;
+
+ const parsed = new Date(ariaLabel);
+ if (isNaN(parsed.getTime())) return null;
+
+ return dateToISO(parsed);
+ }, []);
+
+ // Handle navigation to previous month
+ const handleNavigatePrevious = useCallback(
+ (_column: number, offset: number) => {
+ const focusedDate = getFocusedDate();
+ if (focusedDate) {
+ onNavigatePrevious?.(focusedDate, offset);
+ }
+ },
+ [getFocusedDate, onNavigatePrevious],
+ );
+
+ // Handle navigation to next month
+ const handleNavigateNext = useCallback(
+ (_column: number, offset: number) => {
+ const focusedDate = getFocusedDate();
+ if (focusedDate) {
+ onNavigateNext?.(focusedDate, offset);
+ }
+ },
+ [getFocusedDate, onNavigateNext],
+ );
+
+ // Handle PageUp/PageDown
+ const handlePageUp = useCallback(() => {
+ const focusedDate = getFocusedDate();
+ if (focusedDate) {
+ onNavigatePrevious?.(focusedDate, 7);
+ }
+ }, [getFocusedDate, onNavigatePrevious]);
+
+ const handlePageDown = useCallback(() => {
+ const focusedDate = getFocusedDate();
+ if (focusedDate) {
+ onNavigateNext?.(focusedDate, 7);
+ }
+ }, [getFocusedDate, onNavigateNext]);
+
+ // Grid focus navigation
+ const {gridRef, handleKeyDown: handleGridKeyDown} = useGridFocus({
+ columns: 7,
+ cellSelector: 'button:not([disabled])',
+ onNavigateBefore: handleNavigatePrevious,
+ onNavigateAfter: handleNavigateNext,
+ onPageUp: handlePageUp,
+ onPageDown: handlePageDown,
+ });
+
+ // Handle pending focus after month navigation
+ useEffect(() => {
+ if (!pendingFocus || !gridRef.current) return;
+
+ const buttons = gridRef.current.querySelectorAll<HTMLElement>(
+ 'button:not([disabled])',
+ );
+
+ const targetDate = parseISO(pendingFocus);
+ const targetLabel = formatAccessibleDate(targetDate);
+
+ let targetButton: HTMLElement | null = null;
+ for (const button of buttons) {
+ if (button.getAttribute('aria-label') === targetLabel) {
+ targetButton = button;
+ break;
+ }
+ }
+
+ if (!targetButton && buttons.length > 0) {
+ targetButton = buttons[0];
+ }
+
+ targetButton?.focus();
+ onPendingFocusHandled?.();
+ }, [pendingFocus, gridRef, onPendingFocusHandled]);
+
+ // Parse selection
+ let selectedDate: Date | null = null;
+ let rangeStart: Date | null = null;
+ let rangeEnd: Date | null = null;
+
+ if (mode === 'single' && value && typeof value === 'string') {
+ selectedDate = parseISO(value as ISODateString);
+ } else if (mode === 'range' && value && typeof value === 'object') {
+ const range = value as DateRange;
+ rangeStart = parseISO(range.start);
+ rangeEnd = parseISO(range.end);
+ }
+
+ // Handle in-progress range selection
+ if (rangeSelectionStart) {
+ rangeStart = parseISO(rangeSelectionStart);
+ rangeEnd = rangeStart;
+ }
+
+ // Calculate preview range when hovering during range selection
+ let previewStart: Date | null = null;
+ let previewEnd: Date | null = null;
+ if (mode === 'range' && rangeSelectionStart && hoveredDate) {
+ const startDate = parseISO(rangeSelectionStart);
+ const hoverDate = parseISO(hoveredDate);
+ if (startDate.getTime() !== hoverDate.getTime()) {
+ if (hoverDate < startDate) {
+ previewStart = hoverDate;
+ previewEnd = startDate;
+ } else {
+ previewStart = startDate;
+ previewEnd = hoverDate;
+ }
+ }
+ }
+
+ // Month label for announcements
+ const monthLabel = useMemo(() => {
+ return new Intl.DateTimeFormat(undefined, {
+ year: 'numeric',
+ month: 'long',
+ }).format(month);
+ }, [month]);
+
+ return (
+ <div {...stylex.props(monthGridStyles.monthGrid)}>
+ {/* Day names header */}
+ <div
+ {...stylex.props(
+ monthGridStyles.weekHeader,
+ hasWeekNumbers && monthGridStyles.weekHeaderWithNumbers,
+ )}>
+ {hasWeekNumbers && (
+ <div
+ {...stylex.props(
+ monthGridStyles.dayName,
+ monthGridStyles.weekNumberHeader,
+ )}
+ />
+ )}
+ {dayNames.map((name, i) => (
+ <div key={i} {...stylex.props(monthGridStyles.dayName)}>
+ {name}
+ </div>
+ ))}
+ </div>
+
+ {/* Days grid */}
+ <div
+ ref={gridRef as React.RefObject<HTMLDivElement>}
+ role="grid"
+ aria-label={monthLabel}
+ onKeyDown={handleGridKeyDown}
+ {...stylex.props(
+ monthGridStyles.daysGrid,
+ hasWeekNumbers && monthGridStyles.daysGridWithNumbers,
+ )}>
+ {weeks.map((week, weekIndex) => {
+ const weekDate = week.find(d => !d.isOutside)?.date || week[0].date;
+ const weekNum = getWeekNumber(weekDate);
+
+ return (
+ <div
+ key={weekIndex}
+ role="row"
+ {...stylex.props(monthGridStyles.weekRow)}>
+ {hasWeekNumbers && (
+ <div {...stylex.props(monthGridStyles.weekNumber)}>
+ {weekNum}
+ </div>
+ )}
+ {week.map((day, dayIndex) => (
+ <DayCell
+ key={dayIndex}
+ day={day}
+ dayIndex={dayIndex}
+ mode={mode}
+ selectedDate={selectedDate}
+ rangeStart={rangeStart}
+ rangeEnd={rangeEnd}
+ previewStart={previewStart}
+ previewEnd={previewEnd}
+ today={today}
+ hasOutsideDays={hasOutsideDays}
+ isDisabled={isDateDisabled(day.date)}
+ isTabbable={isTabbable(day.iso)}
+ onDayClick={onDayClick}
+ onDayHover={onDayHover}
+ />
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// DayCell (Private)
+// =============================================================================
+
+interface DayCellProps {
+ day: CalendarDay;
+ dayIndex: number;
+ mode: 'single' | 'range';
+ selectedDate: Date | null;
+ rangeStart: Date | null;
+ rangeEnd: Date | null;
+ previewStart: Date | null;
+ previewEnd: Date | null;
+ today: Date;
+ hasOutsideDays: boolean;
+ isDisabled: boolean;
+ isTabbable: boolean;
+ onDayClick: (date: Date) => void;
+ onDayHover: (date: Date | null) => void;
+}
+
+function DayCell({
+ day,
+ dayIndex,
+ mode,
+ selectedDate,
+ rangeStart,
+ rangeEnd,
+ previewStart,
+ previewEnd,
+ today,
+ hasOutsideDays,
+ isDisabled,
+ isTabbable: isTabbableDay,
+ onDayClick,
+ onDayHover,
+}: DayCellProps) {
+ const {date, isOutside, dayNumber} = day;
+
+ // Empty cell for outside days when not showing them
+ if (isOutside && !hasOutsideDays) {
+ return <div {...stylex.props(dayCellStyles.cell)} />;
+ }
+
+ const isToday = isSameDay(date, today);
+ const isSelected =
+ mode === 'single' && selectedDate && isSameDay(date, selectedDate);
+ const isInRange =
+ mode === 'range' &&
+ rangeStart &&
+ rangeEnd &&
+ isDateInRange(date, rangeStart, rangeEnd);
+ const isRangeStart =
+ mode === 'range' && rangeStart && isSameDay(date, rangeStart);
+ const isRangeEnd = mode === 'range' && rangeEnd && isSameDay(date, rangeEnd);
+
+ // Preview range calculations
+ const isInPreview =
+ previewStart && previewEnd && isDateInRange(date, previewStart, previewEnd);
+ const isPreviewStart = previewStart && isSameDay(date, previewStart);
+ const isPreviewEnd = previewEnd && isSameDay(date, previewEnd);
+
+ // Determine cell background for range
+ const hasRangeBackground = isInRange;
+
+ // Round edges at grid boundaries or range endpoints
+ const isFirstColumn = dayIndex === 0;
+ const isLastColumn = dayIndex === 6;
+
+ // Determine if background needs rounded edges
+ const roundLeft = isRangeStart || isFirstColumn;
+ const roundRight = isRangeEnd || isLastColumn;
+
+ // Determine if preview needs rounded edges
+ const previewRoundLeft = isPreviewStart || isFirstColumn;
+ const previewRoundRight = isPreviewEnd || isLastColumn;
+
+ return (
+ <div {...stylex.props(dayCellStyles.cell)}>
+ {/* Range background */}
+ {hasRangeBackground && (
+ <div
+ {...stylex.props(
+ dayCellStyles.rangeBg,
+ dayCellTheme.rangeBg,
+ roundLeft && dayCellStyles.rangeBgRadiusLeft,
+ roundRight && dayCellStyles.rangeBgRadiusRight,
+ isRangeStart && dayCellStyles.rangeInsetLeft,
+ isRangeStart && roundRight && dayCellStyles.rangeInsetRight,
+ isRangeEnd && dayCellStyles.rangeInsetRight,
+ isRangeStart && roundLeft && dayCellStyles.rangeInsetLeft,
+ )}
+ />
+ )}
+
+ {/* Preview range background */}
+ {isInPreview && (
+ <div
+ {...stylex.props(
+ dayCellStyles.previewBg,
+ dayCellTheme.previewBg,
+ previewRoundLeft && dayCellStyles.previewBgRadiusLeft,
+ previewRoundRight && dayCellStyles.previewBgRadiusRight,
+ isPreviewStart && dayCellStyles.previewStart,
+ isPreviewStart && roundRight && dayCellStyles.rangeInsetRight,
+ isPreviewEnd && dayCellStyles.previewEnd,
+ isPreviewEnd && roundLeft && dayCellStyles.rangeInsetLeft,
+ )}
+ />
+ )}
+
+ {/* Day button */}
+ <button
+ type="button"
+ role="gridcell"
+ aria-label={formatAccessibleDate(date)}
+ aria-selected={isSelected || isInRange || undefined}
+ aria-disabled={isDisabled || undefined}
+ disabled={isDisabled}
+ tabIndex={isTabbableDay ? 0 : -1}
+ onClick={() => !isDisabled && onDayClick(date)}
+ onMouseEnter={() => !isDisabled && onDayHover(date)}
+ onMouseLeave={() => onDayHover(null)}
+ {...stylex.props(
+ dayCellStyles.day,
+ dayCellTheme.day,
+ isOutside && dayCellStyles.dayOutside,
+ isOutside && dayCellTheme.dayOutside,
+ isToday && !isSelected && !isInRange && dayCellStyles.dayToday,
+ isToday && !isSelected && !isInRange && dayCellTheme.dayToday,
+ isToday && !isSelected && isInRange && dayCellStyles.dayTodayInRange,
+ isToday && !isSelected && isInRange && dayCellTheme.dayTodayInRange,
+ (isSelected || isRangeStart || isRangeEnd) &&
+ dayCellStyles.daySelected,
+ (isSelected || isRangeStart || isRangeEnd) &&
+ dayCellTheme.daySelected,
+ isDisabled && dayCellStyles.dayDisabled,
+ isDisabled && dayCellTheme.dayDisabled,
+ )}>
+ {dayNumber}
+ </button>
+ </div>
+ );
+}
diff --git a/packages/core/src/Calendar/hooks/index.ts b/packages/core/src/Calendar/hooks/index.ts
new file mode 100644
index 0000000000..f944f661ca
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/index.ts
@@ -0,0 +1,33 @@
+/**
+ * @file index.ts
+ * @input Imports calendar-specific hooks
+ * @output Exports all calendar hooks
+ * @position Calendar hooks entry point; used by XDSCalendar
+ *
+ * SYNC: When modified, update this header
+ */
+
+export {useCalendarDays} from './useCalendarDays';
+export type {
+ CalendarDay,
+ UseCalendarDaysOptions,
+ UseCalendarDaysReturn,
+} from './useCalendarDays';
+
+export {useCalendarConstraints} from './useCalendarConstraints';
+export type {
+ UseCalendarConstraintsOptions,
+ UseCalendarConstraintsReturn,
+} from './useCalendarConstraints';
+
+export {useCalendarNavigation} from './useCalendarNavigation';
+export type {
+ UseCalendarNavigationOptions,
+ UseCalendarNavigationReturn,
+} from './useCalendarNavigation';
+
+export {useCalendarRovingTabindex} from './useCalendarRovingTabindex';
+export type {
+ UseCalendarRovingTabindexOptions,
+ UseCalendarRovingTabindexReturn,
+} from './useCalendarRovingTabindex';
diff --git a/packages/core/src/Calendar/hooks/useCalendarConstraints.ts b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
new file mode 100644
index 0000000000..5db4e3b16c
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarConstraints.ts
@@ -0,0 +1,106 @@
+/**
+ * @file useCalendarConstraints.ts
+ * @input Uses React useCallback, useMemo
+ * @output Exports useCalendarConstraints hook for date validation
+ * @position Calendar-specific hook; used by XDSCalendar
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Calendar/hooks/index.ts
+ */
+
+import {useCallback, useMemo} from 'react';
+import type {ISODateString} from '../XDSCalendar';
+
+/**
+ * Configuration for date constraints
+ */
+export interface UseCalendarConstraintsOptions {
+ /** Minimum selectable date in ISO format */
+ min?: ISODateString;
+ /** Maximum selectable date in ISO format */
+ max?: ISODateString;
+ /**
+ * Custom date constraint functions.
+ * Date is disabled if ANY function returns false.
+ */
+ dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+}
+
+/**
+ * Return type for useCalendarConstraints hook
+ */
+export interface UseCalendarConstraintsReturn {
+ /** Check if a date is disabled */
+ isDateDisabled: (date: Date) => boolean;
+ /** Parsed min date (or null) */
+ minDate: Date | null;
+ /** Parsed max date (or null) */
+ maxDate: Date | null;
+}
+
+/**
+ * Parse ISO date string to Date object.
+ */
+function parseISO(str: ISODateString): Date {
+ const [year, month, day] = str.split('-').map(Number);
+ return new Date(year, month - 1, day);
+}
+
+/**
+ * Hook for managing calendar date validation constraints.
+ *
+ * Provides a function to check if a date is disabled based on
+ * min/max bounds and custom constraint functions.
+ *
+ * @example
+ * ```tsx
+ * const {isDateDisabled} = useCalendarConstraints({
+ * min: '2026-01-01',
+ * max: '2026-12-31',
+ * dateConstraints: [
+ * (date) => date.getDay() !== 0, // No Sundays
+ * ],
+ * });
+ *
+ * // Check if a date can be selected
+ * if (isDateDisabled(someDate)) {
+ * console.log('This date is not selectable');
+ * }
+ * ```
+ */
+export function useCalendarConstraints(
+ options: UseCalendarConstraintsOptions,
+): UseCalendarConstraintsReturn {
+ const {min, max, dateConstraints} = options;
+
+ // Parse min/max dates
+ const minDate = useMemo(() => (min ? parseISO(min) : null), [min]);
+ const maxDate = useMemo(() => (max ? parseISO(max) : null), [max]);
+
+ // Check if a date is disabled
+ const isDateDisabled = useCallback(
+ (date: Date): boolean => {
+ // Check min bound
+ if (minDate && date < minDate) return true;
+
+ // Check max bound
+ if (maxDate && date > maxDate) return true;
+
+ // Check custom constraints
+ if (dateConstraints) {
+ for (const constraint of dateConstraints) {
+ if (!constraint(date)) return true;
+ }
+ }
+
+ return false;
+ },
+ [minDate, maxDate, dateConstraints],
+ );
+
+ return {
+ isDateDisabled,
+ minDate,
+ maxDate,
+ };
+}
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.ts
new file mode 100644
index 0000000000..37231e8183
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts
@@ -0,0 +1,154 @@
+/**
+ * @file useCalendarDays.ts
+ * @input Uses React useMemo
+ * @output Exports useCalendarDays hook for generating calendar day grids
+ * @position Calendar-specific hook; used by XDSCalendar
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Calendar/hooks/index.ts
+ */
+
+import {useMemo} from 'react';
+import type {DayOfWeek, ISODateString} from '../XDSCalendar';
+
+/**
+ * Represents a single day in the calendar grid.
+ */
+export interface CalendarDay {
+ /** The date object for this day */
+ date: Date;
+ /** ISO date string (YYYY-MM-DD) */
+ iso: ISODateString;
+ /** Whether this day is outside the current month */
+ isOutside: boolean;
+ /** The day number (1-31) */
+ dayNumber: number;
+}
+
+/**
+ * Configuration for calendar days generation
+ */
+export interface UseCalendarDaysOptions {
+ /** The year to generate days for */
+ year: number;
+ /** The month index (0-11) */
+ month: number;
+ /** First day of week (0=Sunday through 6=Saturday) */
+ weekStartsOn?: DayOfWeek;
+ /** Use variable rows per month vs. fixed 6-row grid */
+ hasVariableRowCount?: boolean;
+}
+
+/**
+ * Return type for useCalendarDays hook
+ */
+export interface UseCalendarDaysReturn {
+ /** All days in the grid (includes outside days) */
+ days: CalendarDay[];
+ /** Days grouped into weeks */
+ weeks: CalendarDay[][];
+ /** Localized day names for the header */
+ dayNames: string[];
+ /** Total number of cells in the grid */
+ totalCells: number;
+}
+
+/**
+ * Convert a Date to ISO date string format.
+ */
+function dateToISO(date: Date): ISODateString {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}` as ISODateString;
+}
+
+/**
+ * Hook for generating calendar day grids.
+ *
+ * Calculates all the days to display for a given month, including
+ * days from adjacent months to fill the grid.
+ *
+ * @example
+ * ```tsx
+ * const {days, weeks, dayNames} = useCalendarDays({
+ * year: 2026,
+ * month: 0, // January
+ * weekStartsOn: 0, // Sunday
+ * });
+ * ```
+ */
+export function useCalendarDays(
+ options: UseCalendarDaysOptions,
+): UseCalendarDaysReturn {
+ const {year, month, weekStartsOn = 0, hasVariableRowCount = false} = options;
+
+ // Calculate grid structure
+ const gridInfo = useMemo(() => {
+ const firstDayOfMonth = new Date(year, month, 1);
+ const lastDayOfMonth = new Date(year, month + 1, 0);
+ const daysInMonth = lastDayOfMonth.getDate();
+
+ // Calculate starting offset based on weekStartsOn
+ let startingDayOfWeek = firstDayOfMonth.getDay() - weekStartsOn;
+ if (startingDayOfWeek < 0) startingDayOfWeek += 7;
+
+ // Calculate total cells
+ const totalDays = daysInMonth + startingDayOfWeek;
+ const totalRows = hasVariableRowCount ? Math.ceil(totalDays / 7) : 6;
+ const totalCells = totalRows * 7;
+
+ return {
+ daysInMonth,
+ startingDayOfWeek,
+ totalCells,
+ };
+ }, [year, month, weekStartsOn, hasVariableRowCount]);
+
+ // Generate day names
+ const dayNames = useMemo(() => {
+ const names = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
+ const rotated: string[] = [];
+ for (let i = 0; i < 7; i++) {
+ rotated.push(names[(i + weekStartsOn) % 7]);
+ }
+ return rotated;
+ }, [weekStartsOn]);
+
+ // Generate days array
+ const days = useMemo(() => {
+ const {daysInMonth, startingDayOfWeek, totalCells} = gridInfo;
+ const result: CalendarDay[] = [];
+
+ for (let i = 0; i < totalCells; i++) {
+ const dayOffset = i - startingDayOfWeek + 1;
+ const date = new Date(year, month, dayOffset);
+ const isOutside = dayOffset < 1 || dayOffset > daysInMonth;
+
+ result.push({
+ date,
+ iso: dateToISO(date),
+ isOutside,
+ dayNumber: date.getDate(),
+ });
+ }
+
+ return result;
+ }, [year, month, gridInfo]);
+
+ // Group days into weeks
+ const weeks = useMemo(() => {
+ const result: CalendarDay[][] = [];
+ for (let i = 0; i < days.length; i += 7) {
+ result.push(days.slice(i, i + 7));
+ }
+ return result;
+ }, [days]);
+
+ return {
+ days,
+ weeks,
+ dayNames,
+ totalCells: gridInfo.totalCells,
+ };
+}
diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
new file mode 100644
index 0000000000..f4839c74ef
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
@@ -0,0 +1,188 @@
+/**
+ * @file useCalendarNavigation.ts
+ * @input Uses React useState, useMemo, useCallback
+ * @output Exports useCalendarNavigation hook for month navigation
+ * @position Calendar-specific hook; used by XDSCalendar
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Calendar/hooks/index.ts
+ */
+
+import {useState, useMemo, useCallback} from 'react';
+import type {ISODateString} from '../XDSCalendar';
+
+/**
+ * Configuration for calendar navigation
+ */
+export interface UseCalendarNavigationOptions {
+ /** Initial value to determine starting month */
+ initialValue?: ISODateString;
+ /** Controlled focus date (which month is visible) */
+ focusDate?: ISODateString;
+ /** Callback when visible month changes */
+ onFocusDateChange?: (focusDate: ISODateString) => void;
+ /** Number of months to display */
+ numberOfMonths?: 1 | 2;
+}
+
+/**
+ * Return type for useCalendarNavigation hook
+ */
+export interface UseCalendarNavigationReturn {
+ /** The base month (first day of the focus month) */
+ baseMonth: Date;
+ /** Array of visible months to render */
+ visibleMonths: Date[];
+ /** Formatted label for the month header */
+ monthYearLabel: string;
+ /** Navigate to previous/next month */
+ navigateMonth: (
+ delta: number,
+ focusedDate?: ISODateString,
+ offset?: number,
+ ) => void;
+ /** Target date to focus after navigation */
+ pendingFocus: ISODateString | null;
+ /** Clear the pending focus */
+ clearPendingFocus: () => void;
+}
+
+/**
+ * Convert a Date to ISO date string format.
+ */
+function dateToISO(date: Date): ISODateString {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}` as ISODateString;
+}
+
+/**
+ * Parse ISO date string to Date object.
+ */
+function parseISO(str: ISODateString): Date {
+ const [year, month, day] = str.split('-').map(Number);
+ return new Date(year, month - 1, day);
+}
+
+/**
+ * Hook for managing calendar month navigation.
+ *
+ * Handles the current focus date (which month is visible), previous/next
+ * navigation, and pending focus for keyboard navigation across months.
+ *
+ * @example
+ * ```tsx
+ * const {
+ * visibleMonths,
+ * monthYearLabel,
+ * navigateMonth,
+ * pendingFocus,
+ * clearPendingFocus,
+ * } = useCalendarNavigation({
+ * initialValue: '2026-01-15',
+ * numberOfMonths: 1,
+ * });
+ *
+ * // Navigate to next month
+ * navigateMonth(1);
+ *
+ * // Navigate from arrow key (with focus tracking)
+ * navigateMonth(1, focusedDate, 1); // horizontal offset
+ * navigateMonth(1, focusedDate, 7); // vertical offset
+ * ```
+ */
+export function useCalendarNavigation(
+ options: UseCalendarNavigationOptions,
+): UseCalendarNavigationReturn {
+ const {
+ initialValue,
+ focusDate: focusDateProp,
+ onFocusDateChange,
+ numberOfMonths = 1,
+ } = options;
+
+ // Pending focus target after month navigation
+ const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
+
+ // Internal focus date state
+ const [internalFocusDate, setInternalFocusDate] = useState<Date>(() => {
+ if (focusDateProp) return parseISO(focusDateProp);
+ if (initialValue) return parseISO(initialValue);
+ return new Date();
+ });
+
+ // Determine if focus is controlled
+ const isControlledFocus =
+ focusDateProp !== undefined && onFocusDateChange !== undefined;
+ const focusDate = isControlledFocus
+ ? parseISO(focusDateProp)
+ : internalFocusDate;
+
+ // Base month (first day of focus month)
+ const baseMonth = useMemo(() => {
+ const d = new Date(focusDate);
+ d.setDate(1);
+ return d;
+ }, [focusDate]);
+
+ // Generate visible months
+ const visibleMonths = useMemo(() => {
+ return Array.from({length: numberOfMonths}, (_, i) => {
+ const m = new Date(baseMonth);
+ m.setMonth(baseMonth.getMonth() + i);
+ return m;
+ });
+ }, [baseMonth, numberOfMonths]);
+
+ // Format month header
+ const monthYearLabel = useMemo(() => {
+ const formatter = new Intl.DateTimeFormat(undefined, {
+ year: 'numeric',
+ month: 'long',
+ });
+ if (numberOfMonths === 1) {
+ return formatter.format(visibleMonths[0]);
+ }
+ return visibleMonths.map(m => formatter.format(m)).join(' – ');
+ }, [visibleMonths, numberOfMonths]);
+
+ // Navigate to previous/next month
+ const navigateMonth = useCallback(
+ (delta: number, focusedDate?: ISODateString, offset?: number) => {
+ const newDate = new Date(baseMonth);
+ newDate.setMonth(baseMonth.getMonth() + delta);
+ const newISO = dateToISO(newDate);
+
+ // Calculate target focus date if provided
+ if (focusedDate) {
+ const currentDate = parseISO(focusedDate);
+ // Use the provided offset (1 for horizontal, 7 for vertical)
+ const daysToMove = offset ?? 7;
+ currentDate.setDate(currentDate.getDate() + delta * daysToMove);
+ setPendingFocus(dateToISO(currentDate));
+ }
+
+ if (onFocusDateChange) {
+ onFocusDateChange(newISO);
+ } else {
+ setInternalFocusDate(newDate);
+ }
+ },
+ [baseMonth, onFocusDateChange],
+ );
+
+ // Clear pending focus
+ const clearPendingFocus = useCallback(() => {
+ setPendingFocus(null);
+ }, []);
+
+ return {
+ baseMonth,
+ visibleMonths,
+ monthYearLabel,
+ navigateMonth,
+ pendingFocus,
+ clearPendingFocus,
+ };
+}
diff --git a/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts
new file mode 100644
index 0000000000..140ec8211e
--- /dev/null
+++ b/packages/core/src/Calendar/hooks/useCalendarRovingTabindex.ts
@@ -0,0 +1,114 @@
+/**
+ * @file useCalendarRovingTabindex.ts
+ * @input Uses React useMemo
+ * @output Exports useCalendarRovingTabindex hook for accessible grid navigation
+ * @position Calendar-specific hook; used by XDSCalendar
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Calendar/hooks/index.ts
+ */
+
+import {useMemo} from 'react';
+import type {ISODateString} from '../XDSCalendar';
+import type {CalendarDay} from './useCalendarDays';
+
+/**
+ * Configuration for calendar roving tabindex
+ */
+export interface UseCalendarRovingTabindexOptions {
+ /** All days in the grid */
+ days: CalendarDay[];
+ /** Today's date */
+ today: Date;
+ /** The year being displayed */
+ year: number;
+ /** The month being displayed (0-11) */
+ month: number;
+ /** Function to check if a date is disabled */
+ isDateDisabled: (date: Date) => boolean;
+}
+
+/**
+ * Return type for useCalendarRovingTabindex hook
+ */
+export interface UseCalendarRovingTabindexReturn {
+ /** The ISO date string of the tabbable element, or null */
+ tabbableDate: ISODateString | null;
+ /** Check if a specific date is the tabbable one */
+ isTabbable: (iso: ISODateString) => boolean;
+}
+
+/**
+ * Convert a Date to ISO date string format.
+ */
+function dateToISO(date: Date): ISODateString {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}` as ISODateString;
+}
+
+/**
+ * Hook for managing roving tabindex in calendar grids.
+ *
+ * Implements the WAI-ARIA roving tabindex pattern where only one element
+ * in a group has tabindex="0" while others have tabindex="-1".
+ *
+ * Priority for tabbable element:
+ * 1. Today if visible in the current month and enabled
+ * 2. First enabled day in the month
+ *
+ * @example
+ * ```tsx
+ * const {tabbableDate, isTabbable} = useCalendarRovingTabindex({
+ * days,
+ * today: new Date(),
+ * year: 2026,
+ * month: 0,
+ * isDateDisabled,
+ * });
+ *
+ * // In day rendering:
+ * <button tabIndex={isTabbable(day.iso) ? 0 : -1}>
+ * {day.dayNumber}
+ * </button>
+ * ```
+ */
+export function useCalendarRovingTabindex(
+ options: UseCalendarRovingTabindexOptions,
+): UseCalendarRovingTabindexReturn {
+ const {days, today, year, month, isDateDisabled} = options;
+
+ // Determine which day should be tabbable
+ const tabbableDate = useMemo(() => {
+ // Check if today is in this month
+ const isTodayInMonth =
+ today.getFullYear() === year && today.getMonth() === month;
+
+ // If today is in this month and enabled, use it
+ if (isTodayInMonth && !isDateDisabled(today)) {
+ return dateToISO(today);
+ }
+
+ // Otherwise, find first enabled day in this month
+ for (const day of days) {
+ if (!day.isOutside && !isDateDisabled(day.date)) {
+ return day.iso;
+ }
+ }
+
+ return null;
+ }, [days, today, year, month, isDateDisabled]);
+
+ // Check if a specific date is tabbable
+ const isTabbable = useMemo(() => {
+ return (iso: ISODateString): boolean => {
+ return tabbableDate !== null && iso === tabbableDate;
+ };
+ }, [tabbableDate]);
+
+ return {
+ tabbableDate,
+ isTabbable,
+ };
+}
diff --git a/packages/core/src/Calendar/index.ts b/packages/core/src/Calendar/index.ts
index d244025e16..34d7aab1e3 100644
--- a/packages/core/src/Calendar/index.ts
+++ b/packages/core/src/Calendar/index.ts
@@ -1,7 +1,7 @@
/**
* @file index.ts
- * @input Imports XDSCalendar component and types from XDSCalendar.tsx
- * @output Exports XDSCalendar, XDSCalendarProps, ISODateString, DayOfWeek, DateRange
+ * @input Imports calendar components and types
+ * @output Exports XDSCalendar and related types
* @position Component entry point; re-exported by /packages/core/src/index.ts
*
* SYNC: When modified, update this header and /packages/core/src/Calendar/README.md
@@ -14,3 +14,33 @@ export type {
DayOfWeek,
DateRange,
} from './XDSCalendar';
+
+// Re-export hooks for advanced usage
+export {
+ useCalendarDays,
+ useCalendarConstraints,
+ useCalendarNavigation,
+ useCalendarRovingTabindex,
+} from './hooks';
+export type {
+ CalendarDay,
+ UseCalendarDaysOptions,
+ UseCalendarDaysReturn,
+ UseCalendarConstraintsOptions,
+ UseCalendarConstraintsReturn,
+ UseCalendarNavigationOptions,
+ UseCalendarNavigationReturn,
+ UseCalendarRovingTabindexOptions,
+ UseCalendarRovingTabindexReturn,
+} from './hooks';
+
+// Re-export calendar-specific utilities for advanced usage
+export {
+ isSameDay,
+ isDateInRange,
+ getWeekNumber,
+ formatAccessibleDate,
+} from './utils';
+
+// Re-export theme styles for customization
+export {dayCellTheme} from './styles';
diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.ts
new file mode 100644
index 0000000000..1bcd553b3c
--- /dev/null
+++ b/packages/core/src/Calendar/styles.ts
@@ -0,0 +1,284 @@
+/**
+ * @file styles.ts
+ * @input Uses stylex, theme tokens
+ * @output Exports calendar styles (structural) and theme styles (customizable)
+ * @position Shared styles; used by XDSCalendar
+ *
+ * Style Organization:
+ * - *Styles objects: Structural/layout styles (spacing, sizing, positioning)
+ * - *Theme objects: Themeable styles (colors, borders) that can be overridden
+ *
+ * SYNC: When modified, update this header
+ */
+
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ transitionVars,
+ textSizeVars,
+} from '../theme/tokens.stylex';
+
+// =============================================================================
+// Calendar Container Styles
+// =============================================================================
+
+export const calendarStyles = stylex.create({
+ calendar: {
+ display: 'inline-block',
+ padding: spacingVars['--spacing-3'],
+ minWidth: '220px',
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: spacingVars['--spacing-2'],
+ gap: spacingVars['--spacing-2'],
+ },
+ monthYearLabel: {
+ flex: 1,
+ textAlign: 'center',
+ fontWeight: 600,
+ fontSize: textSizeVars['--text-base'],
+ color: colorVars['--color-text-primary'],
+ },
+ monthsContainer: {
+ display: 'flex',
+ gap: spacingVars['--spacing-4'],
+ },
+ navIcon: {
+ width: '16px',
+ height: '16px',
+ },
+});
+
+// =============================================================================
+// Month Grid Styles
+// =============================================================================
+
+export const monthGridStyles = stylex.create({
+ monthGrid: {
+ flex: '1 1 0',
+ },
+ weekHeader: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(7, 1fr)',
+ marginBottom: spacingVars['--spacing-1'],
+ },
+ weekHeaderWithNumbers: {
+ gridTemplateColumns: 'auto repeat(7, 1fr)',
+ },
+ dayName: {
+ width: '32px',
+ height: '32px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: textSizeVars['--text-xsm'],
+ fontWeight: 400,
+ color: colorVars['--color-text-secondary'],
+ },
+ weekNumberHeader: {
+ width: '32px',
+ },
+ daysGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(7, 1fr)',
+ },
+ daysGridWithNumbers: {
+ gridTemplateColumns: 'auto repeat(7, 1fr)',
+ },
+ weekNumber: {
+ width: '32px',
+ height: '32px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: textSizeVars['--text-xsm'],
+ color: colorVars['--color-text-secondary'],
+ },
+ weekRow: {
+ display: 'contents',
+ },
+});
+
+// =============================================================================
+// Day Cell Styles - Structural (layout, sizing, positioning)
+// =============================================================================
+
+export const dayCellStyles = stylex.create({
+ // Cell container
+ cell: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '32px',
+ },
+
+ // Range background - structural positioning
+ rangeBg: {
+ position: 'absolute',
+ top: '2px',
+ bottom: '2px',
+ left: 0,
+ right: 0,
+ },
+ rangeBgRadiusLeft: {
+ left: '2px',
+ borderTopLeftRadius: radiusVars['--radius-rounded'],
+ borderBottomLeftRadius: radiusVars['--radius-rounded'],
+ },
+ rangeBgRadiusRight: {
+ right: '2px',
+ borderTopRightRadius: radiusVars['--radius-rounded'],
+ borderBottomRightRadius: radiusVars['--radius-rounded'],
+ },
+ rangeInsetLeft: {
+ left: '2px',
+ },
+ rangeInsetRight: {
+ right: '2px',
+ },
+
+ // Preview background - structural positioning
+ previewBg: {
+ position: 'absolute',
+ top: '2px',
+ bottom: '2px',
+ left: 0,
+ right: 0,
+ },
+ previewBgRadiusLeft: {
+ left: '2px',
+ borderTopLeftRadius: radiusVars['--radius-rounded'],
+ borderBottomLeftRadius: radiusVars['--radius-rounded'],
+ },
+ previewBgRadiusRight: {
+ right: '2px',
+ borderTopRightRadius: radiusVars['--radius-rounded'],
+ borderBottomRightRadius: radiusVars['--radius-rounded'],
+ },
+ previewStart: {
+ left: '2px',
+ borderTopLeftRadius: radiusVars['--radius-rounded'],
+ borderBottomLeftRadius: radiusVars['--radius-rounded'],
+ },
+ previewEnd: {
+ right: '2px',
+ borderTopRightRadius: radiusVars['--radius-rounded'],
+ borderBottomRightRadius: radiusVars['--radius-rounded'],
+ },
+
+ // Day button - structural
+ day: {
+ width: '28px',
+ height: '28px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: '50%',
+ borderWidth: 0,
+ borderStyle: 'none',
+ cursor: 'pointer',
+ fontFamily: 'inherit',
+ fontSize: textSizeVars['--text-sm'],
+ padding: 0,
+ position: 'relative',
+ zIndex: 1,
+ transitionProperty: 'background-color, color',
+ transitionDuration: transitionVars['--transition-fast'],
+ },
+
+ // State modifiers - structural only
+ dayOutside: {
+ opacity: 0.5,
+ },
+ dayToday: {},
+ dayTodayInRange: {},
+ daySelected: {},
+ dayDisabled: {
+ cursor: 'not-allowed',
+ },
+});
+
+// =============================================================================
+// Day Cell Theme - Colors and visual appearance (customizable)
+// =============================================================================
+
+export const dayCellTheme = stylex.create({
+ // Range background color
+ rangeBg: {
+ backgroundColor: colorVars['--color-accent-deemphasized'],
+ },
+
+ // Preview background (dotted border style)
+ previewBg: {
+ borderTopWidth: 1,
+ borderTopStyle: 'dotted',
+ borderTopColor: colorVars['--color-divider-emphasized'],
+ borderBottomWidth: 1,
+ borderBottomStyle: 'dotted',
+ borderBottomColor: colorVars['--color-divider-emphasized'],
+ borderLeftWidth: 1,
+ borderLeftStyle: 'dotted',
+ borderLeftColor: colorVars['--color-divider-emphasized'],
+ borderRightWidth: 1,
+ borderRightStyle: 'dotted',
+ borderRightColor: colorVars['--color-divider-emphasized'],
+ },
+
+ // Day button - default state
+ day: {
+ color: colorVars['--color-text-primary'],
+ backgroundColor: 'transparent',
+ backgroundImage: {
+ default: null,
+ ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
+ },
+ outline: {
+ default: null,
+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': '2px',
+ },
+ },
+
+ // Outside days (adjacent months)
+ dayOutside: {
+ color: colorVars['--color-text-secondary'],
+ },
+
+ // Today indicator
+ dayToday: {
+ boxShadow: `inset 0 0 0 1px ${colorVars['--color-divider-emphasized']}`,
+ },
+
+ // Today when inside a selected range
+ dayTodayInRange: {
+ boxShadow: `inset 0 0 0 1px ${colorVars['--color-text-primary']}`,
+ },
+
+ // Selected state (single selection or range endpoints)
+ daySelected: {
+ backgroundColor: colorVars['--color-accent'],
+ color: colorVars['--color-text-on-media'],
+ backgroundImage: {
+ default: null,
+ ':hover': `linear-gradient(${colorVars['--color-hover-overlay']}, ${colorVars['--color-hover-overlay']})`,
+ },
+ },
+
+ // Disabled state
+ dayDisabled: {
+ opacity: 0.3,
+ backgroundImage: {
+ default: null,
+ ':hover': null,
+ },
+ },
+});
diff --git a/packages/core/src/Calendar/utils.ts b/packages/core/src/Calendar/utils.ts
new file mode 100644
index 0000000000..a08977277c
--- /dev/null
+++ b/packages/core/src/Calendar/utils.ts
@@ -0,0 +1,72 @@
+/**
+ * @file utils.ts
+ * @input None
+ * @output Exports shared date utility functions for calendar components
+ * @position Shared utilities; used by XDSCalendar, XDSCalendarMonthGrid, XDSCalendarDayCell
+ *
+ * SYNC: When modified, update this header
+ */
+
+import type {ISODateString} from './XDSCalendar';
+
+/**
+ * Convert a Date to ISO date string format (YYYY-MM-DD).
+ */
+export function dateToISO(date: Date): ISODateString {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}` as ISODateString;
+}
+
+/**
+ * Parse ISO date string (YYYY-MM-DD) to Date object.
+ */
+export function parseISO(str: ISODateString): Date {
+ const [year, month, day] = str.split('-').map(Number);
+ return new Date(year, month - 1, day);
+}
+
+/**
+ * Check if two dates are the same day.
+ */
+export function isSameDay(a: Date, b: Date): boolean {
+ return (
+ a.getFullYear() === b.getFullYear() &&
+ a.getMonth() === b.getMonth() &&
+ a.getDate() === b.getDate()
+ );
+}
+
+/**
+ * Check if a date is within a range (inclusive).
+ */
+export function isDateInRange(date: Date, start: Date, end: Date): boolean {
+ const time = date.getTime();
+ return time >= start.getTime() && time <= end.getTime();
+}
+
+/**
+ * Get ISO week number for a date.
+ */
+export function getWeekNumber(date: Date): number {
+ const d = new Date(
+ Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
+ );
+ const dayNum = d.getUTCDay() || 7;
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
+ return Math.ceil(((d.getTime() - yearStart.getTime()) / 86400000 + 1) / 7);
+}
+
+/**
+ * Format a date for accessible screen reader label.
+ */
+export function formatAccessibleDate(date: Date): string {
+ return new Intl.DateTimeFormat(undefined, {
+ weekday: 'long',
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ }).format(date);
+}
diff --git a/packages/core/src/DatePicker/README.md b/packages/core/src/DatePicker/README.md
new file mode 100644
index 0000000000..619bff95bc
--- /dev/null
+++ b/packages/core/src/DatePicker/README.md
@@ -0,0 +1,97 @@
+# /packages/core/src/DatePicker
+
+XDSDatePicker component combining a text input with a calendar popover for date selection.
+
+## Features
+
+- **Text Input**: Manual date entry with flexible parsing (supports various formats)
+- **Calendar Popover**: Click icon or use keyboard to open calendar picker
+- **Date Constraints**: `min`, `max`, and custom `dateConstraints` functions
+- **Accessibility**: Full keyboard navigation, focus trapping, screen reader support
+- **Field Integration**: Built on XDSField for consistent label, description, and validation states
+
+## Usage
+
+```tsx
+import { XDSDatePicker } from '@xds/core/DatePicker';
+
+// Basic usage
+<XDSDatePicker
+ label="Event date"
+ value={date}
+ onChange={setDate}
+/>
+
+// With constraints
+<XDSDatePicker
+ label="Departure date"
+ value={date}
+ onChange={setDate}
+ min="2026-01-01"
+ max="2026-12-31"
+ placeholder="Pick a date"
+/>
+
+// Two-month calendar
+<XDSDatePicker
+ label="Check-in date"
+ value={date}
+ onChange={setDate}
+ numberOfMonths={2}
+/>
+
+// With description and required
+<XDSDatePicker
+ label="Due date"
+ description="When should this task be completed?"
+ isRequired
+ value={date}
+ onChange={setDate}
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| --------------- | --------------------------------------------- | ----------------- | -------------------------------- |
+| label | `string` | — | Label text (required) |
+| isLabelHidden | `boolean` | `false` | Visually hide label |
+| description | `string` | — | Helper text below label |
+| isOptional | `boolean` | `false` | Show "(optional)" indicator |
+| isRequired | `boolean` | `false` | Mark field as required |
+| isDisabled | `boolean` | `false` | Disable input and calendar |
+| value | `ISODateString` | — | Selected date (YYYY-MM-DD) |
+| onChange | `(value: ISODateString \| undefined) => void` | — | Selection callback |
+| min | `ISODateString` | — | Minimum selectable date |
+| max | `ISODateString` | — | Maximum selectable date |
+| dateConstraints | `Array<(date: Date) => boolean>` | — | Custom constraint functions |
+| placeholder | `string` | `"Select a date"` | Input placeholder text |
+| size | `'sm' \| 'md'` | `'md'` | Input size |
+| numberOfMonths | `1 \| 2` | `1` | Months shown in calendar popover |
+
+## Keyboard Navigation
+
+- **Tab**: Move between input and calendar icon button
+- **Enter/Space** on icon: Open calendar and move focus into it
+- **Escape**: Close calendar popover
+- **Arrow keys** in calendar: Navigate between days
+- **Page Up/Down** in calendar: Navigate between months
+
+## Date Input Parsing
+
+The text input accepts various date formats:
+
+- ISO format: `2026-01-28`
+- US format: `01/28/2026`, `1/28/2026`
+- Written: `Jan 28, 2026`, `January 28 2026`
+
+Invalid input reverts to the previous valid value on blur.
+
+## Files
+
+| File | Role | Purpose |
+| ---------------------- | ------ | ------------------------ |
+| XDSDatePicker.tsx | Core | Component implementation |
+| XDSDatePicker.test.tsx | Test | Unit tests |
+| index.ts | Export | Public API exports |
+| README.md | Docs | This documentation |
diff --git a/packages/core/src/DatePicker/XDSDatePicker.test.tsx b/packages/core/src/DatePicker/XDSDatePicker.test.tsx
new file mode 100644
index 0000000000..0a6a0d4350
--- /dev/null
+++ b/packages/core/src/DatePicker/XDSDatePicker.test.tsx
@@ -0,0 +1,110 @@
+/**
+ * @file XDSDatePicker.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSDatePicker component
+ * @output Unit tests for XDSDatePicker component behavior
+ * @position Testing; validates XDSDatePicker.tsx implementation
+ *
+ * SYNC: When XDSDatePicker.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {XDSDatePicker} from './XDSDatePicker';
+
+describe('XDSDatePicker', () => {
+ it('renders with label', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ expect(screen.getByLabelText('Date')).toBeInTheDocument();
+ });
+
+ it('renders with placeholder', () => {
+ render(
+ <XDSDatePicker
+ label="Date"
+ onChange={() => {}}
+ placeholder="Pick a date"
+ />,
+ );
+ expect(screen.getByPlaceholderText('Pick a date')).toBeInTheDocument();
+ });
+
+ it('displays formatted date when value is provided', () => {
+ render(
+ <XDSDatePicker label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+ expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();
+ });
+
+ it('forwards ref correctly', () => {
+ const ref = vi.fn();
+ render(<XDSDatePicker ref={ref} label="Date" onChange={() => {}} />);
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+
+ it('visually hides label when isLabelHidden is true', () => {
+ render(<XDSDatePicker label="Date" isLabelHidden onChange={() => {}} />);
+ const label = screen.getByText('Date');
+ expect(label).toBeInTheDocument();
+ expect(screen.getByLabelText('Date')).toBeInTheDocument();
+ });
+
+ it('shows label visually by default', () => {
+ render(<XDSDatePicker label="Event date" onChange={() => {}} />);
+ const label = screen.getByText('Event date');
+ expect(label).toBeVisible();
+ });
+
+ it('sets aria-required when isRequired is true', () => {
+ render(<XDSDatePicker label="Date" isRequired onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toHaveAttribute(
+ 'aria-required',
+ 'true',
+ );
+ });
+
+ it('does not set aria-required when isRequired is false', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-required');
+ });
+
+ it('sets disabled attribute when isDisabled is true', () => {
+ render(<XDSDatePicker label="Date" isDisabled onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toBeDisabled();
+ });
+
+ it('is not disabled by default', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).not.toBeDisabled();
+ });
+
+ it('renders calendar icon', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ const svg = document.querySelector('svg');
+ expect(svg).toBeInTheDocument();
+ });
+
+ it('calendar button has aria-haspopup="dialog" attribute', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('button', {name: 'Open calendar'})).toHaveAttribute(
+ 'aria-haspopup',
+ 'dialog',
+ );
+ });
+
+ it('calendar button is focusable and clickable', () => {
+ render(<XDSDatePicker label="Date" onChange={() => {}} />);
+ const button = screen.getByRole('button', {name: 'Open calendar'});
+ expect(button).toBeInTheDocument();
+ expect(button).not.toBeDisabled();
+ });
+
+ it('calendar button is disabled when isDisabled is true', () => {
+ render(<XDSDatePicker label="Date" isDisabled onChange={() => {}} />);
+ const button = screen.getByRole('button', {name: 'Open calendar'});
+ expect(button).toBeDisabled();
+ });
+
+ // Note: Tests involving blur that trigger popover are skipped because
+ // jsdom doesn't support the Popover API (showPopover is not a function).
+ // These behaviors are tested in the browser via Storybook.
+});
diff --git a/packages/core/src/DatePicker/XDSDatePicker.tsx b/packages/core/src/DatePicker/XDSDatePicker.tsx
new file mode 100644
index 0000000000..aabf9bde53
--- /dev/null
+++ b/packages/core/src/DatePicker/XDSDatePicker.tsx
@@ -0,0 +1,409 @@
+/**
+ * @file XDSDatePicker.tsx
+ * @input Uses React forwardRef, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon, XDSCalendar, useXDSPopover
+ * @output Exports XDSDatePicker component, XDSDatePickerProps
+ * @position Core implementation; consumed by index.ts, tested by XDSDatePicker.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/DatePicker/README.md (props table, features, implementation notes)
+ * - /packages/core/src/DatePicker/XDSDatePicker.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/DatePicker/index.ts (exports if types change)
+ * - /apps/storybook/stories/DatePicker.stories.tsx (storybook stories)
+ */
+
+import {
+ forwardRef,
+ useId,
+ useState,
+ useEffect,
+ useCallback,
+ useRef,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {CalendarDaysIcon} from '@heroicons/react/24/outline';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ transitionVars,
+ typographyVars,
+ textSizeVars,
+ lineHeightVars,
+ elevationVars,
+} from '../theme/tokens.stylex';
+import {XDSField} from '../Field';
+import {XDSIcon} from '../Icon';
+import {XDSCalendar, type ISODateString} from '../Calendar';
+import {useXDSPopover} from '../Layer';
+import {parseDateInput, formatDisplayDate} from '../utils';
+
+const styles = stylex.create({
+ wrapper: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderWidth: 1,
+ borderStyle: 'solid',
+ borderColor: {
+ default: colorVars['--color-divider-emphasized'],
+ ':hover': colorVars['--color-divider-high-contrast'],
+ },
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: colorVars['--color-surface'],
+ transitionProperty: 'border-color, outline',
+ transitionDuration: transitionVars['--transition-fast'],
+ outline: {
+ default: 'none',
+ ':focus-within': `2px solid ${colorVars['--color-focus-outline']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-within': '1px',
+ },
+ },
+ wrapperDisabled: {
+ cursor: 'not-allowed',
+ opacity: 0.5,
+ borderColor: colorVars['--color-divider-emphasized'],
+ },
+ iconButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
+ },
+ outlineOffset: 1,
+ },
+ iconButtonDisabled: {
+ cursor: 'not-allowed',
+ },
+ input: {
+ display: 'block',
+ flex: 1,
+ minWidth: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ padding: 0,
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-base'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ color: colorVars['--color-text-primary'],
+ backgroundColor: 'transparent',
+ outline: 'none',
+ '::placeholder': {
+ color: colorVars['--color-text-placeholder'],
+ },
+ },
+ inputDisabled: {
+ cursor: 'not-allowed',
+ },
+ popover: {
+ backgroundColor: colorVars['--color-popover'],
+ borderRadius: radiusVars['--radius-container'],
+ boxShadow: elevationVars['--elevation-menu'],
+ },
+});
+
+const sizeStyles = stylex.create({
+ sm: {
+ height: 18,
+ },
+ md: {
+ height: 26,
+ },
+});
+
+export type XDSDatePickerSize = keyof typeof sizeStyles;
+
+export interface XDSDatePickerProps {
+ /**
+ * Label text for the input (required for accessibility).
+ */
+ label: string;
+
+ /**
+ * Whether to visually hide the label (still accessible to screen readers).
+ * @default false
+ */
+ isLabelHidden?: boolean;
+
+ /**
+ * Description text displayed between the label and input.
+ */
+ description?: string;
+
+ /**
+ * Whether the field is optional. Mutually exclusive with isRequired.
+ * @default false
+ */
+ isOptional?: boolean;
+
+ /**
+ * Whether the field is required. Mutually exclusive with isOptional.
+ * @default false
+ */
+ isRequired?: boolean;
+
+ /**
+ * Whether the input is disabled.
+ * @default false
+ */
+ isDisabled?: boolean;
+
+ /**
+ * The selected date in ISO format (YYYY-MM-DD).
+ */
+ value?: ISODateString;
+
+ /**
+ * Callback fired when the date changes.
+ * Called with undefined when input is cleared.
+ */
+ onChange: (value: ISODateString | undefined) => void;
+
+ /**
+ * Minimum selectable date in ISO format.
+ */
+ min?: ISODateString;
+
+ /**
+ * Maximum selectable date in ISO format.
+ */
+ max?: ISODateString;
+
+ /**
+ * Custom date constraint functions. Date is disabled if ANY function returns false.
+ */
+ dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
+
+ /**
+ * Placeholder text shown when no date is selected.
+ * @default "Select a date"
+ */
+ placeholder?: string;
+
+ /**
+ * The size of the input.
+ * - 'sm': Compact size (18px height)
+ * - 'md': Default size (26px height)
+ * @default 'md'
+ */
+ size?: XDSDatePickerSize;
+
+ /**
+ * Number of months to display in the calendar popover.
+ * @default 1
+ */
+ numberOfMonths?: 1 | 2;
+}
+
+/**
+ * A date picker component combining a text input with a calendar popover.
+ *
+ * @example
+ * ```tsx
+ * <XDSDatePicker
+ * label="Event date"
+ * value={date}
+ * onChange={setDate}
+ * />
+ * ```
+ */
+export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
+ (
+ {
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ value,
+ onChange,
+ min,
+ max,
+ dateConstraints,
+ placeholder = 'Select a date',
+ size = 'md',
+ numberOfMonths = 1,
+ },
+ ref,
+ ) => {
+ const id = useId();
+ const descriptionID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ // Track input text separately from value for manual editing
+ const [inputValue, setInputValue] = useState('');
+
+ // Use XDSPopover for popover rendering, positioning, and focus trapping
+ const popover = useXDSPopover({
+ xstyle: styles.popover,
+ dialogLabel: 'Choose date',
+ closeButtonLabel: 'Close calendar',
+ onHide: () => {
+ // Return focus to input when popover closes
+ inputRef.current?.focus();
+ },
+ });
+
+ // Sync input value with controlled value
+ useEffect(() => {
+ if (value) {
+ setInputValue(formatDisplayDate(value));
+ } else {
+ setInputValue('');
+ }
+ }, [value]);
+
+ // Handle opening the popover
+ const handleOpen = useCallback(() => {
+ if (!isDisabled && !popover.isOpen) {
+ popover.show();
+ }
+ }, [isDisabled, popover]);
+
+ // Handle date selection from calendar
+ const handleDateSelect = useCallback(
+ (selectedDate: ISODateString) => {
+ onChange(selectedDate);
+ popover.hide();
+ },
+ [onChange, popover],
+ );
+
+ // Handle input text change
+ const handleInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ setInputValue(e.target.value);
+ },
+ [],
+ );
+
+ // Handle blur - parse the input and validate
+ const handleBlur = useCallback(() => {
+ if (!inputValue.trim()) {
+ // Empty input clears the value
+ if (value !== undefined) {
+ onChange(undefined);
+ }
+ return;
+ }
+
+ const parsed = parseDateInput(inputValue);
+ if (parsed) {
+ // Valid date - update if different
+ if (parsed !== value) {
+ onChange(parsed);
+ }
+ } else {
+ // Invalid date - revert to previous value
+ if (value) {
+ setInputValue(formatDisplayDate(value));
+ } else {
+ setInputValue('');
+ }
+ }
+ }, [inputValue, value, onChange]);
+
+ // Handle keyboard events on input
+ const handleInputKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === 'Escape' && popover.isOpen) {
+ e.preventDefault();
+ popover.hide();
+ }
+ },
+ [popover],
+ );
+
+ // Combine refs
+ const setRefs = useCallback(
+ (el: HTMLInputElement | null) => {
+ inputRef.current = el;
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
+ }
+ },
+ [ref],
+ );
+
+ return (
+ <XDSField
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}>
+ <div
+ ref={popover.triggerRef}
+ {...stylex.props(
+ styles.wrapper,
+ isDisabled && styles.wrapperDisabled,
+ )}>
+ <button
+ type="button"
+ onClick={handleOpen}
+ disabled={isDisabled}
+ aria-label="Open calendar"
+ {...popover.triggerProps}
+ {...stylex.props(
+ styles.iconButton,
+ isDisabled && styles.iconButtonDisabled,
+ )}>
+ <XDSIcon icon={CalendarDaysIcon} size="sm" color="secondary" />
+ </button>
+ <input
+ ref={setRefs}
+ id={id}
+ type="text"
+ value={inputValue}
+ onChange={handleInputChange}
+ onBlur={handleBlur}
+ onClick={handleOpen}
+ onKeyDown={handleInputKeyDown}
+ placeholder={placeholder}
+ disabled={isDisabled}
+ aria-describedby={description ? descriptionID : undefined}
+ aria-required={isRequired === true ? 'true' : undefined}
+ {...stylex.props(
+ styles.input,
+ sizeStyles[size],
+ isDisabled && styles.inputDisabled,
+ )}
+ />
+ </div>
+ {popover.render(
+ <XDSCalendar
+ mode="single"
+ value={value}
+ onChange={handleDateSelect}
+ min={min}
+ max={max}
+ dateConstraints={dateConstraints}
+ numberOfMonths={numberOfMonths}
+ focusDate={value}
+ />,
+ {placement: 'below', alignment: 'start'},
+ )}
+ </XDSField>
+ );
+ },
+);
+
+XDSDatePicker.displayName = 'XDSDatePicker';
diff --git a/packages/core/src/DatePicker/index.ts b/packages/core/src/DatePicker/index.ts
new file mode 100644
index 0000000000..566ad50980
--- /dev/null
+++ b/packages/core/src/DatePicker/index.ts
@@ -0,0 +1,9 @@
+/**
+ * @file index.ts
+ * @input DatePicker component exports
+ * @output Re-exports XDSDatePicker and types
+ * @position Package entry point for DatePicker
+ */
+
+export {XDSDatePicker} from './XDSDatePicker';
+export type {XDSDatePickerProps, XDSDatePickerSize} from './XDSDatePicker';
diff --git a/packages/core/src/Layer/index.ts b/packages/core/src/Layer/index.ts
index 00a7da8427..482123e133 100644
--- a/packages/core/src/Layer/index.ts
+++ b/packages/core/src/Layer/index.ts
@@ -23,6 +23,10 @@ export type {
FixedLayerReturn,
} from './useXDSLayer';
+// Popover hook (combines layer + focus trap)
+export {useXDSPopover} from './useXDSPopover';
+export type {UseXDSPopoverOptions, UseXDSPopoverReturn} from './useXDSPopover';
+
// HoverCard hook and component
export {useXDSHoverCard} from './useXDSHoverCard';
export type {
diff --git a/packages/core/src/Layer/useXDSLayer.tsx b/packages/core/src/Layer/useXDSLayer.tsx
index 2227218d90..e64cf1531f 100644
--- a/packages/core/src/Layer/useXDSLayer.tsx
+++ b/packages/core/src/Layer/useXDSLayer.tsx
@@ -22,6 +22,7 @@ import type {StyleXStyles} from '@stylexjs/stylex';
// Extend React's HTMLAttributes to include popover API attributes
declare module 'react' {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
interface HTMLAttributes<T> {
popover?: 'auto' | 'manual' | '';
}
@@ -92,6 +93,13 @@ interface BaseLayerOptions {
* StyleX styles for the layer container
*/
xstyle?: StyleXStyles;
+
+ /**
+ * Whether clicking outside should dismiss the layer.
+ * When true, uses popover="auto" for native light-dismiss behavior.
+ * @default false
+ */
+ lightDismiss?: boolean;
}
/**
@@ -243,7 +251,7 @@ export function useXDSLayer(options: FixedLayerOptions): FixedLayerReturn;
export function useXDSLayer(
options: ContextLayerOptions | FixedLayerOptions,
): ContextLayerReturn | FixedLayerReturn {
- const {mode, onShow, onHide, xstyle} = options;
+ const {mode, onShow, onHide, xstyle, lightDismiss = false} = options;
const id = useId();
const anchorId = `--xds-layer-${id.replace(/:/g, '')}`;
@@ -323,14 +331,14 @@ export function useXDSLayer(
}
}}
id={id}
- popover="manual"
+ popover={lightDismiss ? 'auto' : 'manual'}
{...stylex.props(styles.base, xstyle)}
style={anchorStyle}>
{children}
</div>
);
},
- [anchorId, handleToggle, id, xstyle],
+ [anchorId, handleToggle, id, lightDismiss, xstyle],
);
// Render function for fixed mode
@@ -353,14 +361,14 @@ export function useXDSLayer(
}
}}
id={id}
- popover="manual"
+ popover={lightDismiss ? 'auto' : 'manual'}
{...stylex.props(styles.base, styles.fixed, xstyle)}
style={positionStyle}>
{children}
</div>
);
},
- [handleToggle, id, xstyle],
+ [handleToggle, id, lightDismiss, xstyle],
);
if (mode === 'context') {
diff --git a/packages/core/src/Layer/useXDSPopover.tsx b/packages/core/src/Layer/useXDSPopover.tsx
new file mode 100644
index 0000000000..1020dfb458
--- /dev/null
+++ b/packages/core/src/Layer/useXDSPopover.tsx
@@ -0,0 +1,384 @@
+/**
+ * @file useXDSPopover.tsx
+ * @input Uses useXDSLayer, useFocusTrap, React hooks
+ * @output Exports useXDSPopover hook for popover dialogs with focus trapping
+ * @position Higher-level layer utility; used by DatePicker, Combobox, etc.
+ *
+ * Combines popover layer behavior with focus trap for dialog-like popovers.
+ * Use this for interactive popover content that should trap focus.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/README.md
+ * - /packages/core/src/Layer/index.ts
+ */
+
+import React, {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ useXDSLayer,
+ type ContextRenderProps,
+ type LayerPlacement,
+ type LayerAlignment,
+} from './useXDSLayer';
+import {useFocusTrap} from '../hooks/useFocusTrap';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ textSizeVars,
+} from '../theme/tokens.stylex';
+
+const styles = stylex.create({
+ // Focus trap container
+ contentWrapper: {
+ position: 'relative',
+ },
+ // Hidden close button - visually hidden until focused
+ closeButton: {
+ position: 'absolute',
+ width: 1,
+ height: 1,
+ padding: 0,
+ margin: -1,
+ overflow: 'hidden',
+ clip: 'rect(0, 0, 0, 0)',
+ whiteSpace: 'nowrap',
+ borderWidth: 0,
+ pointerEvents: 'none', // Prevent mouse clicks when hidden
+ },
+ // Revealed state when focused - positioned bottom center, outside popover
+ closeButtonFocused: {
+ position: 'absolute',
+ bottom: 0,
+ left: '50%',
+ transform: 'translate(-50%, 100%)',
+ width: 'auto',
+ height: 'auto',
+ padding: spacingVars['--spacing-2'],
+ margin: 0,
+ overflow: 'visible',
+ clip: 'auto',
+ whiteSpace: 'nowrap',
+ // Inverted color palette (like tooltip): dark background, light text
+ backgroundColor: colorVars['--color-text-primary'],
+ color: colorVars['--color-surface'],
+ fontSize: textSizeVars['--text-sm'],
+ borderRadius: radiusVars['--radius-element'],
+ cursor: 'pointer',
+ borderWidth: 0,
+ borderStyle: 'none',
+ outline: `2px solid ${colorVars['--color-focus-outline']}`,
+ outlineOffset: 2,
+ zIndex: 1,
+ pointerEvents: 'auto', // Re-enable mouse clicks when visible
+ },
+});
+
+/**
+ * Options for useXDSPopover
+ */
+export interface UseXDSPopoverOptions {
+ /**
+ * Callback fired when popover is shown
+ */
+ onShow?: () => void;
+
+ /**
+ * Callback fired when popover is hidden.
+ * Use this to return focus to the trigger element.
+ */
+ onHide?: () => void;
+
+ /**
+ * StyleX styles for the popover container
+ */
+ xstyle?: StyleXStyles;
+
+ /**
+ * Whether clicking outside should dismiss the popover.
+ * @default true
+ */
+ hasLightDismiss?: boolean;
+
+ /**
+ * Whether to automatically focus the first focusable element when opened.
+ * @default true
+ */
+ hasAutoFocus?: boolean;
+
+ /**
+ * Whether to include a hidden close button for accessibility.
+ * The button appears when keyboard users tab past the last element.
+ * Set to false for menus or selectors with different focus behavior.
+ * @default true
+ */
+ hasCloseButton?: boolean;
+
+ /**
+ * Label for the hidden close button.
+ * Only used when hasCloseButton is true.
+ * @default "Close popover"
+ */
+ closeButtonLabel?: string;
+
+ /**
+ * Accessible label for the dialog.
+ * Required for screen readers to announce the dialog purpose.
+ */
+ dialogLabel?: string;
+}
+
+/**
+ * Return type for useXDSPopover
+ */
+export interface UseXDSPopoverReturn {
+ /**
+ * Ref callback to attach to the trigger element.
+ * Sets up CSS anchor positioning.
+ */
+ triggerRef: (el: HTMLElement | null) => void;
+
+ /**
+ * Ref for the popover content container (used internally for focus trapping).
+ * You typically don't need to use this directly - the render function
+ * automatically wraps content in a focus trap container.
+ */
+ contentRef: React.RefObject<HTMLElement | null>;
+
+ /**
+ * The CSS anchor name to use for positioning.
+ * Use when you need to set anchorName manually (e.g., display:contents wrapper).
+ */
+ anchorId: string;
+
+ /**
+ * Show the popover
+ */
+ show: () => void;
+
+ /**
+ * Hide the popover
+ */
+ hide: () => void;
+
+ /**
+ * Toggle the popover open/closed
+ */
+ toggle: () => void;
+
+ /**
+ * Whether the popover is currently open
+ */
+ isOpen: boolean;
+
+ /**
+ * Unique ID for aria-describedby or aria-controls
+ */
+ id: string;
+
+ /**
+ * Render function for popover content.
+ * Automatically wraps content in a focus trap container with a hidden close button.
+ *
+ * @example
+ * ```tsx
+ * {popover.render(
+ * <Calendar />,
+ * { placement: 'below', alignment: 'start' }
+ * )}
+ * ```
+ */
+ render: (children: ReactNode, props?: ContextRenderProps) => ReactNode;
+
+ /**
+ * ARIA attributes to spread on the trigger element
+ */
+ triggerProps: {
+ 'aria-haspopup': 'dialog';
+ 'aria-expanded': boolean;
+ 'aria-controls': string;
+ };
+}
+
+/**
+ * Hook for creating popover dialogs with focus trapping.
+ *
+ * Combines:
+ * - `useXDSLayer` for popover positioning using CSS anchor positioning
+ * - `useFocusTrap` for trapping focus within the popover content
+ * - Auto-focus first element on open
+ * - Escape key to close
+ * - Hidden close button that reveals on focus for accessibility
+ *
+ * The render function automatically wraps your content in a focus trap container
+ * and appends a hidden close button. The button appears at the end of the popover,
+ * is visually hidden until focused, then shows a tooltip-like message (default: "Close popover").
+ *
+ * @example
+ * ```tsx
+ * function DatePickerExample() {
+ * const inputRef = useRef<HTMLInputElement>(null);
+ * const popover = useXDSPopover({
+ * onHide: () => inputRef.current?.focus(),
+ * closeButtonLabel: 'Close calendar',
+ * });
+ *
+ * return (
+ * <>
+ * <input ref={inputRef} />
+ * <button
+ * ref={popover.triggerRef}
+ * onClick={popover.toggle}
+ * {...popover.triggerProps}
+ * >
+ * Open Calendar
+ * </button>
+ *
+ * {popover.render(
+ * <Calendar />,
+ * { placement: 'below', alignment: 'start' }
+ * )}
+ * </>
+ * );
+ * }
+ * ```
+ */
+export function useXDSPopover(
+ options: UseXDSPopoverOptions = {},
+): UseXDSPopoverReturn {
+ const {
+ onShow,
+ onHide,
+ xstyle,
+ hasLightDismiss = true,
+ hasAutoFocus = true,
+ hasCloseButton = true,
+ closeButtonLabel = 'Close popover',
+ dialogLabel,
+ } = options;
+
+ // Track whether close button is focused (to show tooltip)
+ const [isCloseButtonFocused, setIsCloseButtonFocused] = useState(false);
+
+ // Track the trigger element for returning focus
+ const triggerElementRef = useRef<HTMLElement | null>(null);
+
+ // Core layer for popover positioning
+ const layer = useXDSLayer({
+ mode: 'context',
+ lightDismiss: hasLightDismiss,
+ xstyle,
+ onShow,
+ onHide,
+ });
+
+ // Focus trap for the popover content
+ const {containerRef: contentRef, focusFirst} = useFocusTrap({
+ isActive: layer.isOpen,
+ onEscape: layer.hide,
+ });
+
+ // Auto-focus first element when popover opens
+ useEffect(() => {
+ if (layer.isOpen && hasAutoFocus) {
+ // Use requestAnimationFrame to ensure DOM is ready
+ requestAnimationFrame(() => {
+ focusFirst();
+ });
+ }
+ }, [layer.isOpen, hasAutoFocus, focusFirst]);
+
+ // Reset close button focus state when popover closes
+ useEffect(() => {
+ if (!layer.isOpen) {
+ setIsCloseButtonFocused(false);
+ }
+ }, [layer.isOpen]);
+
+ // Combined ref for trigger element (layer anchor + our ref)
+ const triggerRef = useCallback(
+ (el: HTMLElement | null) => {
+ triggerElementRef.current = el;
+ layer.ref(el);
+ },
+ [layer],
+ );
+
+ // Toggle function
+ const toggle = useCallback(() => {
+ if (layer.isOpen) {
+ layer.hide();
+ } else {
+ layer.show();
+ }
+ }, [layer]);
+
+ // ARIA attributes for the trigger
+ const triggerProps = {
+ 'aria-haspopup': 'dialog' as const,
+ 'aria-expanded': layer.isOpen,
+ 'aria-controls': layer.id,
+ };
+
+ // Wrapped render function that includes optional hidden close button
+ const render = useCallback(
+ (children: ReactNode, props?: ContextRenderProps) => {
+ return layer.render(
+ <div
+ ref={contentRef as React.RefObject<HTMLDivElement>}
+ role="dialog"
+ aria-modal="true"
+ aria-label={dialogLabel}
+ {...stylex.props(styles.contentWrapper)}>
+ {children}
+ {hasCloseButton && (
+ <button
+ type="button"
+ onClick={layer.hide}
+ onFocus={() => setIsCloseButtonFocused(true)}
+ onBlur={() => setIsCloseButtonFocused(false)}
+ aria-label={closeButtonLabel}
+ {...stylex.props(
+ styles.closeButton,
+ isCloseButtonFocused && styles.closeButtonFocused,
+ )}>
+ {closeButtonLabel}
+ </button>
+ )}
+ </div>,
+ props,
+ );
+ },
+ [
+ layer,
+ hasCloseButton,
+ closeButtonLabel,
+ isCloseButtonFocused,
+ contentRef,
+ dialogLabel,
+ ],
+ );
+
+ return {
+ triggerRef,
+ contentRef,
+ anchorId: layer.anchorId,
+ show: layer.show,
+ hide: layer.hide,
+ toggle,
+ isOpen: layer.isOpen,
+ id: layer.id,
+ render,
+ triggerProps,
+ };
+}
+
+// Re-export types for convenience
+export type {LayerPlacement, LayerAlignment, ContextRenderProps};
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 6eaf9bbe3e..545f9ba407 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -7,5 +7,8 @@
* SYNC: When modified, update this header
*/
-// Hooks will be added here as needed
-export {};
+export {useFocusTrap} from './useFocusTrap';
+export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';
+
+export {useGridFocus} from './useGridFocus';
+export type {UseGridFocusOptions, UseGridFocusReturn} from './useGridFocus';
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
new file mode 100644
index 0000000000..6d085f0c0f
--- /dev/null
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -0,0 +1,239 @@
+/**
+ * @file useFocusTrap.ts
+ * @input Uses React useCallback, useEffect, useRef
+ * @output Exports useFocusTrap hook for trapping focus within a container
+ * @position Core hook; used by dialogs, modals, date pickers
+ *
+ * Based on WAI-ARIA dialog pattern:
+ * https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ */
+
+import {useCallback, useEffect, useRef} from 'react';
+
+/**
+ * Selector for commonly focusable elements.
+ */
+const FOCUSABLE_SELECTOR =
+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])';
+
+/**
+ * Get all focusable elements within a container.
+ */
+function getFocusableElements(container: HTMLElement): HTMLElement[] {
+ return Array.from(
+ container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
+ );
+}
+
+/**
+ * Attempt to focus an element. Returns true if focus was successful.
+ */
+function attemptFocus(element: HTMLElement): boolean {
+ try {
+ element.focus();
+ } catch {
+ // Some elements may throw on focus
+ }
+ return document.activeElement === element;
+}
+
+/**
+ * Focus the first focusable descendant of a container.
+ * Returns true if a focusable element was found and focused.
+ */
+function focusFirstDescendant(container: HTMLElement): boolean {
+ const focusable = getFocusableElements(container);
+ for (const element of focusable) {
+ if (attemptFocus(element)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Focus the last focusable descendant of a container.
+ * Returns true if a focusable element was found and focused.
+ */
+function focusLastDescendant(container: HTMLElement): boolean {
+ const focusable = getFocusableElements(container);
+ for (let i = focusable.length - 1; i >= 0; i--) {
+ if (attemptFocus(focusable[i])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Configuration for focus trap behavior
+ */
+export interface UseFocusTrapOptions {
+ /**
+ * Whether the focus trap is currently active.
+ */
+ isActive: boolean;
+
+ /**
+ * Callback when Escape key is pressed.
+ */
+ onEscape?: () => void;
+}
+
+/**
+ * Return type for useFocusTrap hook
+ */
+export interface UseFocusTrapReturn {
+ /**
+ * Ref to attach to the container element that should trap focus.
+ */
+ containerRef: React.RefObject<HTMLElement | null>;
+
+ /**
+ * Focus the first focusable element in the container.
+ */
+ focusFirst: () => void;
+}
+
+/**
+ * Hook for trapping focus within a container element.
+ *
+ * Implements the WAI-ARIA dialog focus trap pattern:
+ * - Listens to focus events on the document
+ * - Redirects focus back into the container if it escapes
+ * - Handles both Tab and Shift+Tab navigation
+ *
+ * @example
+ * ```tsx
+ * const {containerRef, focusFirst} = useFocusTrap({
+ * isActive: isOpen,
+ * onEscape: () => setIsOpen(false),
+ * });
+ *
+ * useEffect(() => {
+ * if (isOpen) focusFirst();
+ * }, [isOpen, focusFirst]);
+ *
+ * <div ref={containerRef}>
+ * <button>First</button>
+ * <button>Last</button>
+ * </div>
+ * ```
+ */
+export function useFocusTrap(options: UseFocusTrapOptions): UseFocusTrapReturn {
+ const {isActive, onEscape} = options;
+
+ const containerRef = useRef<HTMLElement | null>(null);
+ const lastFocusRef = useRef<Element | null>(null);
+ // Track if focus change was triggered by keyboard (Tab key)
+ const isKeyboardNavigationRef = useRef(false);
+
+ /**
+ * Focus the first focusable element.
+ */
+ const focusFirst = useCallback(() => {
+ if (containerRef.current) {
+ focusFirstDescendant(containerRef.current);
+ }
+ }, []);
+
+ /**
+ * Handle focus events - redirect focus back into container if it escapes.
+ * Only redirects for keyboard navigation, not mouse clicks.
+ */
+ useEffect(() => {
+ if (!isActive) return;
+
+ const handleFocus = (event: FocusEvent) => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const target = event.target as Node;
+
+ if (container.contains(target)) {
+ // Focus is inside the container - track it
+ lastFocusRef.current = target as Element;
+ } else if (isKeyboardNavigationRef.current) {
+ // Focus escaped via keyboard - redirect it back
+ focusFirstDescendant(container);
+
+ // If we're back at the same element (Shift+Tab from first element),
+ // try focusing the last element instead
+ if (lastFocusRef.current === document.activeElement) {
+ focusLastDescendant(container);
+ }
+
+ lastFocusRef.current = document.activeElement;
+ }
+ // If focus escaped via mouse click, don't redirect - let light dismiss handle it
+
+ // Reset keyboard navigation flag
+ isKeyboardNavigationRef.current = false;
+ };
+
+ // Use capture phase to intercept focus before it settles
+ document.addEventListener('focus', handleFocus, true);
+
+ return () => {
+ document.removeEventListener('focus', handleFocus, true);
+ };
+ }, [isActive]);
+
+ /**
+ * Handle Tab key to wrap focus at boundaries, and Escape to close.
+ * Also tracks that keyboard navigation is occurring.
+ */
+ useEffect(() => {
+ if (!isActive) return;
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ if (event.key === 'Escape' && onEscape) {
+ event.preventDefault();
+ onEscape();
+ return;
+ }
+
+ if (event.key === 'Tab') {
+ // Mark that keyboard navigation is happening
+ isKeyboardNavigationRef.current = true;
+
+ const focusable = getFocusableElements(container);
+ if (focusable.length === 0) return;
+
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+
+ if (event.shiftKey) {
+ // Shift+Tab: if on first element, wrap to last
+ if (document.activeElement === first) {
+ event.preventDefault();
+ last.focus();
+ }
+ } else {
+ // Tab: if on last element, wrap to first
+ if (document.activeElement === last) {
+ event.preventDefault();
+ first.focus();
+ }
+ }
+ }
+ };
+
+ document.addEventListener('keydown', handleKeyDown);
+
+ return () => {
+ document.removeEventListener('keydown', handleKeyDown);
+ };
+ }, [isActive, onEscape]);
+
+ return {
+ containerRef,
+ focusFirst,
+ };
+}
diff --git a/packages/core/src/hooks/useGridFocus.ts b/packages/core/src/hooks/useGridFocus.ts
new file mode 100644
index 0000000000..a7c64204db
--- /dev/null
+++ b/packages/core/src/hooks/useGridFocus.ts
@@ -0,0 +1,313 @@
+/**
+ * @file useGridFocus.ts
+ * @input Uses React useCallback, useRef
+ * @output Exports useGridFocus hook for grid keyboard navigation
+ * @position Core hook; used by XDSCalendar for date grid navigation
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ * - /packages/core/src/hooks/useGridFocus.test.ts
+ */
+
+import {useCallback, useRef} from 'react';
+
+/**
+ * Configuration for grid focus behavior
+ */
+export interface UseGridFocusOptions {
+ /**
+ * Number of columns in the grid.
+ * Used for up/down navigation (moves by this many cells).
+ */
+ columns: number;
+
+ /**
+ * Selector for focusable cells within the grid.
+ * @default 'button:not([disabled]), [tabindex]:not([tabindex="-1"])'
+ */
+ cellSelector?: string;
+
+ /**
+ * Callback when navigation would go before the first cell.
+ * Useful for navigating to previous month in calendars.
+ * @param column The column index (0-based) that was focused when navigating
+ * @param offset Number of cells to move (1 for horizontal, columns for vertical)
+ */
+ onNavigateBefore?: (column: number, offset: number) => void;
+
+ /**
+ * Callback when navigation would go after the last cell.
+ * Useful for navigating to next month in calendars.
+ * @param column The column index (0-based) that was focused when navigating
+ * @param offset Number of cells to move (1 for horizontal, columns for vertical)
+ */
+ onNavigateAfter?: (column: number, offset: number) => void;
+
+ /**
+ * Callback for Page Up key (e.g., previous month).
+ */
+ onPageUp?: () => void;
+
+ /**
+ * Callback for Page Down key (e.g., next month).
+ */
+ onPageDown?: () => void;
+}
+
+/**
+ * Return type for useGridFocus hook
+ */
+export interface UseGridFocusReturn {
+ /**
+ * Ref to attach to the grid container element.
+ */
+ gridRef: React.RefObject<HTMLElement>;
+
+ /**
+ * Key down handler to attach to the grid container.
+ */
+ handleKeyDown: (e: React.KeyboardEvent) => void;
+
+ /**
+ * Focus a specific cell by index.
+ */
+ focusCell: (index: number) => void;
+
+ /**
+ * Focus the first focusable cell.
+ */
+ focusFirst: () => void;
+
+ /**
+ * Focus the last focusable cell.
+ */
+ focusLast: () => void;
+}
+
+/**
+ * Hook for managing keyboard navigation within a grid.
+ *
+ * Implements WAI-ARIA grid pattern:
+ * - Arrow keys: Navigate between cells
+ * - Home: Move to first cell in row
+ * - End: Move to last cell in row
+ * - Ctrl+Home: Move to first cell in grid
+ * - Ctrl+End: Move to last cell in grid
+ * - Page Up/Down: Custom callbacks (e.g., month navigation)
+ *
+ * @example
+ * ```tsx
+ * const {gridRef, handleKeyDown} = useGridFocus({
+ * columns: 7,
+ * onPageUp: () => navigateMonth(-1),
+ * onPageDown: () => navigateMonth(1),
+ * });
+ *
+ * <div ref={gridRef} role="grid" onKeyDown={handleKeyDown}>
+ * {cells.map(cell => <button role="gridcell">{cell}</button>)}
+ * </div>
+ * ```
+ */
+export function useGridFocus(options: UseGridFocusOptions): UseGridFocusReturn {
+ const {
+ columns,
+ cellSelector = 'button:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ onNavigateBefore,
+ onNavigateAfter,
+ onPageUp,
+ onPageDown,
+ } = options;
+
+ const gridRef = useRef<HTMLElement>(null);
+
+ /**
+ * Get all focusable cells in the grid.
+ */
+ const getCells = useCallback((): HTMLElement[] => {
+ if (!gridRef.current) return [];
+ return Array.from(
+ gridRef.current.querySelectorAll<HTMLElement>(cellSelector),
+ );
+ }, [cellSelector]);
+
+ /**
+ * Get the currently focused cell index.
+ */
+ const getCurrentIndex = useCallback((): number => {
+ const cells = getCells();
+ const active = document.activeElement;
+ return cells.findIndex(
+ cell => cell === active || cell.contains(active as Node),
+ );
+ }, [getCells]);
+
+ /**
+ * Focus a cell by index, clamping to valid range.
+ * Returns true if focus was successful, false if navigation callback was triggered.
+ */
+ const focusCellInternal = useCallback(
+ (index: number, currentColumn: number, offset: number) => {
+ const cells = getCells();
+ if (cells.length === 0) return;
+
+ if (index < 0) {
+ onNavigateBefore?.(currentColumn, offset);
+ return;
+ }
+ if (index >= cells.length) {
+ onNavigateAfter?.(currentColumn, offset);
+ return;
+ }
+
+ cells[index]?.focus();
+ },
+ [getCells, onNavigateBefore, onNavigateAfter],
+ );
+
+ /**
+ * Public focusCell that doesn't trigger navigation callbacks
+ */
+ const focusCell = useCallback(
+ (index: number) => {
+ const cells = getCells();
+ if (cells.length === 0) return;
+ const clampedIndex = Math.max(0, Math.min(index, cells.length - 1));
+ cells[clampedIndex]?.focus();
+ },
+ [getCells],
+ );
+
+ /**
+ * Focus the first cell.
+ */
+ const focusFirst = useCallback(() => {
+ const cells = getCells();
+ cells[0]?.focus();
+ }, [getCells]);
+
+ /**
+ * Focus the last cell.
+ */
+ const focusLast = useCallback(() => {
+ const cells = getCells();
+ cells[cells.length - 1]?.focus();
+ }, [getCells]);
+
+ /**
+ * Handle keyboard navigation.
+ */
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ const currentIndex = getCurrentIndex();
+ if (currentIndex === -1) return;
+
+ const cells = getCells();
+ const currentRow = Math.floor(currentIndex / columns);
+ const currentCol = currentIndex % columns;
+ const totalRows = Math.ceil(cells.length / columns);
+
+ let handled = true;
+
+ switch (e.key) {
+ case 'ArrowRight':
+ // Horizontal navigation: offset = 1
+ focusCellInternal(currentIndex + 1, (currentCol + 1) % columns, 1);
+ break;
+
+ case 'ArrowLeft':
+ // Horizontal navigation: offset = 1
+ focusCellInternal(
+ currentIndex - 1,
+ currentCol === 0 ? columns - 1 : currentCol - 1,
+ 1,
+ );
+ break;
+
+ case 'ArrowDown':
+ // Vertical navigation: offset = columns (7 for calendar)
+ if (currentRow < totalRows - 1) {
+ const nextIndex = currentIndex + columns;
+ if (nextIndex < cells.length) {
+ focusCellInternal(nextIndex, currentCol, columns);
+ } else {
+ // Last row might be partial, focus last cell
+ focusCellInternal(cells.length - 1, currentCol, columns);
+ }
+ } else {
+ onNavigateAfter?.(currentCol, columns);
+ }
+ break;
+
+ case 'ArrowUp':
+ // Vertical navigation: offset = columns (7 for calendar)
+ if (currentRow > 0) {
+ focusCellInternal(currentIndex - columns, currentCol, columns);
+ } else {
+ onNavigateBefore?.(currentCol, columns);
+ }
+ break;
+
+ case 'Home':
+ if (e.ctrlKey || e.metaKey) {
+ // Ctrl+Home: first cell in grid
+ focusFirst();
+ } else {
+ // Home: first cell in current row
+ focusCell(currentRow * columns);
+ }
+ break;
+
+ case 'End':
+ if (e.ctrlKey || e.metaKey) {
+ // Ctrl+End: last cell in grid
+ focusLast();
+ } else {
+ // End: last cell in current row
+ const rowEnd = Math.min(
+ (currentRow + 1) * columns - 1,
+ cells.length - 1,
+ );
+ focusCell(rowEnd);
+ }
+ break;
+
+ case 'PageUp':
+ onPageUp?.();
+ break;
+
+ case 'PageDown':
+ onPageDown?.();
+ break;
+
+ default:
+ handled = false;
+ }
+
+ if (handled) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ },
+ [
+ columns,
+ focusCell,
+ focusCellInternal,
+ focusFirst,
+ focusLast,
+ getCells,
+ getCurrentIndex,
+ onNavigateAfter,
+ onNavigateBefore,
+ onPageDown,
+ onPageUp,
+ ],
+ );
+
+ return {
+ gridRef,
+ handleKeyDown,
+ focusCell,
+ focusFirst,
+ focusLast,
+ };
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 26b467bdb4..f85988103a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -12,6 +12,7 @@ export * from './Avatar';
export * from './Button';
export * from './Calendar';
export * from './CheckboxInput';
+export * from './DatePicker';
export * from './Field';
export * from './Icon';
export * from './Text';
@@ -30,5 +31,8 @@ export * from './Skeleton';
// Hooks
export * from './hooks';
+// Utilities
+export * from './utils';
+
// Theme
export * from './theme';
diff --git a/packages/core/src/utils/dateParser.test.ts b/packages/core/src/utils/dateParser.test.ts
new file mode 100644
index 0000000000..3311a2792a
--- /dev/null
+++ b/packages/core/src/utils/dateParser.test.ts
@@ -0,0 +1,162 @@
+/**
+ * @file dateParser.test.ts
+ * @input Uses vitest, dateParser utilities
+ * @output Unit tests for date parsing utilities
+ * @position Testing; validates dateParser.ts implementation
+ *
+ * SYNC: When dateParser.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ parseDateInput,
+ formatDisplayDate,
+ dateToISO,
+ parseISO,
+} from './dateParser';
+
+describe('parseDateInput', () => {
+ describe('ISO format (YYYY-MM-DD)', () => {
+ it('parses valid ISO date', () => {
+ expect(parseDateInput('2026-01-25')).toBe('2026-01-25');
+ });
+
+ it('parses ISO date with single-digit month/day', () => {
+ expect(parseDateInput('2026-1-5')).toBe('2026-01-05');
+ });
+
+ it('returns null for invalid ISO date', () => {
+ expect(parseDateInput('2026-13-25')).toBeNull();
+ expect(parseDateInput('2026-02-30')).toBeNull();
+ });
+ });
+
+ describe('full month name formats', () => {
+ it('parses "January 25, 2026"', () => {
+ expect(parseDateInput('January 25, 2026')).toBe('2026-01-25');
+ });
+
+ it('parses "Jan 25, 2026"', () => {
+ expect(parseDateInput('Jan 25, 2026')).toBe('2026-01-25');
+ });
+
+ it('parses "25 January 2026"', () => {
+ expect(parseDateInput('25 January 2026')).toBe('2026-01-25');
+ });
+
+ it('parses "25 Jan 2026"', () => {
+ expect(parseDateInput('25 Jan 2026')).toBe('2026-01-25');
+ });
+
+ it('parses without comma', () => {
+ expect(parseDateInput('January 25 2026')).toBe('2026-01-25');
+ });
+
+ it('handles case insensitive month names', () => {
+ expect(parseDateInput('JANUARY 25, 2026')).toBe('2026-01-25');
+ expect(parseDateInput('january 25, 2026')).toBe('2026-01-25');
+ });
+
+ it('parses all month names', () => {
+ expect(parseDateInput('February 1, 2026')).toBe('2026-02-01');
+ expect(parseDateInput('March 1, 2026')).toBe('2026-03-01');
+ expect(parseDateInput('April 1, 2026')).toBe('2026-04-01');
+ expect(parseDateInput('May 1, 2026')).toBe('2026-05-01');
+ expect(parseDateInput('June 1, 2026')).toBe('2026-06-01');
+ expect(parseDateInput('July 1, 2026')).toBe('2026-07-01');
+ expect(parseDateInput('August 1, 2026')).toBe('2026-08-01');
+ expect(parseDateInput('September 1, 2026')).toBe('2026-09-01');
+ expect(parseDateInput('October 1, 2026')).toBe('2026-10-01');
+ expect(parseDateInput('November 1, 2026')).toBe('2026-11-01');
+ expect(parseDateInput('December 1, 2026')).toBe('2026-12-01');
+ });
+
+ it('parses abbreviated month names', () => {
+ expect(parseDateInput('Feb 1, 2026')).toBe('2026-02-01');
+ expect(parseDateInput('Sep 1, 2026')).toBe('2026-09-01');
+ expect(parseDateInput('Sept 1, 2026')).toBe('2026-09-01');
+ });
+ });
+
+ describe('numeric formats with heuristics', () => {
+ it('detects day when first number > 12', () => {
+ expect(parseDateInput('25/1/2026')).toBe('2026-01-25');
+ expect(parseDateInput('31-12-2026')).toBe('2026-12-31');
+ });
+
+ it('detects day when second number > 12', () => {
+ expect(parseDateInput('1/25/2026')).toBe('2026-01-25');
+ expect(parseDateInput('12-31-2026')).toBe('2026-12-31');
+ });
+
+ it('returns null when both numbers > 12', () => {
+ expect(parseDateInput('25/31/2026')).toBeNull();
+ });
+
+ it('validates day/month ranges', () => {
+ expect(parseDateInput('0/15/2026')).toBeNull();
+ expect(parseDateInput('15/0/2026')).toBeNull();
+ });
+ });
+
+ describe('edge cases', () => {
+ it('returns null for empty string', () => {
+ expect(parseDateInput('')).toBeNull();
+ });
+
+ it('returns null for whitespace only', () => {
+ expect(parseDateInput(' ')).toBeNull();
+ });
+
+ it('trims whitespace', () => {
+ expect(parseDateInput(' 2026-01-25 ')).toBe('2026-01-25');
+ });
+
+ it('returns null for completely invalid strings', () => {
+ expect(parseDateInput('not a date')).toBeNull();
+ expect(parseDateInput('abc xyz')).toBeNull();
+ });
+
+ it('validates February dates', () => {
+ expect(parseDateInput('February 29, 2024')).toBe('2024-02-29'); // Leap year
+ expect(parseDateInput('February 29, 2025')).toBeNull(); // Not a leap year
+ expect(parseDateInput('February 30, 2024')).toBeNull();
+ });
+ });
+});
+
+describe('formatDisplayDate', () => {
+ it('formats ISO date to readable format', () => {
+ expect(formatDisplayDate('2026-01-25')).toBe('January 25, 2026');
+ });
+
+ it('formats single-digit dates correctly', () => {
+ expect(formatDisplayDate('2026-01-05')).toBe('January 5, 2026');
+ });
+
+ it('formats all months correctly', () => {
+ expect(formatDisplayDate('2026-02-15')).toBe('February 15, 2026');
+ expect(formatDisplayDate('2026-12-25')).toBe('December 25, 2026');
+ });
+});
+
+describe('dateToISO', () => {
+ it('converts Date object to ISO string', () => {
+ const date = new Date(2026, 0, 25); // January 25, 2026
+ expect(dateToISO(date)).toBe('2026-01-25');
+ });
+
+ it('pads single-digit month and day', () => {
+ const date = new Date(2026, 0, 5); // January 5, 2026
+ expect(dateToISO(date)).toBe('2026-01-05');
+ });
+});
+
+describe('parseISO', () => {
+ it('parses ISO string to Date object', () => {
+ const date = parseISO('2026-01-25');
+ expect(date.getFullYear()).toBe(2026);
+ expect(date.getMonth()).toBe(0); // January
+ expect(date.getDate()).toBe(25);
+ });
+});
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
new file mode 100644
index 0000000000..21e367a88b
--- /dev/null
+++ b/packages/core/src/utils/dateParser.ts
@@ -0,0 +1,219 @@
+/**
+ * @file dateParser.ts
+ * @input Uses Intl.DateTimeFormat for locale detection
+ * @output Exports date parsing utilities for user input
+ * @position Core utility; used by XDSDatePicker
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/utils/dateParser.test.ts
+ * - /packages/core/src/utils/index.ts
+ */
+
+import type {ISODateString} from '../Calendar';
+
+/**
+ * Detects if the user's locale uses day-first date format (DD/MM/YYYY).
+ * US and a few others use month-first (MM/DD/YYYY).
+ */
+export function isLocaleDayFirst(): boolean {
+ const parts = new Intl.DateTimeFormat().formatToParts(new Date(2000, 0, 15));
+ const dayIndex = parts.findIndex(p => p.type === 'day');
+ const monthIndex = parts.findIndex(p => p.type === 'month');
+ return dayIndex < monthIndex;
+}
+
+/**
+ * Parses user input into an ISO date string.
+ *
+ * Supports:
+ * - ISO format: "2026-01-25"
+ * - Full month names: "January 25, 2026", "25 January 2026"
+ * - Numeric formats: "1/25/2026", "25/1/2026" (locale-aware with heuristics)
+ *
+ * For ambiguous numeric formats (both numbers ≤ 12), uses locale preference.
+ *
+ * @returns ISODateString if valid, null if unparseable
+ */
+export function parseDateInput(input: string): ISODateString | null {
+ const trimmed = input.trim();
+ if (!trimmed) return null;
+
+ // 1. Try ISO format first (YYYY-MM-DD) - always unambiguous
+ const isoMatch = trimmed.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
+ if (isoMatch) {
+ const [, year, month, day] = isoMatch;
+ return createISODate(+year, +month, +day);
+ }
+
+ // 2. Try full month name formats
+ // "January 25, 2026" or "Jan 25, 2026"
+ const monthFirstMatch = trimmed.match(
+ /^([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})$/,
+ );
+ if (monthFirstMatch) {
+ const [, monthName, day, year] = monthFirstMatch;
+ const month = parseMonthName(monthName);
+ if (month !== null) {
+ return createISODate(+year, month, +day);
+ }
+ }
+
+ // "25 January 2026" or "25 Jan 2026"
+ const dayFirstMatch = trimmed.match(/^(\d{1,2})\s+([A-Za-z]+),?\s+(\d{4})$/);
+ if (dayFirstMatch) {
+ const [, day, monthName, year] = dayFirstMatch;
+ const month = parseMonthName(monthName);
+ if (month !== null) {
+ return createISODate(+year, month, +day);
+ }
+ }
+
+ // 3. Try numeric formats with separators (/, -, .)
+ const numericMatch = trimmed.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/);
+ if (numericMatch) {
+ const [, first, second, year] = numericMatch;
+ return parseNumericDate(+first, +second, +year);
+ }
+
+ // 4. Fall back to native Date parsing for other formats
+ const parsed = new Date(trimmed);
+ if (!isNaN(parsed.getTime())) {
+ return dateToISO(parsed);
+ }
+
+ return null;
+}
+
+/**
+ * Parses ambiguous numeric dates using heuristics and locale.
+ *
+ * Heuristics:
+ * - If first > 12, it must be the day (e.g., 25/1/2026 → Jan 25)
+ * - If second > 12, it must be the day (e.g., 1/25/2026 → Jan 25)
+ * - If both ≤ 12, use locale preference (day-first vs month-first)
+ */
+function parseNumericDate(
+ first: number,
+ second: number,
+ year: number,
+): ISODateString | null {
+ let day: number;
+ let month: number;
+
+ if (first > 12 && second <= 12) {
+ // First must be day (e.g., 25/1/2026)
+ day = first;
+ month = second;
+ } else if (second > 12 && first <= 12) {
+ // Second must be day (e.g., 1/25/2026)
+ month = first;
+ day = second;
+ } else if (first > 12 && second > 12) {
+ // Both > 12 is invalid
+ return null;
+ } else {
+ // Both ≤ 12: ambiguous, use locale preference
+ if (isLocaleDayFirst()) {
+ day = first;
+ month = second;
+ } else {
+ month = first;
+ day = second;
+ }
+ }
+
+ return createISODate(year, month, day);
+}
+
+/**
+ * Parses month name (full or abbreviated) to 1-12.
+ */
+function parseMonthName(name: string): number | null {
+ const months: Record<string, number> = {
+ january: 1,
+ jan: 1,
+ february: 2,
+ feb: 2,
+ march: 3,
+ mar: 3,
+ april: 4,
+ apr: 4,
+ may: 5,
+ june: 6,
+ jun: 6,
+ july: 7,
+ jul: 7,
+ august: 8,
+ aug: 8,
+ september: 9,
+ sep: 9,
+ sept: 9,
+ october: 10,
+ oct: 10,
+ november: 11,
+ nov: 11,
+ december: 12,
+ dec: 12,
+ };
+ return months[name.toLowerCase()] ?? null;
+}
+
+/**
+ * Creates an ISO date string, validating the date is real.
+ */
+function createISODate(
+ year: number,
+ month: number,
+ day: number,
+): ISODateString | null {
+ if (month < 1 || month > 12 || day < 1 || day > 31) {
+ return null;
+ }
+
+ const date = new Date(year, month - 1, day);
+
+ // Validate the date didn't overflow (e.g., Feb 30 → Mar 2)
+ if (
+ date.getFullYear() !== year ||
+ date.getMonth() !== month - 1 ||
+ date.getDate() !== day
+ ) {
+ return null;
+ }
+
+ return dateToISO(date);
+}
+
+/**
+ * Converts a Date object to ISO date string.
+ */
+export function dateToISO(date: Date): ISODateString {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}` as ISODateString;
+}
+
+/**
+ * Parses an ISO date string into a Date object.
+ */
+export function parseISO(iso: ISODateString): Date {
+ const [year, month, day] = iso.split('-').map(Number);
+ return new Date(year, month - 1, day);
+}
+
+/**
+ * Formats an ISO date string for display.
+ * Uses locale-aware formatting with full month name.
+ *
+ * @example
+ * formatDisplayDate("2026-01-25") // "January 25, 2026"
+ */
+export function formatDisplayDate(iso: ISODateString): string {
+ const date = parseISO(iso);
+ return new Intl.DateTimeFormat('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ }).format(date);
+}
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
new file mode 100644
index 0000000000..dd1f7096d4
--- /dev/null
+++ b/packages/core/src/utils/index.ts
@@ -0,0 +1,14 @@
+/**
+ * @file index.ts
+ * @input Utils module exports
+ * @output Re-exports all utility functions
+ * @position Package entry point for utils
+ */
+
+export {
+ parseDateInput,
+ formatDisplayDate,
+ dateToISO,
+ parseISO,
+ isLocaleDayFirst,
+} from './dateParser';